<template>
  <div class="rule-type">
    <DialogCom
      @colse="onHide"
      :title="id ? '编辑履职任务' : '新增履职任务'"
      :visible.sync="isShow"
      width="1500px"
    >
      <div class="page-body">
        <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="isChildren()"
                  v-model.trim="formData.planName"
                  :maxlength="50"
                  name="planName"
                  placeholder="请输入任务名称"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="planType" label="任务类型:">
                <el-select
                  :disabled="isChildren()"
                  @change="changeData"
                  label="任务类型"
                  v-model="formData.planType"
                  placeholder="请选择任务类型"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.resumption_plan_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
                  @change="changeBuildTime"
                  :disabled="isChildren()"
                  prop="planCycle"
                  label="任务周期"
                  v-model="formData.planCycle"
                  placeholder="请选择任务周期"
                  clearable
                >
                  <el-option
                    v-for="item in dict.type.resumption_plan_cycle"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <el-form-item>
                  <div class="form-item-comment">
                    下次任务生成时间{{ buildTime }}
                  </div>
                </el-form-item>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="planExec" label="任务时间:">
                <el-select
                  :disabled="isChildren()"
                  label="任务时间"
                  v-model="formData.planExec"
                  placeholder="请选择任务时间"
                  clearable
                >
                  <el-option
                    v-for="item in dict.type.resumption_plan_exec"
                    :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="planStatus" label="计划状态:"> -->
            <!-- <el-select
                  :disabled="getDistributePlanStatus()"
                  prop="planStatus"
                  label="计划状态"
                  v-model="formData.planStatus"
                  placeholder="请选择计划状态"
                  clearable
                >
                  <el-option
                    v-for="item in dict.type.resumption_plan_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="0"
                ></el-switch> -->
            <!-- </el-form-item> -->
            <!-- </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item prop="execOrgType" label="机构类型:">
                <el-select
                  :disabled="isChildren()"
                  label="机构类型"
                  v-model="formData.execOrgType"
                  placeholder="请选择机构类型"
                  @change="onOrgTypeChanged"
                  clearable
                >
                  <el-option
                    v-for="item in dict.type.sys_org_type"
                    :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="roleList" label="履职人员:">
                <el-select
                  :disabled="isChildren()"
                  label="履职人员"
                  v-model="formData.roleList"
                  placeholder="请选择用户角色"
                  multiple
                  filterable
                  @change="handleRolesChange"
                >
                  <el-option
                    v-for="item in resumptionRoles"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </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-col :span="6">
              <el-form-item
                prop="tempBuildTaskNow"
                label="立即生效:"
                v-if="NowBuild()"
              >
                <div class="checkbox-wrapper">
                  <el-checkbox
                    :disabled="isbuildTaskNow()"
                    v-model="tempBuildTaskNow"
                    size="medium"
                    @change="handleCheckboxChange"
                    >默认从下个周期生成任务,<br />勾选后从当前周期立即生成任务</el-checkbox
                  >
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item prop="note" label="备注">
            <el-input
              :disabled="isChildren()"
              v-model="formData.note"
              :maxlength="255"
              clearable
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-form>
        <el-button @click="openSelect">选择履职内容</el-button>
        <el-button @click="deleteSelected">批量删除</el-button>
        <el-table
          :data="tableData"
          style="width: 100%"
          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="checkName" label="履职点位" v-if="false">
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button
                v-if="getshenglianshe(row)"
                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"
      :orgType="formData.execOrgType"
      @select="onSelect"
    ></DialogSelect>
  </div>
</template>

<script>
import dayjs from "dayjs";
import { mapGetters } from "vuex";
import * as api from "@/api/resumption/plan";
import { statusOptions } from "./../../commonOption";
import { findAllRole } from "@/api/system/role";
import DialogSelect from "@/views/resumption/ruleManager/dialog.select.point.vue";
export default {
  dicts: [
    "resumption_plan_type",
    "resumption_plan_cycle",
    "resumption_org_type",
    "resumption_plan_status",
    "sys_org_type",
    "resumption_plan_exec",
  ],
  data() {
    // const params = this.$route.params;
    // let o1=options;
    // let o=statusOptions;
    // debugger
    return {
      parentCount: 1,
      buildTime: null,
      isSubmitting: false,
      defaultSelect: [],
      selectedValues: [],
      resumptionRoles: [],
      planName: null,
      tempBuildTaskNow: false,
      planType: null,
      planCycle: null,
      planStatus: null,
      execOrgType: null,
      roleNames: null,
      planExec: null,
      defbuildTaskNow: false,
      count: 0,
      description: null,
      propItem: "",
      propList: [
        {
          label: "是否扫描",
          prop: "pointScan",
        },
        {
          label: "itemId",
          prop: "itemId",
        },
        {
          label: "必完成项",
          prop: "required",
        },
        {
          label: "履职内容库",
          prop: "pointName",
        },
        {
          label: "履职项",
          prop: "itemName",
        },
        {
          label: "履职内容",
          prop: "itemDesc",
        },
        {
          label: "履职区域",
          prop: "areaName",
        },
        {
          label: "操作",
          prop: "lc-component",
          component: "el-button",
        },
      ],
      row: "",
      tableData: [],
      id: null,
      selectedRows: [],
      isShow: false,
      formData: {},
      formDataRules: {
        planName: [{ required: true, message: "请输入计划名称" }],
        planType: [{ required: true, message: "请选择计划类型" }],
        planCycle: [{ required: true, message: "请选择履职周期" }],
        planStatus: [{ required: true, message: "请选择计划状态" }],
        execOrgType: [{ required: true, message: "请选择履职机构类型" }],
        roleList: [
          { required: true, message: "请选择履职角色", trigger: "change" },
        ],
        planExec: [{ required: true, message: "请选择履职时间" }],
        count: [{ required: true, message: "请选择履职次数" }],
      },
      statusOptions: statusOptions,
    };
  },
  props: {
    orgTypeOptions: {
      type: Array,
    },
    ruleTypeOptions: {
      type: Array,
    },
  },
  watch: {},
  computed: {
    ...mapGetters(["orgId", "orgName"]),
  },
  methods: {
    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;
    },
    NowBuild() {
      //如果新增或者是草稿状态的立即生效的编辑
      // if (
      //   this.id == null ||
      //   this.id == undefined ||
      //   (this.defbuildTaskNow && this.formData.planStatus == 0)
      // )
      if (
        this.id == null ||
        this.id == undefined ||
        ( this.formData.planStatus == 0)
      )
        return true;
      else return false;
    },
    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 = [];
    },
    changeBuildTime() {
      if(this.formData.planCycle==null){
        this.buildTime=null;
        return;
      }
      // console.log(this.formData.planCycle, "this.formData.planCycle");
      const dateObj = new Date(); // 获取当前时间对象
      switch (this.formData.planCycle) {
        case "2":
          dateObj.setDate(dateObj.getDate() + 1);
          const year = dateObj.getFullYear(); // 获取年份
          const month = String(dateObj.getMonth() + 1).padStart(2, "0"); // 获取月份，并补齐两位数
          const day = String(dateObj.getDate()).padStart(2, "0"); // 获取日期，并补齐两位数
          this.buildTime = `${year}-${month}-${day}`; // 将年月日拼接并赋值给变量
          break;
        case "3":
          // 获取下一周的第一天日期
          const nextWeekFirstDay = dayjs().add(1, "week").startOf("week");
          // 格式化日期为你想要的格式
          const formattedNextWeekFirstDay =
            nextWeekFirstDay.format("YYYY-MM-DD");
          this.buildTime = formattedNextWeekFirstDay;
          break;

        case "4":
          // 获取下个月的第一天日期
          const nextMonthFirstDay = dayjs().add(1, "month").startOf("month");

          // 格式化日期为你想要的格式
          const formattedNextMonthFirstDay =
            nextMonthFirstDay.format("YYYY-MM-DD");
          this.buildTime = formattedNextMonthFirstDay;
          break;

        case "5":
          const year2 = dateObj.getFullYear(); // 获取年份
          const month2 = String(dateObj.getMonth() + 1).padStart(2, "0"); // 获取月份，并补齐两位数
          const day2 = "01"; // 获取日期，并补齐两位数
          var month3 = month2;
          var years = year2;
          month3++;
          for (var i = 0; i < 12; i++) {
            if (month3 == 1 || month3 == 4 || month3 == 7 || month3 == 10) {
              break;
            }
            if (month3 == 13) {
              month3 = 1;
              years++;
              break;
            }
            month3++;
          }
          this.buildTime = `${years}-${month3}-${day2}`;

          break;
      }
    },
    //编辑内容判断
    isChildren() {
      // console.log(this.formData.distributePlanStatus,"distributePlanStatus")
      //计划所属机构id等于当前机构id并且不存在已完成或者已逾期或者
      //计划所属机构类型不等于行社并且不存在已完成或者已逾期或者
      //新增
      if (
        (this.formData.planCreateOrgId == this.orgId &&
          this.formData.hasEdit != 1) ||
        (this.formData.planOfOrgType != 3 && this.formData.hasEdit != 1) ||
        this.id == null
      ) {
        return false;
      } else return true;
    },
    //省联社履职内容不能删除
    getshenglianshe(row) {
      if (row.ofOrgId == this.orgId) {
        return true;
      } else return false;
    },
    //选择计划类型修改联动框
    changeData() {
      //判断计划类型
      switch (this.formData.planType) {
        //如果是  营业前安全检查
        case "1":
          //周期
          this.formData.planCycle = "2";
          //机构类型
          this.formData.execOrgType = "4";
          this.getRolesByOrg();
          //角色
          this.formData.roleList = ["122"];
          //履职时间
          this.formData.planExec = "2";
          //履职次数
          this.formData.count = 1;
          //履职内容
          this.tableData = null;
          break;
        //如果是  营业期间安全管理
        case "2":
          //周期
          this.formData.planCycle = "2";
          //机构类型
          this.formData.execOrgType = "4";
          this.getRolesByOrg();
          //角色
          this.formData.roleList = ["122"];
          //履职时间
          this.formData.planExec = "3";
          //履职次数
          this.formData.count = 1;
          //履职内容
          this.tableData = null;
          break;
        //如果是  营业终了安全管理
        case "3":
          //周期
          this.formData.planCycle = "2";
          //机构类型
          this.formData.execOrgType = "4";
          this.getRolesByOrg();
          //角色
          this.formData.roleList = ["122"];
          //履职时间
          this.formData.planExec = "4";
          //履职次数
          this.formData.count = 1;
          //履职内容
          this.tableData = null;
          break;
        //如果是  “110”入侵报警系统测试
        case "4":
          //周期
          this.formData.planCycle = "4";
          //机构类型
          this.formData.execOrgType = "4";
          this.getRolesByOrg();
          //角色
          this.formData.roleList = ["122"];
          //履职时间
          this.formData.planExec = "1";
          //履职次数
          this.formData.count = 1;
          //履职内容
          this.tableData = null;
          break;
        //如果是  备用电源维护
        case "5":
          //周期
          this.formData.planCycle = "5";
          //机构类型
          this.formData.execOrgType = "4";
          this.getRolesByOrg();
          //角色
          this.formData.roleList = ["122"];
          //履职时间
          this.formData.planExec = "1";
          //履职次数
          this.formData.count = 1;
          //履职内容
          this.tableData = null;
          break;
        //如果是  离行式自助银行巡检
        case "6":
          //周期
          this.formData.planCycle = "4";
          //机构类型
          this.formData.execOrgType = "5";
          this.getRolesByOrg();
          //角色
          this.formData.roleList = ["129"];
          //履职时间
          this.formData.planExec = "1";
          //履职次数
          this.formData.count = 2;
          //履职内容
          this.tableData = null;
          break;
        //如果是  非营业时间安全管理
        case "7":
          //周期
          this.formData.planCycle = "2";
          //机构类型
          this.formData.execOrgType = "4";
          this.getRolesByOrg();
          //角色
          this.formData.roleList = ["143"];
          //履职时间
          this.formData.planExec = "5";
          //履职次数
          this.formData.count = 1;
          //履职内容
          this.tableData = null;
          break;
        case "8": //其它
          //周期
          this.formData.planCycle = null;
          //机构类型
          this.formData.execOrgType = null;
          this.resumptionRoles = [];
          //角色
          this.formData.roleList = [];
          //履职时间
          this.formData.planExec = null;
          //履职次数
          this.formData.count = 1;
          //履职内容
          this.tableData = null;
      }
      this.changeBuildTime();
    },
    //当时间为全天或者营业中才显示
    getPlanExec() {
      if (
        this.formData.planExec == null ||
        this.formData.planExec == 2 ||
        this.formData.planExec == 4
      ) {
        return true;
      } else return false;
    },
    getDistributePlanStatus() {
      // console.log(this.formData.distributePlanStatus, "distributePlanStatus");
      if (this.formData.distributePlanStatus == 1) {
        return true;
      } else return false;
    },
    reset() {
      return {
        planName: null,
        planType: null,
        planCycle: null,
        planStatus: null,
        execOrgType: null,
        roleNames: null,
        description: null,
        tableData: null,
        itemList: null,
        planExec: null,
        count: 1,
        note: null,
        planCreateOrgId: null,
        planCreateOrgName: null,
        roleList: [],
        distributePlanStatus: null,
        planCreateOrgType: null,
        buildTaskNow: 0,
      };
    },
    handleCheckboxChange() {
      this.formData.buildTaskNow = this.tempBuildTaskNow ? 1 : 0;
    },
    getRolesByOrg() {
      if (this.formData.execOrgType != null) {
        let params = {
          orgType: this.formData.execOrgType,
        };

        findAllRole(params).then((res) => {
          // console.info(res);
          this.resumptionRoles = res.data;
        });
      }
    },
    handleChange(value) {
      // console.log(value);
      this.count = value;
    },
    async refresh(id, other) {
      this.formData = id ? (await api.get(id)).data : this.reset(other);
      if (this.formData.execOrgType) {
        this.getRolesByOrg();
      }
    },
    onSelect(selectList) {
      // console.log(selectList);
      if (this.tableData == null) {
        this.tableData = [];
      }
      let selectedIds = selectList.map((i) => i.id);
      this.tableData = this.tableData.filter((d) => selectedIds.includes(d.id));
      for (let i = 0; i < selectList.length; i++) {
        let item = selectList[i];
        let exist = this.tableData.find((d) => d.id == item.id);
        console.log(this.orgId, "this.orgId");
        if (!exist) {
          let tem = {
            ofOrgId: this.orgId,
            pointScan: !item.pointScan,
            required: !item.required,
            ruleName: item.ruleName,
            itemName: item.itemName,
            pointName: item.pointName,
            areaName: item.areaName,
            checkName: item.checkName,
            itemId: item.itemId,
            id: item.id,
          };

          this.tableData.push(tem);
          // console.log(tem,"tem")
        }
      }
    },
    onOrgTypeChanged() {
      this.formData.roleList = [];
      this.tableData = [];
      this.getRolesByOrg();
    },
    async show(id, other = {}) {
      this.parentCount = 1;
      this.tempBuildTaskNow = false;
      this.buildTime = null;
      this.id = id;
      this.tableData = null;
      this.formData.itemList = null;
      await this.refresh(id, other);
      // console.log(id);
      if (id !== undefined) {
        await api.get(id).then((res) => {
          this.defbuildTaskNow = res.data.buildTaskNow > 0 ? true : false;
          this.tempBuildTaskNow = res.data.buildTaskNow > 0 ? true : false;
          this.parentCount = res.data.parentCount;
          // console.log(res, "res");
          this.tableData = res.data.itemList;
        });
      }
      this.changeBuildTime();
      this.isShow = true;
    },
    removeRow(row) {
      this.$modal
        .confirm("是否确认删除？")
        .then(function () {})
        .then(() => {
          this.tableData = this.tableData.filter((item) => item !== row);
          this.$modal.msgSuccess("删除成功");
        });

      // this.tableData.splice(index, 1);
    },
    // 事件
    onHide() {
      this.isShow = false;
      this.formData = this.reset();
      this.$refs.form.resetFields();
    },
    getIteamF() {
      // if(this.id==null){
      //   this.defaultSelect=[];
      //   return;
      // }
      // api.getPointIds(this.id).then((res) => {
      //   this.defaultSelect = res.data;
      // });
      if (!this.tableData) {
        return [];
      } else {
        // console.log();
        return this.tableData.map((d) => d.id);
      }
    },
    openSelect() {
      this.$refs.DialogSelect.show(this.getIteamF());
    },
    onSubmit() {
      this.$refs.form.validate(async (isValidate) => {
        this.formData.planStatus = 0;
        this.isSubmitting = true;
        // this.formData.note = this.formData.description;
        this.formData.planCreateOrgId = this.orgId;
        this.formData.planCreateOrgName = this.orgName;
        if (!isValidate) return;
        this.formData.itemList = this.tableData == null ? [] : this.tableData;
        //新需求,自动填充角色
        if (
          this.formData.roleList != null &&
          this.formData.roleList.length > 0 &&
          this.selectedValues.length == 0
        ) {
          this.formData.roleList.forEach((item) => {
            this.selectedValues.push(item);
          });
        }
        this.formData.roleList =
          this.selectedValues.length == 0 ? null : this.selectedValues;
        await api.update(this.formData);
        this.isSubmitting = false;
        this.$emit("success");
        this.onHide();
      });
    },
    handleRolesChange(val) {
      this.selectedValues = val.toString().split(",");
    },
    // 事件
    //apimark//
  },
  mounted() {},
  components: { DialogSelect },
};
</script>

<style lang="scss" scoped>
.brand_info {
  .el-form {
    width: 600px;
    padding-top: 40px;
  }
}
.form-item-comment {
  font-size: 12px;
  color: #999;
  height: 10px;
}
.checkbox-wrapper .el-checkbox {
  display: flex;
  align-items: center;
}
</style>
