<template>
  <div class="rule-type">
    <DialogCom
      :title="id ? '编辑检查任务' : '新增检查任务'"
      :visible.sync="isShow"
      width="1500px"
    >
      <div class="page-body" v-loading="loading">
        <el-form
          :model="formData"
          :rules="formDataRules"
          size="small"
          ref="form"
          label-position="right"
          label-width="130px"
          label-prefix=":"
        >
          <el-row>
            <el-col :span="6">
              <el-form-item prop="planName" label="任务名称:">
                <el-input
                  :disabled="cannotEditName()"
                  v-model.trim="formData.planName"
                  :maxlength="50"
                  name="planName"
                  placeholder="请输入任务名称"
                  clearable
                  style="width: 217px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="checkType" label="任务类型:">
                <el-select
                  @change="changeData"
                  :disabled="cannotEdit()"
                  label="任务类型"
                  v-model="formData.checkType"
                  placeholder="请选择任务类型"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.check_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="planCycle" label="任务周期:">
                <el-select
                  :disabled="cannotEdit()"
                  prop="planCycle"
                  label="任务周期"
                  v-model="formData.planCycle"
                  placeholder="请选择任务周期"
                  clearable
                >
                  <el-option
                    v-for="item in dict.type.check_cycle"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>            
            <el-col :span="6">
              <el-form-item
                prop="startDate"
                label="开始时间:"
                v-if="formData.planCycle == 6"
              >
                <el-date-picker
                  :disabled="cannotEdit()"
                  v-model="formData.startDate"
                  style="width: 240px"
                  value-format="yyyy-MM-dd 00:00:00"
                  placeholder="请选择开始时间"
                  type="date"
                  :clearable="false"
                ></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item
                prop="endDate"
                label="结束时间:"
                v-if="formData.planCycle == 6"
              >
                <el-date-picker
                  :disabled="cannotEdit()"
                  v-model="formData.endDate"
                  style="width: 240px"
                  value-format="yyyy-MM-dd 23:59:59"
                  placeholder="请选择结束时间"
                  type="date"
                  :clearable="false"
                ></el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item prop="execOrgType" label="检查主体类型:">
                <el-select
                  :disabled="cannotEdit()"
                  @change="cleanExecOrgList"
                  prop="execOrgType"
                  label="机构类型"
                  v-model="formData.execOrgType"
                  placeholder="请选择机构类型"
                  clearable
                >
                  <el-option
                    v-for="item in  dict.type.sys_org_type"
                    :key="item.value"
                    :label="item.label"
                    :value="parseInt(item.value)"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- </el-row> -->
            <!-- <el-row> -->
            <el-col :span="6">
              <el-form-item prop="roleIds" label="检查人员:">
                <el-select
                  :disabled="cannotEdit()"
                  label="检查人员"
                  v-model="formData.roleIds"
                  placeholder="请选择用户角色"
                  multiple
                  filterable
                  @change="handleRolesChange"
                >
                  <el-option
                    v-for="item in planRoles"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="checkOrgTypes" label="受检机构类型:">
                <el-select
                  :disabled="cannotEdit()"
                  @change="cleanCheckOrgList"
                  prop="checkOrgTypes"
                  label="受检机构类型"
                  v-model="formData.checkOrgTypes"
                  placeholder="请选择机构类型"
                  clearable
                  multiple
                >
                  <el-option
                    v-for="item in orgTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="count" label="任务次数:">
                <el-input-number
                  style="margin-left: 10px"
                  v-model="formData.count"
                  controls-position="right"
                  @change="handleChange"
                  :min="parentCount"
                  :max="9"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item :span="6" prop="execOrgIds" label="检查主体">
                <org-tree-select
                  :disabled="cannotEdit()"
                  v-model="formData.execOrgIds"
                  :queryData="parseInt(formData.execOrgType)"
                  ref="execorgTreeSelect"
                  :enabledCheckOrgTypes="parseInt(formData.execOrgType)"
                  :disable="true"
                >
                </org-tree-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :span="6" prop="checkOrgIds" label="受检机构">
                <org-tree-select
                  :disabled="cannotEdit()"
                  v-model="formData.checkOrgIds"
                  :queryData="parseInt(formData.checkOrgType)"
                  ref="checkorgTreeSelect"
                  :enabledCheckOrgTypes="parseInt(formData.checkOrgType)"
                  :disable="true"
                >
                </org-tree-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6"> -->
            <!-- <el-form-item prop="planStatus" label="计划状态"> -->
            <!-- <el-select
                  label="计划状态"
                  v-model="formData.planStatus"
                  placeholder="请选择计划状态"
                  clearable
                >
                  <el-option
                    v-for="item in dict.type.check_status"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select> -->
            <!-- <el-switch
                  v-model="formData.planStatus"
                  active-value="1"
                  inactive-value="2"
                ></el-switch> -->
            <!-- </el-form-item> -->
            <!-- </el-col> -->
          </el-row>
          <el-form-item :span="6" prop="description" label="备注">
            <el-input
              :disabled="cannotEdit()"
              v-model="formData.description"
              :maxlength="255"
              clearable
            />
          </el-form-item>
        </el-form>
        <el-button @click="openSelect"  v-if="formData.id==null || formData.planOfOrgId == orgId"
          ><span class="requiredlabel">选择检查内容</span>
        </el-button>
        <el-button @click="deleteSelected"  v-if="formData.id==null || formData.planOfOrgId == orgId">批量删除</el-button>
        <el-table
          :data="tableData"
          style="width: 100%; margin-top: 15px"
          height="400px"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            :selectable="handleSelectable"
          ></el-table-column>
          <el-table-column label="是否扫描">
            <template v-slot="{ row }">
              <el-switch
                :disabled="!getshenglianshe(row)"
                v-model="row.pointScan"
                active-text="是"
                inactive-text="否"
              >
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column label="必完成项">
            <template v-slot="{ row }">
              <el-switch
                :disabled="!getshenglianshe(row)"
                v-model="row.required"
                active-text="是"
                inactive-text="否"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="ruleName"
            label="检查手册
          "
          >
          </el-table-column>
          <el-table-column prop="itemName" label="检查项"> </el-table-column>
          <el-table-column prop="pointName" label="检查内容" width="300px">
            <template slot-scope="scope">
              <pre>{{ scope.row.pointName }}</pre>
            </template>
          </el-table-column>
          <el-table-column v-if="false" prop="ofOrgId" label="所属机构id">
          </el-table-column>
          <el-table-column prop="areaName" label="检查区域"> </el-table-column>
          <el-table-column prop="businessType" label="数据来源" v-if="false">
            <template slot-scope="r">
              {{
                getLabel(dict.type.point_data_source, `${r.row.businessType}`)
              }}
            </template>
          </el-table-column>
          <el-table-column prop="areaName" label="操作">
            <template v-slot="{ row }">
              <el-button
                v-if="getshenglianshe(row) && (formData.Id==null || formData.planOfOrgId == orgId)"
                type="text"
                @click="removeRow(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="onHide">取消</el-button>
      </div>
    </DialogCom>
    <DialogSelect
      ref="DialogSelect"
      :defaultSelect="defaultSelect"
      :orgType="formData.checkOrgTypes"
      @select="onSelect"
    ></DialogSelect>
  </div>
</template>

<script>
import OrgTreeSelect from "@/components/orgTreeSelect";
import { mapGetters } from "vuex";
import orgDropDown from "@/components/orgTree/orgDropDown.vue";
import OrgTree from "@/components/orgTree";
import korgTree from "@/components/k-orgTree";
import * as api from "@/api/safetycheck/plan";
import { statusOptions } from "@/views/commonOption";
import { findAllRole, findRoleByType } from "@/api/system/role";
import { getLabel } from "@/views/commonOption";
import DialogSelect from "@/views/safetycheck/ruleManager/dialog.select.point.vue";
export default {
  dicts: [
    "sys_org_type",
    "check_type",
    "check_cycle",
    "check_status",
    "point_data_source",
  ],
  data() {
    return {
      loading: false,
      parentCount: 1,
      defaultSelect: [],
      selectedValues: [],
      planRoles: [],
      planName: null,
      planType: null,
      planCycle: null,
      planStatus: null,
      execOrgType: null,
      roleNames: null,
      planExec: null,
      defbuildTaskNow: false,
      count: 0,
      description: null,
      selectedRows: [],
      propItem: "",
      row: "",
      tableData: [],
      deptOptions: [],
      id: null,
      isShow: false,
      formData: this.reset(),
      formDataRules: {
        planName: [{ required: true, message: "请输入任务名称" }],
        checkType: [{ required: true, message: "请选择任务类型" }],
        planCycle: [{ required: true, message: "请选择任务周期" }],
        execOrgType: [{ required: true, message: "请选择检查主体类型" }],
        roleList: [{ required: true, message: "请选择检查人员" }],
        planExec: [{ required: true, message: "请选择计划时间" }],
        count: [{ required: true, message: "请选择任务次数" }],
        checkOrgTypes: [{ required: true, message: "请选择受检机构类型" }],
        roleIds: [{ required: true, message: "请选择检查人员" }],
        startDate:[{ required: true, message: "请选择开始时间" }],
        endDate:[{ required: true, message: "请选择结束时间" }]
      },
      statusOptions: statusOptions,
    };
  },
  props: {
    orgTypeOptions: {
      type: Array,
    },
    ruleTypeOptions: {
      type: Array,
    },
  },
  watch: {},
  computed: {
    ...mapGetters(["orgId", "orgName"]),
  },
  methods: {
    //选择计划类型修改联动框
    changeData() {
      //判断计划类型
      switch (this.formData.checkType) {
        //如果是  【定期检查】全省农信系统安全检查
        case "1":
          //周期
          this.formData.planCycle = "5";
          //机构类型
          this.formData.execOrgType = "1";
          this.getRolesByOrg();
          //角色
          this.formData.roleIds = ["116"];
          this.selectedValues = ["116"];
          //检查次数
          this.formData.count = 1;
          //检查内容
          this.tableData = null;
          break;
        //如果是  【定期检查】办事处辖区安全检查
        case "2":
          //周期
          this.formData.planCycle = "5";
          //机构类型
          this.formData.execOrgType = "2";
          this.getRolesByOrg();
          //角色
          this.formData.roleIds = ["118"];
          this.selectedValues = ["118"];
          //检查次数
          this.formData.count = 2;
          //检查内容
          this.tableData = null;
          break;
        //如果是  【定期检查】营业网点安全保卫检查
        case "3":
          //周期
          this.formData.planCycle = "2";
          //机构类型
          this.formData.execOrgType = "4";
          this.getRolesByOrg();
          //角色
          this.formData.roleIds = ["121"];
          this.selectedValues = ["121"];
          this.formData.checkOrgTypes = ["4"];
          //检查次数
          this.formData.count = 3;
          //检查内容
          this.tableData = null;
          break;
        //如果是  【定期检查】行社全面安全检查
        case "4":
          //周期
          this.formData.planCycle = "5";
          //机构类型
          this.formData.execOrgType = "3";
          this.getRolesByOrg();
          //角色
          this.formData.roleIds = ["120"];
          this.selectedValues = ["120"];
          //检查次数
          this.formData.count = 2;
          //检查内容
          this.tableData = null;
          break;
        //如果是  【不定期检查】阶段性检查
        case "5":
          //周期
          this.formData.planCycle = "6";
          //机构类型
          this.formData.execOrgType = null;
          //角色
          this.formData.roleIds = [];
          //检查次数
          this.formData.count = 1;
          //检查内容
          this.tableData = null;
          break;
        //如果是  【不定期检查】专项检查
        case "6":
          //周期
          this.formData.planCycle = "6";
          //机构类型
          this.formData.execOrgType = null;
          //角色
          this.formData.roleIds = [];
          //检查次数
          this.formData.count = 1;
          //检查内容
          this.tableData = null;
          break;
        //如果是  其他
        case "7":
          //周期
          this.formData.planCycle = null;
          //机构类型
          this.formData.execOrgType = null;
          //角色
          this.formData.roleIds = [];
          //检查次数
          this.formData.count = 1;
          this.formData.checkOrgTypes = [];
          //检查内容
          this.tableData = null;
          break;
      }
      // this.changeBuildTime();
    },
    isbuildTaskNow() {
      if (
        (this.formData.planCreateOrgId == this.orgId &&
          this.formData.hasEdit != 1) ||
        (this.formData.planOfOrgType != 3 && this.formData.hasEdit != 1) ||
        (this.id == null &&
          (this.id == null ||
            this.id == undefined ||
            this.formData.planStatus == 0))
      ) {
        return false;
      } else return true;
    },
    handleSelectable(row) {
      // 在这里根据特定条件判断是否停用多选框行
      return this.getshenglianshe(row); // 返回 true 停用，返回 false 不停用
    },
    // 监听行选中事件，将选中的行数据存入 selectedRows 数组中
    handleSelectionChange(selection) {
      // console.log(selection, "selection");
      this.selectedRows = selection;
    },
    deleteSelected() {
      // 在这里执行批量删除操作，使用 this.selectedRows 数组中的数据
      // console.log("删除选中的数据:", this.selectedRows);
      // 从数据数组中移除选中的行数据
      this.tableData = this.tableData.filter(
        (row) => !this.selectedRows.includes(row)
      );
      // 清空选中的行数据
      this.selectedRows = [];
    },
    //省联社内容不能删除
    getshenglianshe(row) {
      if (row.ofOrgId == this.orgId) {
        return true;
      } else return false;
    },
    //编辑内容判断
    cannotEdit() {
      //停用和使用中的任务，只能编辑名称和履职内容
      if (this.formData.planStatus == null) {
        return false;
      }

      if (this.formData.planOfOrgId != this.orgId) {
        return true;
      }

      let r = !(this.formData.planStatus == 0);

      return r;
    },
    //只能编辑创建机构和所属机构是自己的
    cannotEditName() {
      if (this.formData.planStatus == null) {
        return false;
      }

      let r =
        this.formData.planOfOrgId != this.orgId ||
        this.formData.planCreateOrgId != this.orgId;
      return r;
    },
    NowBuild() {
      //如果新增或者是草稿状态的立即生效的编辑
      // if (
      //   this.formData.planCycle != 6 &&
      //   (this.id == null ||
      //     this.id == undefined ||
      //     (this.defbuildTaskNow && this.formData.planStatus == 0))
      // )
      if (
        this.formData.planCycle != 6 &&
        (this.id == null ||
          this.id == undefined ||
          this.formData.planStatus == 0)
      )
        // if (
        //   this.formData.planCycle != 6
        //   )

        return true;
      else return false;
    },
    getLabel(options, value) {
      return getLabel(options, value);
    },
    cleanExecOrgList() {
      this.execOrgIds = null;
      this.formData.execOrgList = [];
      this.formData.roleIds = [];
      this.formData.execOrgIds = [];
      this.getRolesByOrg();
    },
    cleanCheckOrgList() {
      this.checkOrgIds = null;
      this.formData.checkOrgList = [];
      this.formData.checkOrgIds = [];
      this.tableData = [];
    },
    tenantIdnormalizer(node, instanceId) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    handleCheckboxChange() {},
    reset() {
      return {
        planName: null,
        planType: null,
        planCycle: null,
        planStatus: null,
        execOrgType: null,
        roleNames: null,
        count: null,
        description: null,
        tableData: null,
        itemList: null,
        planExec: null,
        count: 0,
        note: null,
        planCreateOrgId: null,
        planCreateOrgName: null,
        roleList: null,
        roleIds: null,
        execOrg: null,
        checkOrg: null,
        buildTaskNow: false,
        checkOrgList: [],
        execOrgList: [],
        rulePointList: null,
        checkOrgIds: null,
        execOrgIds: null,
        rulePointIds: null,
        checkOrgTypes: [],
        checkType: null,
        startDate: null,
        endDate: null,
      };
    },
    getRolesByOrg() {
      console.log(this.formData.execOrgType, "this.formData.execOrgType");
      // let params = {
      //   orgType: null,
      // };
      if (
        this.formData.execOrgType != null &&
        this.formData.execOrgType != undefined &&
        this.formData.execOrgType != ""
      ) {
        findRoleByType(this.formData.execOrgType).then((res) => {
          console.log(res, "res");
          this.planRoles = res;
        });
      }
    },
    handleChange(value) {
      this.count = value;
    },
    async refresh(id, other) {
      if (id != null && id != undefined) {
        await api.get(id).then((res) => {
          this.defbuildTaskNow = res.data.buildTaskNow;
          this.parentCount = res.data.parentCount;
          this.formData = res.data;
          this.formData.buildTaskNow;
          this.tableData = res.data.rulePointList;
          if (this.formData.execOrgType) {
            this.formData.roleIds = this.formData.roleList.map(
              (role) => role.id
            );
            this.formData.checkOrgTypes = this.formData.checkOrgTypeList.map(
              (type) => type.typeId.toString()
            );
            this.formData.execOrgIds = this.formData.execOrgList.map(
              (org) => org.id
            );
            this.formData.checkOrgIds = this.formData.checkOrgList.map(
              (org) => org.id
            );
            this.getRolesByOrg();
          }
        });
      } else {
        this.formData.id = null;
        this.formData.planName = null;
        this.formData.planType = null;
        this.formData.planCycle = null;
        this.formData.planStatus = null;
        this.formData.execOrgType = null;
        this.formData.checkOrgTypes = [];
        this.formData.checkType = null;
        this.formData.roleNames = null;
        this.formData.count = null;
        this.formData.description = null;
        this.formData.tableData = null;
        this.formData.itemList = null;
        this.formData.planExec = null;
        this.formData.count = 0;
        this.formData.note = null;
        this.formData.planCreateOrgId = null;
        this.formData.planCreateOrgName = null;
        this.formData.roleList = null;
        this.formData.roleIds = null;
        this.formData.execOrg = null;
        this.formData.checkOrg = null;
        this.formData.buildTaskNow = false;
        this.formData.checkOrgList = [];
        this.formData.execOrgList = [];
        this.formData.rulePointList = null;
        this.formData.checkOrgIds = null;
        this.formData.execOrgIds = null;
        this.formData.rulePointIds = null;
        this.formData.distributePlanStatus = null;
      }
    },
    onSelect(selectList) {
      console.log(selectList, "selectList");
      for (let i = 0; i < selectList.length; i++) {
        let tem = {
          ofOrgId: this.orgId,
          pointScan: selectList[i].pointScan,
          required: !selectList[i].required,
          ruleName: selectList[i].ruleName,
          itemName: selectList[i].itemName,
          pointName: selectList[i].pointName,
          areaName: selectList[i].areaName,
          itemId: selectList[i].itemId,
          id: selectList[i].id,
          businessType: selectList[i].businessType,
        };
        if (this.tableData == null) {
          this.tableData = [];
        }
        if (tem.itemName != null && tem.itemName != undefined) {
          this.tableData.push(tem);
        }
      }
    },

    async show(id, other = {}) {
      this.id = id;
      this.tableData = null;
      this.formData.execOrgIds = [];
      this.formData.checkOrgIds = [];
      this.formData.itemList = {};
      await this.refresh(id, other);
      this.getRolesByOrg();
      this.isShow = true;
    },
    removeRow(row) {
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {})
        .then(() => {
          this.tableData = this.tableData.filter((item) => item !== row);
          this.$modal.msgSuccess("删除成功");
        });
      // this.tableData = this.tableData.filter((item) => item !== row);
    },
    // 事件
    onHide() {
      this.isShow = false;
    },
    getIteamF() {
      // if (this.id == null) {
      //   this.defaultSelect = [];
      //   return;
      // }else{
      //   api.getPointIds(this.id).then((res) => {
      //   this.defaultSelect = res.data;
      // });
      // }
      if (!this.tableData) {
        return [];
      } else {
        return this.tableData.map((d) => d.id);
      }
    },
    openSelect() {
      if (
        this.formData.checkOrgTypes == null ||
        this.formData.checkOrgTypes.length === 0
      ) {
        this.$modal.alert("请先选择受检机构类型");
        return;
      }

      this.$refs.DialogSelect.show(this.getIteamF());
    },
    onSubmit() {
      this.$refs.form.validate(async (isValidate) => {
        if (!isValidate) return;
        this.loading = true;
        // console.log(this.formData.hasEdit,"this.formData.hasEdit")
        this.formData.planCreateOrgId = this.orgId;
        this.formData.planCreateOrgName = this.orgName;

        this.formData.rulePointList =
          this.tableData == null ? [] : this.tableData;
        // let rols = this.formData.roleList;
        // let rolis = this.formData.roleIds;
        // this.formData.roleList = null;
        // this.formData.roleIds =
        //   this.selectedValues.length == 0 ? null : this.selectedValues;

        // if (this.formData.planCycle == 6) {
        //   this.formData.buildTaskNow = true;
        // }

        if (this.formData.planStatus == 1) {
          let msg;
          let imme;
          if (this.formData.taskHasCompleted == 1) {
            imme = false;
            msg = "因存在已完成任务，本次修改内容将从下周期生效。";
          } else {
            imme = true;
            msg = "因不存在已完成任务，本次修改内容将立即生成。";
          }

          this.$modal.confirm(msg).then(() => {
            this.update(this.formData, imme);
          });
        } else if (this.formData.planStatus == 2) {
          this.update(this.formData, false);
        } else {
          this.update(this.formData, false);
        }
      });
    },
    async update(data, immediateEffect) {      
      await api
        .add(data, immediateEffect)
        .then((data) => {
          this.isSubmitting = false;
          this.loading = false;
          this.$emit("success");
          this.onHide();
        })
        .catch((err) => {
          this.loading = false;
          // console.log(err,"err")
        });
    },
    handleRolesChange(val) {
      this.selectedValues = val.toString().split(",");
    },
    // 事件
    //apimark//
  },
  mounted() {},
  components: { DialogSelect, orgDropDown, OrgTree, korgTree, OrgTreeSelect },
};
</script>

<style lang="scss" scoped>
.brand_info {
  .el-form {
    width: 600px;
    padding-top: 40px;
  }
}
.checkbox-wrapper .el-checkbox {
  display: flex;
  align-items: center;
}
</style>
