<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <!-- 计划名称 -->
      <el-form-item :label="$t('administration.ProjectName')">
        <el-input
          v-model="queryParams.taskName"
          :placeholder="
            $t('share.PleaseEnter') + ' ' + $t('administration.ProjectName')
          "
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 区域名称 -->
      <el-form-item :label="$t('administration.RegionName')">
        <el-input
          v-model="queryParams.areaName"
          :placeholder="
            $t('share.PleaseEnter') + ' ' + $t('administration.RegionName')
          "
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 状态 -->
      <el-form-item :label="$t('share.status')" prop="status">
        <el-select
          v-model="queryParams.isenable"
          :placeholder="$t('share.status')"
          clearable
          style="width: 240px"
        >
          <el-option :label="$t('share.On')" value="0"></el-option>
          <el-option :label="$t('share.Off')" value="1"></el-option>
        </el-select>
      </el-form-item>
      <!-- 计划有效期 -->
      <el-form-item :label="$t('administration.PlanValidityPeriod')">
        <el-date-picker
          v-model="queryParams.cycleStartTime"
          type="date"
          :placeholder="$t('share.StartTime')"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
        -
        <el-date-picker
          v-model="queryParams.cycleEndTime"
          type="date"
          :placeholder="$t('share.EndTime')"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <!-- 创建时间 -->
      <el-form-item :label="$t('share.CreationTime')">
        <el-date-picker
          v-model="queryParams.beginTime"
          type="date"
          :placeholder="$t('share.StartTime')"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
        -
        <el-date-picker
          v-model="queryParams.endTime"
          type="date"
          :placeholder="$t('share.EndTime')"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >{{ $t("share.search") }}</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("share.reset")
        }}</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!-- 新增 -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >{{ $t("share.new") }}</el-button
        >
      </el-col>
      <!-- 删除 -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDeleteAll"
          >{{ $t("share.delete") }}</el-button
        >
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- 计划名称 -->
      <el-table-column
        :label="$t('administration.ProjectName')"
        prop="taskName"
      />
      <!-- 计划有效期开始时间 -->
      <el-table-column
        :label="$t('administration.PlanValidityPeriod') + $t('share.StartTime')"
        prop="cycleStartTime"
        :show-overflow-tooltip="true"
        min-width="100px"
      />
      <!-- 计划有效期结束时间 -->
      <el-table-column
        :label="$t('administration.PlanValidityPeriod') + $t('share.EndTime')"
        prop="cycleEndTime"
        :show-overflow-tooltip="true"
        min-width="100px"
      />
      <!-- 创建时间 -->
      <el-table-column :label="$t('share.CreationTime')" prop="createTime" />
      <!-- 区域时间 -->
      <el-table-column
        :label="$t('administration.RegionName')"
        prop="areaName"
      />
      <!-- 任务策略 -->
      <el-table-column
        :label="$t('administration.TaskStrategy')"
        prop="executionStatus"
        :formatter="stateFormat"
      />
      <!-- 执行任务周期 -->
      <el-table-column
        :label="$t('administration.ExecutionTaskCycle')"
        prop="taskCycle"
        :formatter="stateTask"
      />
      <!-- 状态 -->
      <el-table-column :label="$t('share.status')" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isenable"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column
        :label="$t('share.operate')"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <!-- 立即执行 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleImmediateExecution(scope.row.taskId)"
            >{{ $t("administration.ImmediateExecution") }}</el-button
          >
          <!-- 下发 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleIssue(scope.row.taskId)"
            >{{ $t("administration.issue") }}</el-button
          >
          <!-- 复制任务 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCopy(scope.row)"
            >{{ $t("administration.ReplicationTask") }}</el-button
          >
          <!-- 编辑 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="editClick(scope.row)"
            >{{ $t("share.edit") }}</el-button
          >
          <!-- 删除 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row.taskId)"
            >{{ $t("share.delete") }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="init"
    />

    <!-- 复制弹框 -->
    <el-dialog
      :title="$t('administration.CopyTask')"
      :visible.sync="copyDialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-time-picker
        v-model="copyTask.time"
        format="HH:mm:ss"
        value-format="HH:mm:ss"
        :placeholder="$t('share.PleaseChoose') + $t('administration.time')"
      >
      </el-time-picker>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="copyOk()">{{
          $t("administration.Copy")
        }}</el-button>
      </span>
    </el-dialog>

    <!-- 新增弹框 -->
    <el-dialog
      title="新建方案"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :visible.sync="addShow"
      width="1200px"
      custom-class="card-dialog card-page"
    >
      <newTask
        @hideDialog="addShow = false"
        v-if="addShow"
        @addSuccess="addSuccess"
      >
      </newTask>
    </el-dialog>
    <!-- 编辑任务 -->
    <el-dialog
      title="编辑任务"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :visible.sync="editShow"
      width="1200px"
      custom-class="card-dialog card-page"
    >
      <editTask
        @hideDialog="editShow = false"
        :editid="editid"
        @editSuccess="editSuccess"
        v-if="editShow"
      >
      </editTask>
    </el-dialog>
  </div>
</template>

<script>
import {
  getList,
  getChangeStatus,
  postRemove,
  getPatroltypeList,
  getAreaList,
  getProDeviceTreeSelect,
  getTreeProMainDevicePatrolEquSelect,
  getCopyTask,
  getControlChange,
  getTaskIsSue,
} from "@/api/administration";
import TreeSelect from "@riophae/vue-treeselect";
import newTask from "./new_task";
import editTask from "./edit_task";
export default {
  components: { newTask,editTask },
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: "",
        cycleStartTime: "",
        cycleEndTime: "",
        areaName: "",
        isenable: "",
        beginTime: "",
        endTime: "",
      },
      total: 0,
      loading: true,
      dataList: [],
      // 选中数组
      ids: [],
      title: "新增",
      dialogTableVisible: false,
      active: 0,
      patroltype: [],
      dialogForm: {
        areaIdS: [],
        executionMode: [],
        executionStatus: 1,
      },
      areaIdS: [],
      treeData: [],
      setUpAreaIds: [],
      selectTreeData: [],
      selectTreeIds: [],
      pointSettingsTreeData: [],
      pointSettingsDefaultProps: {
        children: "children",
        label: "label",
      },
      defaultProps: {
        children: "children",
        label: "areaName",
      },
      rules: {},
      executionTimeButton: 1,
      executionTimeData: [{ day: "", time: "", id: Date.now() }],
      weekData: [
        { name: "周一", id: "0" },
        { name: "周二", id: "1" },
        { name: "周三", id: "2" },
        { name: "周四", id: "3" },
        { name: "周五", id: "4" },
        { name: "周六", id: "5" },
        { name: "周日", id: "6" },
      ],
      dialogTableVisibleStep: 0,
      transferData: [],
      transferValue: [],
      copyDialogVisible: false,
      rules: {
        taskName: [
          {
            required: true,
            message:
              this.$t("share.PleaseEnter") + this.$t("administration.name"),
            trigger: "blur",
          },
        ],
        priority: [
          {
            required: true,
            message:
              this.$t("share.PleaseChoose") +
              this.$t("administration.priority"),
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message:
              this.$t("share.PleaseChoose") +
              this.$t("administration.TaskType"),
            trigger: "blur",
          },
        ],
        executionMode: [
          {
            type: "array",
            required: true,
            message:
              this.$t("share.PleaseChoose") +
              this.$t("administration.TaskExecutionMethod"),
            trigger: "change",
          },
        ],
        areaIdS: [
          {
            type: "array",
            required: true,
            message:
              this.$t("share.PleaseChoose") +
              this.$t("administration.InspectionArea"),
            trigger: "change",
          },
        ],
        fixedStartTime: [
          {
            required: true,
            message:
              this.$t("share.PleaseChoose") +
              this.$t("administration.ExecutionDate"),
            trigger: "change",
          },
        ],
        proDeviceTreeSelect: [],
        isenable: [
          {
            required: true,
            message: this.$t("share.PleaseChoose") + this.$t("share.status"),
            trigger: "change",
          },
        ],
        PlanValidityPeriod: [
          {
            required: true,
            message:
              this.$t("share.PleaseChoose") +
              this.$t("administration.PlanValidityPeriod"),
            trigger: "change",
          },
        ],
        ExecutionTaskCycle: [
          {
            required: true,
            message:
              this.$t("share.PleaseChoose") +
              this.$t("administration.ExecutionTaskCycle"),
            trigger: "change",
          },
        ],
        ExecutionDate: [
          {
            required: true,
            message:
              this.$t("share.PleaseChoose") +
              this.$t("administration.ExecutionDate"),
            trigger: "change",
          },
        ],
        interval: [
          {
            required: true,
            message:
              this.$t("share.PleaseChoose") +
              this.$t("administration.interval"),
            trigger: "change",
          },
        ],
        executionTime: [
          {
            required: true,
            message:
              this.$t("share.PleaseChoose") +
              this.$t("administration.executionTime"),
            trigger: "change",
          },
        ],
        intervalType: [
          {
            required: true,
            message:
              this.$t("share.PleaseChoose") +
              this.$t("administration.intervalType"),
            trigger: "change",
          },
        ],
        quantity: [
          {
            required: true,
            message:
              this.$t("share.PleaseChoose") +
              this.$t("administration.quantity"),
            trigger: "change",
          },
        ],
      },
      copyTask: {
        taskId: null,
        time: null,
      },
      treeWatchInput: "",
      addShow: false,
      editShow: false,
      editid: "",
    };
  },
  watch: {
    treeWatchInput(val) {
      this.$refs.selectTree.filter(val);
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      getList(this.queryParams).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.loading = false;
          this.dataList = res.rows;
          this.total = res.total;
          this.$message({
            message: this.$t("prompt.success.queryWasSuccessful"),
            type: "success",
          });
        }
      });
    },
    // 查询
    handleQuery() {
      this.init();
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.init();
    },
    addSuccess() {
      this.addShow = false;
      this.$modal.msgSuccess("添加成功");
      this.init();
    },
    editSuccess() {
      this.editShow = false;
      this.init();
    },
    stateFormat(row, column) {
      if (row.executionStatus == 0) {
        return "立即执行";
      } else if (row.executionStatus == 1) {
        return "周期执行";
      } else if (row.executionStatus == 2) {
        return "定时执行";
      } else if (row.executionStatus == 3) {
        return "已执行";
      } else if (row.executionStatus == 4) {
        return "间隔执行";
      }
    },
    stateTask(row, column) {
      if (row.executionStatus == 1) {
        if (row.taskCycle == 0) {
          return "按月";
        } else if (row.taskCycle == 1) {
          return "按周";
        }
        return "";
      }
    },
    handleStatusChange(row) {
      let data = {
        taskId: row.taskId,
        isenable: row.isenable,
      };
      getChangeStatus(data).then((res) => {
        if (res.code == 200) {
          this.init();
        }
      });
    },
    // 新增
    // handleAdd() {
    //   this.dialogTableVisible = true;
    //   getPatroltypeList().then((res) => {
    //     if (res.code == 200) {
    //       this.patroltype = res.rows;
    //     }
    //   });
    //   getAreaList().then((res) => {
    //     if (res.code == 200) {
    //       let tree = this.dialogTree(res.data);
    //       this.treeData = tree;
    //     }
    //   });
    // },
    handleAdd() {
      this.addShow = true;
    },
    // 弹框tree扁平转树结构
    dialogTree(list) {
      var map = {},
        node,
        tree = [];
      for (let i = 0; i < list.length; i++) {
        map[list[i].areaId] = list[i];
        list[i].children = [];
      }
      for (let i = 0; i < list.length; i += 1) {
        list[i];
        if (list[i].parentId !== 0) {
          // 不是根节点
          map[list[i].parentId].children.push(list[i]); // 放到父节点的children里
        } else {
          // 是根节点
          tree.push(list[i]); // 根节点计入结果数组
        }
      }
      return tree;
    },
    // 多选删除
    handleDeleteAll() {
      if (this.ids.length <= 0) {
        this.$message({
          message: this.$t("prompt.error.delete_Data"),
          type: "warning",
        });
        return;
      } else {
        console.log(this.ids.toString());
        postRemove(this.ids.toString()).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: this.$t("prompt.success.queryWasSuccessful"),
              type: "success",
            });
            this.init();
          } else {
            this.$message({
              message: res.msg,
              type: "warning",
            });
          }
        });
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.taskId);
    },
    handleDelete(taskId) {
      postRemove(taskId).then((res) => {
        if (res.code == 200) {
          this.init();
        }
      });
    },
    cancel() {
      this.dialogTableVisible = false;
      this.dialogForm = {};
    },

    // 弹框tree树选择
    handleCheckChange(data) {
      let idArr = [];
      if (idArr.indexOf(data.areaId) > -1) {
        idArr.splice(idArr.indexOf(data.areaId), 1);
      } else {
        idArr.push(data.areaId);
      }
      return idArr;
    },
    // 设置计划对象弹框选择
    setUpHandleCheckChange(data) {
      var parentIds = this.$refs.tree.getHalfCheckedKeys();
      var childsIds = this.$refs.tree.getCheckedKeys();
      let treeIds = parentIds.concat(childsIds);
      this.dialogForm.areaIdS = treeIds;

      return;
      this.dialogForm.areaIdS = this.handleCheckChange(treeIds);
      console.log(this.dialogForm.areaIdS);
    },
    // 弹框选择巡检对象 tree树选择
    selectTreeHandleCheckChange(data) {
      // this.selectTreeIds = this.handleCheckChange(data);
      let res = this.$refs.selectTree.getCheckedNodes();
      let arrDeptId = [];
      res.forEach((item) => {
        arrDeptId.push(item.areaId);
      });
      this.transferData = this.proDeviceTreeSelect.filter((item) =>
        arrDeptId.some((ele) => ele === item.areaId)
      );
    },
    // 点位设置数
    pointSettingsTreeDataHandleCheckChange() {
      let res = this.$refs.pointSettingsTree.getCheckedNodes();
      console.log(res);
    },
    // 弹框下一步
    submitForm(type) {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          console.log(this.dialogForm);
          // this.dialogForm.executionMode = 0;
          if (type == 0) {
            this.active = 1;
            this.dialogTableVisibleStep = 1;
            let areaIdS = JSON.parse(JSON.stringify(this.dialogForm.areaIdS));
            // areaIdS.push(1);
            getAreaList(areaIdS.join(","), 1).then((res) => {
              if (res.code == 200) {
                let tree = this.dialogTree(res.data);
                this.selectTreeData = tree;
              }
            });
            getProDeviceTreeSelect(areaIdS.join(",")).then((res) => {
              if (res.code == 200) {
                this.proDeviceTreeSelect = res.data;
              }
            });
          }
          if (type == 1 && this.transferValue) {
            this.active = 2;
            this.dialogTableVisibleStep = 2;
            getTreeProMainDevicePatrolEquSelect(
              this.transferValue.join(",")
            ).then((res) => {
              console.log(res, 11111);
              this.pointSettingsTreeData = res.data;
            });
          }
          if (type == 2) {
            console.log(this.dialogForm);
          }
        }
      });
    },
    // 弹框上一步
    returnCancel(type) {
      this.active = type;
      this.dialogTableVisibleStep = type;
    },
    resetForm(formName) {
      this.dialogForm = {};
      this.$refs[formName].resetFields();
      this.dialogTableVisible = false;
    },
    // 添加任务执行时间输入框
    executionTimeBtn() {
      if (this.executionTimeData.length <= 6) {
        this.executionTimeData.push({ day: "", time: "", id: Date.now() });
      }
    },
    executionTimeDelet(row) {
      if (this.executionTimeData.length > 1) {
        this.executionTimeData = this.executionTimeData.filter(
          (item) => item.id != row.id
        );
        console.log(this.executionTimeData);
      }
    },
    // 复制任务
    handleCopy(row) {
      this.copyTask.taskId = row.taskId;
      this.copyDialogVisible = true;
    },
    // 编辑任务
    editClick(row) {
      this.editid = row.taskId;
       sessionStorage.setItem("reportLineId", JSON.stringify(this.editid));
       this.editShow = true;
    },
    handleClose() {
      this.copyDialogVisible = false;
    },
    // 复制任务确定
    copyOk() {
      console.log(this.copyTask.time);
      if (this.copyTask.time) {
        getCopyTask(this.copyTask).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: this.$t("prompt.success.taskCopySuccess"),
              type: "success",
            });
            this.init();
            this.copyDialogVisible = false;
          }
        });
      } else {
        this.$message.error(this.$t("prompt.error.PleaseSelectATime"));
      }
    },
    // 立即执行
    handleImmediateExecution(taskId) {
      getControlChange({ taskId }).then((res) => {
        console.log(res, 111111111);
        if (res.code == 200) {
          this.$message({
            message: this.$t("prompt.success.OperationSuccessful"),
            type: "success",
          });
        }
      });
    },
    // 任务下发
    handleIssue(taskId) {
      getTaskIsSue({ taskId }).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: this.$t("prompt.success.OperationSuccessful"),
            type: "success",
          });
        }
      });
    },
    // 第二部Tree过滤
    selectTreeDataWacth(value, data) {
      console.log(value, data, 11111111);
      if (!value) return true;
      return data.areaName.indexOf(value) !== -1;
    },
  },
};
</script>

<style lang="scss" scoped>
.cycle2 {
  padding: 10px;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
}
.dialogTableVisibleStep1 {
  display: flex;
  justify-content: space-around;
}
.dialogTableVisibleStep1-content {
  width: 30%;
  // height: 200px;
  .leftTotle {
    font-size: 20px;
    margin-bottom: 10px;
  }
  .el-input {
    width: 75%;
  }
}
</style>
