<template>
  <!-- 检查部位 -->
  <div class="container_main">
    <div class="checkPoint">
      <div class="header_title">
        <el-form size="medium" :model="queryParams" ref="queryForm" :inline="true">
          <el-form-item prop="dynamicType">
            <el-radio-group
              @change="onControlListTypeChange"
              v-model="queryParams.dynamicType"
            >
              <el-radio :label="1">动态风险</el-radio>
              <el-radio :label="2">静态风险</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="风险类型" prop="containLibraryIds">
            <el-cascader
              v-model="queryParams.containLibraryIds"
              style="width: 100%"
              :options="riskPointTreeList"
              filterable
              clearable
              :show-all-levels="false"
              :props="{
                emitPath: false,
                checkStrictly: true,
                value: 'id',
                label: 'nodeName',
              }"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="handleQuery">查询</el-button>
            <el-button type="warning" plain @click="handleRefresh">刷新</el-button>
            <!-- <el-button
              :disabled="$refs.multipleTable && $refs.multipleTable.selection.length == 0"
              type="danger"
              plain
              class="delete_btn"
              @click="deleteAttendanceBatch"
              >批量删除</el-button
            > -->
            <el-dropdown @command="handleCommand" class="el-button" style="padding: 0">
              <el-button type="primary"> 批量设置 </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="1">排查类别及频次</el-dropdown-item>
                <el-dropdown-item command="2">排查时间</el-dropdown-item>
                <el-dropdown-item command="3">排查范围</el-dropdown-item>
                <el-dropdown-item command="4">排查责任人</el-dropdown-item>
                <el-dropdown-item command="5">全部字段</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-dropdown
              @command="handleCommandReminder"
              class="el-button"
              style="padding: 0"
            >
              <el-button type="primary"> 待办任务 </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="1">生成待办任务</el-dropdown-item>
                <el-dropdown-item command="2">取消待办任务</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleCommandExport(1)" type="primary" plain
              >导出</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <!-- <div class="check_box">
            <div>
              已选{{ $refs.multipleTable ? $refs.multipleTable.selection.length : 0 }}项
            </div>
            <el-button @click="toggleSelection(false)" type="text" style="color: #f76c6c"
              >取消</el-button
            >
            <el-button @click="toggleSelection(true)" type="text">全选</el-button>
            <el-button @click="toggleExpandAll(true)" type="text">全部展开</el-button>
            <el-button @click="toggleExpandAll(false)" type="text">全部关闭</el-button>
          </div> -->
      <el-table
        ref="multipleTable"
        :data="tableData"
        row-key="id"
        :height="526"
        class="new-tables"
      >
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column
          align="center"
          prop="riskPointName"
          label="风险分类"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="riskDescription"
          label="风险情况描述"
        >
          <template slot-scope="scope">
            {{ scope.row.riskDescription ? scope.row.riskDescription : "--" }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="riskLevel"
          label="风险等级"
        >
          <template slot-scope="scope">
            {{ setNameUp(scope.row.riskLevel, riskLevelList, "id", "name") }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="accidentTypeId"
          label="潜在事故类型"
        >
          <template slot-scope="scope">
            {{ accidentTypeUp(scope.row.accidentTypeId) }}
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip align="center" prop="isDaily" label="日常">
          <template slot-scope="scope">
            <i
              v-if="scope.row.isDaily == 1"
              style="color: #5c81ee"
              class="el-icon-check"
            ></i>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="isSpecial"
          label="专项"
        >
          <template slot-scope="scope">
            <i
              v-if="scope.row.isSpecial == 1"
              style="color: #5c81ee"
              class="el-icon-check"
            ></i>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="isComposite"
          label="综合"
        >
          <template slot-scope="scope">
            <i
              v-if="scope.row.isComposite == 1"
              style="color: #5c81ee"
              class="el-icon-check"
            ></i>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="riskSituationDescription" label="管控措施">
          <template slot-scope="scope">
            <el-tooltip placement="top">
              <div slot="content">
                工程措施：{{
                  scope.row.engineeringMeasure ? scope.row.engineeringMeasure : "--"
                }}<br />管理措施：{{
                  scope.row.managementMeasure ? scope.row.managementMeasure : "--"
                }}<br />个体防护：{{
                  scope.row.personalProtection ? scope.row.personalProtection : "--"
                }}<br />应急措施：{{
                  scope.row.emergencyMeasure ? scope.row.emergencyMeasure : "--"
                }}<br />教育措施：{{
                  scope.row.educationalMeasure ? scope.row.educationalMeasure : "--"
                }}<br />
              </div>
              <div class="oneLine">{{ concatenationTextUp(scope.row) }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="checkWorkerNames"
          show-overflow-tooltip
          label="排查责任人"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.checkWorkerNames ? scope.row.checkWorkerNames : "--" }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          show-overflow-tooltip
          prop="validTime"
          label="有效时间"
        >
          <template slot-scope="scope">
            <template v-if="scope.row.effectiveTimeBegin">
              {{ scope.row.effectiveTimeBegin }}至{{ scope.row.effectiveTimeEnd }}
            </template>
            <div class="color_e400" v-else>未设置</div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="checkNum"
          label="排查频次"
        >
          <template slot-scope="scope">
            {{ scope.row.checkNum ? scope.row.checkNum : "--" }}次/{{ scope.row.checkPeriod ? checkPeriodList[scope.row.checkPeriod - 1].checkPeriodName : '--' }}
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip align="center" prop="remark" label="备注">
          <template slot-scope="scope">
            {{ scope.row.remark ? scope.row.remark : "--" }}
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="allowGenerateTask"
          label="允许生成任务"
        >
          <template slot-scope="scope">
            <i
              v-if="scope.row.allowGenerateTask == 1"
              style="color: #5c81ee"
              class="el-icon-check"
            ></i>
          </template>
        </el-table-column>
        <el-table-column width="240" label="操作" align="center">
          <template slot-scope="scope">
            <div class="flex2 edit">
              <!-- <img src="@/assets/images/icon-edit.png" /> -->
              <!-- <el-button type="text" icon="el-icon-view">查看</el-button> -->
              <el-button
                @click="setControlListDialog(0, scope.row)"
                style="border: 0 !important"
                type="text"
                icon="el-icon-edit"
                >编辑</el-button
              >
              <!-- <el-button
                style="border: 0 !important; color: #f56c6c"
                type="text"
                icon="el-icon-delete"
                @click="deleteBtn(scope.row)"
                >删除</el-button
              > -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="Number(total)"
        :page.sync="queryParams.pageNo"
        :limit.sync="queryParams.pageSize"
        @pagination="getQualityRegionList"
        :pageSizes="[...$store.state.PAGESIZRS, 100, 200, 500, 1000]"
        layout="total,sizes, prev, pager, next, jumper"
      />
    </div>

    <el-dialog
      :modal-append-to-body="false"
      @close="close"
      :title="title"
      :visible.sync="setDialog"
      width="668px"
      class="dialog_center"
    >
      <div class="dialog_content">
        <el-form
          ref="setForm"
          :model="setForm"
          :rules="rules"
          label-width="100px"
          size="medium"
          class="setForm"
        >
          <el-form-item label-width="0" prop="period">
            <span class="color_808 font_size"
              >注:【排查类别、时问、范围、责任人、频次、允许生成任务】全部设置后可以生成任务</span
            >
          </el-form-item>
          <template v-if="batchSettingType == 0 || batchSettingType == 5">
            <el-form-item label-width="0" prop="alarmTypeAllList">
              <el-checkbox-group v-model="setForm.alarmTypeAllList">
                <el-checkbox
                  v-for="item in alarmTypeList"
                  :key="item.alarmTypeId"
                  :label="item.alarmTypeName"
                  >{{ item.alarmTypeName }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="排查频次" prop="checkNum">
              <div class="flex">
                <el-input-number
                  class="w-210"
                  v-model="setForm.checkNum"
                  controls-position="right"
                ></el-input-number>
                <el-select
                  class="w-102 ml-8"
                  v-model="setForm.checkPeriod"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in checkPeriodList"
                    :key="item.id"
                    :label="item.checkPeriodName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="排查时间" prop="effectiveTime">
              <el-date-picker
                class="w-320"
                v-model="setForm.effectiveTime"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="排查范围" prop="specificResponsibilityAreaIds">
              <el-cascader
                v-model="setForm.specificResponsibilityAreaIds"
                :options="regionV2TreeList"
                class="w-320"
                filterable
                clearable
                collapse-tags
                :show-all-levels="false"
                :props="{
                  emitPath: false,
                  multiple: true,
                  checkStrictly: true,
                  value: 'id',
                  label: 'regionName',
                }"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="责任分包单位" prop="checkWorkerEnterpriseIds">
              <el-cascader
                v-model="setForm.checkWorkerEnterpriseIds"
                :options="enterpriseInfoList"
                filterable
                clearable
                collapse-tags
                class="w-320"
                :show-all-levels="false"
                :props="{
                  multiple: true,
                  checkStrictly: true,
                  emitPath: false,
                  value: 'id',
                  label: 'enterpriseName',
                }"
                clearable
              ></el-cascader>
            </el-form-item>
            <el-form-item label="责任人" prop="checkWorkerIds">
              <SelectedPersonnelAccount
                v-model="setForm.checkWorkerIds"
                class="w-320"
                :enterpriseFlag="false"
                :enterpriseIds="setForm.checkWorkerEnterpriseIds"
              ></SelectedPersonnelAccount>
            </el-form-item>
          </template>
          <template v-else-if="batchSettingType == 1">
            <el-form-item label-width="0" prop="alarmTypeAllList">
              <el-checkbox-group v-model="setForm.alarmTypeAllList">
                <el-checkbox
                  v-for="item in alarmTypeList"
                  :key="item.alarmTypeId"
                  :label="item.alarmTypeName"
                  >{{ item.alarmTypeName }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="排查频次" prop="checkNum">
              <div class="flex">
                <el-input-number
                  class="w-210"
                  v-model="setForm.checkNum"
                  controls-position="right"
                ></el-input-number>
                <el-select
                  class="w-102 ml-8"
                  v-model="setForm.checkPeriod"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in checkPeriodList"
                    :key="item.id"
                    :label="item.checkPeriodName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </template>
          <template v-else-if="batchSettingType == 2">
            <el-form-item label="排查时间" prop="effectiveTime">
              <el-date-picker
                class="w-320"
                v-model="setForm.effectiveTime"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </template>
          <template v-else-if="batchSettingType == 3">
            <el-form-item label="排查范围" prop="specificResponsibilityAreaIds">
              <el-cascader
                v-model="setForm.specificResponsibilityAreaIds"
                :options="regionV2TreeList"
                class="w-320"
                filterable
                clearable
                collapse-tags
                :show-all-levels="false"
                :props="{
                  emitPath: false,
                  multiple: true,
                  checkStrictly: true,
                  value: 'id',
                  label: 'regionName',
                }"
              ></el-cascader>
            </el-form-item>
          </template>
          <template v-else-if="batchSettingType == 4">
            <el-form-item label="责任分包单位" prop="checkWorkerEnterpriseIds">
              <el-cascader
                v-model="setForm.checkWorkerEnterpriseIds"
                :options="enterpriseInfoList"
                filterable
                clearable
                collapse-tags
                class="w-320"
                :show-all-levels="false"
                :props="{
                  multiple: true,
                  checkStrictly: true,
                  emitPath: false,
                  value: 'id',
                  label: 'enterpriseName',
                }"
                clearable
              ></el-cascader>
            </el-form-item>
            <el-form-item label="责任人" prop="checkWorkerIds">
              <SelectedPersonnelAccount
                v-model="setForm.checkWorkerIds"
                class="w-320"
                :enterpriseFlag="false"
                :enterpriseIds="setForm.checkWorkerEnterpriseIds"
              ></SelectedPersonnelAccount>
            </el-form-item>
          </template>
        </el-form>
      </div>
      <div class="dialog-footer">
        <el-button
          class="cancleBtn"
          @click="setDialog = false"
          icon="el-icon-circle-close"
          size="medium"
          >{{ $t("message.alarmValueSet.cancel") }}
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-circle-check"
          @click="submit('setForm')"
          size="medium"
          >{{ $t("message.alarmValueSet.save") }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :modal-append-to-body="false"
      title="提示"
      :visible.sync="reminderDialog"
      width="668px"
      class="dialog_center"
    >
      <div class="dialog_content form_box">
        <!-- 、当日是否在排查时间范围内 -->
        <div>以下危险源未生成待办任务，请确认设置是否完整:</div>
        <div v-for="(item, index) in oldSelectionList" :key="item.id">
          {{ index + 1 }}、风险分类:{{ item.riskPointName }}，风险描述:{{
            item.riskDescription
          }};
        </div>
      </div>
      <div class="dialog-footer">
        <el-button
          type="primary"
          icon="el-icon-circle-check"
          @click="reminderSubmit(1)"
          size="medium"
          >确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  deleteBatchRiskListSourceApi,
  getRiskListSourcePageApi,
  deleteRiskListSourceApi,
  editRiskListSourceApi,
  batchSetFieldRiskListSourceApi,
  getRegionV2TreePageApi,
  setRiskSourceGenerateTaskApi,
} from "@/assets/js/api/quality.js";
import {
  getRiskListPotentialAccidentTypeApi,
  getRiskListLibraryTreePageApi,
} from "@/assets/js/api/safeManage";
import { selectHierarchyEnterpriseListApi } from "@/assets/js/api/laborPerson.js";
import dayjs from "dayjs";
export default {
  name: "controlList",
  props: ["zindexFlag"],
  data() {
    return {
      COMPANY: COMPANY,
      title: "编辑",
      dialogType: 1,
      projectSn: "",
      notifierOrPeopleList: [],
      enterpriseInfoList: [],
      value: "",
      tableData: [],
      setDialog: false,
      setForm: {
        alarmTypeAllList: [],
        checkNum: "",
        checkPeriod: "",
        effectiveTime: [],
        checkWorkerEnterpriseIds: [],
        checkWorkerIds: [],
        specificResponsibilityAreaIds: [],
      },
      showList: [],
      rules: {
        aiDeviceId: [
          {
            required: true,
            message: "请选择AI设备",
            trigger: "change",
          },
        ],
        dutyId: [
          {
            required: true,
            message: "请输入责任单位",
            trigger: "change",
          },
        ],
        personId: [
          {
            required: true,
            message: "请输入责任人",
            trigger: "change",
          },
        ],
      },
      aiDeviceList: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        regionName: "",
        controlListType: 1,
        dynamicType: 1,
        containLibraryIds: "",
        specificResponsibilityAreaIds: "",
      },
      total: 0,
      projectTypeList: [],
      accidentTypeList: [],
      riskFactorTypeList: [],
      regionV2TreeList: [],
      batchSettingType: 0,
      sourceDangerDialog: false,
      sourceDangerTitle: "",
      sourceDangerList: [],
      sourceDangerInfo: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
      },
      defaultProps: {
        children: "children",
        label: "nodeName",
        disabled: function (data, node) {
          // 禁用回收站选项
          if (data.ancestors.split(",").length < 4) {
            return true;
          }
        },
      },
      riskPointTitle: "",
      riskPointDialog: false,
      riskPointTreeList: [],
      riskPointList: [],
      defaultCheckedKeys: [],
      checkPeriodList: [
        {
          id: 1,
          checkPeriodName: "日",
        },
        {
          id: 2,
          checkPeriodName: "周",
        },
        {
          id: 3,
          checkPeriodName: "月",
        },
        {
          id: 4,
          checkPeriodName: "季度",
        },
        {
          id: 5,
          checkPeriodName: "半年",
        },
      ],
      riskLevelList: [
        {
          id: 1,
          name: "重大风险",
        },
        {
          id: 2,
          name: "较大风险",
        },
        {
          id: 3,
          name: "一般风险",
        },
        {
          id: 4,
          name: "低风险",
        },
      ],
      alarmTypeList: [
        {
          alarmTypeId: 1,
          alarmTypeName: "日常",
          alarmTypeKey: "isDaily",
        },
        {
          alarmTypeId: 2,
          alarmTypeName: "专项",
          alarmTypeKey: "isSpecial",
        },
        {
          alarmTypeId: 3,
          alarmTypeName: "综合",
          alarmTypeKey: "isComposite",
        },
      ],
      reminderDialog: false,
      newSelectionList: [],
      oldSelectionList: [],
    };
  },
  created() {
    this.projectSn = this.$store.state.projectSn;
    this.getQualityRegionList();
    this.getRiskListLibraryList();
    this.getUpdateUnitListFn();
    this.getDicProjectTypeList();
  },
  methods: {
    handleCommandExport(command) {
      if (this.$refs.multipleTable.selection.length == 0)
        return this.$message.warning("请先勾选需要导出的数据！");
      const objFn = {
        1: "xmgl/riskListSource/exportRiskPointXls",
      };

      if (command == 1) {
        const requestData = {
          sourceIds: this.$refs.multipleTable.selection.map((item) => item.id).join(","),
          projectSn: this.projectSn,
        };
        this.exportDownload(requestData, objFn[command], "隐患排查计划导出.xlsx");
      }
    },
    exportDownload(requestData, url, name) {
      fetch(this.$http.defaults.baseURL + url, {
        method: "post",
        headers: {
          Authorization: this.$store.state.userInfo.token,
          "Content-Type": "application/json", // 设置请求头的内容类型为JSON
        },
        body: JSON.stringify(requestData),
      })
        .then((response) => {
          // 处理响应
          if (!response.ok) {
            throw new Error("导出失败");
          }
          return response.blob();
        })
        .then((blob) => {
          console.log("导出成功");
          // 创建一个下载链接
          const url = window.URL.createObjectURL(blob);
          // 创建一个<a>元素
          const link = document.createElement("a");
          link.href = url;
          link.download = name; // 指定下载文件的文件名
          // 模拟点击下载链接
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          // 释放URL对象
          window.URL.revokeObjectURL(url);
          // 处理导出的文件
          // 这里可以使用blob对象来获取导出的文件内容或者将其保存到本地
        })
        .catch((error) => {
          // 处理错误
          console.error(error);
        });
    },
    // 设置危险源
    onDetail() {
      console.log(1111);
      this.$emit("openHandelDetail", {
        dynamicType: this.queryParams.dynamicType,
      });
    },
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getQualityRegionList();
    },
    handleRefresh() {
      this.queryParams.pageNo = 1;
      this.queryParams.regionName = "";
      this.queryParams.containLibraryIds = "";
      this.queryParams.specificResponsibilityAreaIds = "";
      this.getQualityRegionList();
    },
    deleteAttendanceBatch() {
      if (this.$refs.multipleTable.selection.length === 0)
        return this.$message.warning("请勾选需要删除的数据！");
      this.$confirm("删除后操作不可恢复，请谨慎操作！", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const ids = this.$refs.multipleTable.selection.map((item) => item.id).join(",");
          //   console.log(this.$refs.multipleTable.selection);
          deleteBatchRiskListSourceApi({ ids }).then((res) => {
            this.getQualityRegionList();
          });
        })
        .catch(() => {});
    },
    toggleExpandAll(isExpandAll) {
      this.toggleSelectionAll(this.tableData, isExpandAll);
    },
    toggleSelection(flag) {
      if (flag) {
        // this.$refs.multipleTable.toggleAllSelection(true)
        this.toggleSelectionAll(this.tableData);
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    toggleSelectionAll(dataList, isExpandAll = null) {
      dataList.forEach((item) => {
        if (isExpandAll == null) {
          this.$refs.multipleTable.toggleRowSelection(item, true);
        } else {
          this.$refs.multipleTable.toggleRowExpansion(item, isExpandAll);
        }
        if (item.children instanceof Array && item.children.length > 0) {
          this.toggleSelectionAll(item.children, isExpandAll);
        }
      });
    },

    onControlListTypeChange() {
      this.getQualityRegionList();
    },
    // 获取列表信息
    getQualityRegionList() {
      let data = {
        projectSn: this.projectSn,
        dynamicType: this.queryParams.dynamicType,
        regionName: this.queryParams.regionName,
        containLibraryIds: this.queryParams.containLibraryIds,
        pageNo: this.queryParams.pageNo,
        pageSize: this.queryParams.pageSize,
      };
      // getQualityRegionListApi

      getRiskListSourcePageApi(data).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.tableData = res.result.records;
          this.total = res.result.total;
        }
      });
    },
    handleCommandReminder(command) {
      if (this.$refs.multipleTable.selection.length == 0)
        return this.$message.warning("请先勾选需要批量设置的数据！");
      if (command == 1) {
        this.newSelectionList = [];
        this.oldSelectionList = [];
        this.$refs.multipleTable.selection.forEach((item) => {
          console.log(112233, item);
          const isFlag =
            item.isDaily == 1 || item.isSpecial == 1 || item.isComposite == 1;
          if (
            isFlag &&
            item.checkNum &&
            item.checkPeriod &&
            item.effectiveTimeBegin &&
            item.effectiveTimeEnd &&
            item.specificResponsibilityAreaIds &&
            item.checkWorkerEnterpriseIds &&
            item.checkWorkerIds
          ) {
            this.newSelectionList.push(item);
          } else {
            this.oldSelectionList.push(item);
          }
        });
        if(this.oldSelectionList.length > 0) {
          this.reminderDialog = true;
        }else {
          this.reminderSubmit(1);
        }
      } else if (command == 2) {
        this.reminderSubmit(0);
      }
    },
    reminderSubmit(type) {
      let RiskListSource = [];
      if (type == 0) {
        RiskListSource = this.$refs.multipleTable.selection.map((item) => {
          return {
            ...item,
            allowGenerateTask: type,
          };
        });
      } else if (type == 1) {
        RiskListSource = this.newSelectionList.map((item) => {
          return {
            ...item,
            allowGenerateTask: type,
          };
        });
      }

      setRiskSourceGenerateTaskApi(RiskListSource).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$message.success("操作成功！");
          this.reminderDialog = false;
          this.getQualityRegionList();
        }
      });
    },
    handleCommand(command) {
      if (this.$refs.multipleTable.selection.length == 0)
        return this.$message.warning("请先勾选需要批量设置的数据！");
      this.setControlListDialog(command);
    },
    setControlListDialog(settingType, row) {
      this.batchSettingType = settingType;
      if (row && row.id) {
        this.setForm = {
          ...row,
          specificResponsibilityAreaIds: row.specificResponsibilityAreaIds
            ? row.specificResponsibilityAreaIds.split(",")
            : "",
          checkWorkerEnterpriseIds: row.checkWorkerEnterpriseIds
            ? row.checkWorkerEnterpriseIds.split(",")
            : [],
          checkWorkerIds: row.checkWorkerIds ? row.checkWorkerIds.split(",") : [],
          effectiveTime: [
            row.effectiveTimeBegin ? row.effectiveTimeBegin : "",
            row.effectiveTimeEnd ? row.effectiveTimeEnd : "",
          ],
          alarmTypeAllList: [],
        };
        for (const key in row) {
          this.alarmTypeList.forEach((item) => {
            if (item.alarmTypeKey == key && row[key] == 1) {
              this.setForm.alarmTypeAllList.push(item.alarmTypeName);
            }
          });
        }
      } else {
        this.setForm = {
          alarmTypeAllList: [],
          checkNum: "",
          checkPeriod: "",
          effectiveTime: [],
          checkWorkerEnterpriseIds: [],
          checkWorkerIds: [],
          specificResponsibilityAreaIds: [],
        };
      }
      this.setDialog = true;
      if (settingType == 0) {
        this.title = "编辑";
      }
      this.$nextTick(() => {
        this.$refs["setForm"].clearValidate();
      });
    },

    //弹窗---保存按钮
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = {};
          if (this.batchSettingType == 0) {
            data = {
              ...this.setForm,
              specificResponsibilityAreaIds:
                this.setForm.specificResponsibilityAreaIds instanceof Array
                  ? this.setForm.specificResponsibilityAreaIds.join(",")
                  : "",
              checkWorkerEnterpriseIds:
                this.setForm.checkWorkerEnterpriseIds instanceof Array
                  ? this.setForm.checkWorkerEnterpriseIds.join(",")
                  : "",
              checkWorkerIds:
                this.setForm.checkWorkerIds instanceof Array
                  ? this.setForm.checkWorkerIds.join(",")
                  : "",
              effectiveTimeBegin:
                this.setForm.effectiveTime.length > 1
                  ? this.setForm.effectiveTime[0]
                  : "",
              effectiveTimeEnd:
                this.setForm.effectiveTime.length > 1
                  ? this.setForm.effectiveTime[1]
                  : "",
              projectSn: this.projectSn,
            };
            this.alarmTypeList.forEach((item) => {
              if (this.setForm.alarmTypeAllList.includes(item.alarmTypeName)) {
                data[item.alarmTypeKey] = 1;
              } else {
                data[item.alarmTypeKey] = 0;
              }
            });
          } else if (this.batchSettingType >= 1 && this.batchSettingType <= 5) {
            data.updates = this.$refs.multipleTable.selection.map((item) => {
              if (this.batchSettingType == 1 || this.batchSettingType == 5) {
                this.alarmTypeList.forEach((ele) => {
                  if (this.setForm.alarmTypeAllList.includes(ele.alarmTypeName)) {
                    item[ele.alarmTypeKey] = 1;
                  } else {
                    item[ele.alarmTypeKey] = 0;
                  }
                });
                item.checkNum = this.setForm.checkNum;
                item.checkPeriod = this.setForm.checkPeriod
                  ? this.setForm.checkPeriod
                  : null;
              }
              if (this.batchSettingType == 2 || this.batchSettingType == 5) {
                item.effectiveTimeBegin =
                  this.setForm.effectiveTime.length > 1
                    ? this.setForm.effectiveTime[0]
                    : "";
                item.effectiveTimeEnd =
                  this.setForm.effectiveTime.length > 1
                    ? this.setForm.effectiveTime[1]
                    : "";
              }
              if (this.batchSettingType == 3 || this.batchSettingType == 5) {
                item.specificResponsibilityAreaIds = this.setForm
                  .specificResponsibilityAreaIds
                  ? this.setForm.specificResponsibilityAreaIds.join(",")
                  : "";
              }
              if (this.batchSettingType == 4 || this.batchSettingType == 5) {
                item.checkWorkerEnterpriseIds = this.setForm.checkWorkerEnterpriseIds
                  ? this.setForm.checkWorkerEnterpriseIds.join(",")
                  : "";
                item.checkWorkerIds = this.setForm.checkWorkerIds
                  ? this.setForm.checkWorkerIds.join(",")
                  : "";
              }

              return {
                ...item,
              };
            });
          }

          //   editRiskListSourceApi

          if (this.batchSettingType == 0) {
            editRiskListSourceApi(data).then((res) => {
              // console.log(res);
              if (res.code == 200) {
                this.$message.success(this.$t("message.quality.newSuccess"));
                this.setDialog = false;
                this.getQualityRegionList();
              }
            });
          } else if (this.batchSettingType >= 1 && this.batchSettingType <= 5) {
            batchSetFieldRiskListSourceApi(data).then((res) => {
              // console.log(res);
              if (res.code == 200) {
                this.$message.success("设置成功！");
                this.setDialog = false;
                this.getQualityRegionList();
              }
            });
          }
        }
      });
    },
    //删除 按钮
    deleteBtn(value) {
      this.$confirm(
        this.$t("message.quality.deleteHint"),
        this.$t("message.quality.hint"),
        {
          confirmButtonText: this.$t("message.quality.confirm"),
          cancelButtonText: this.$t("message.quality.cancel"),
          type: "warning",
        }
      )
        .then(() => {
          let data = {
            id: value.id,
          };
          deleteRiskListSourceApi(data).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: this.$t("message.quality.successfullyDelete") + "!",
              });
              this.getQualityRegionList();
            }
          });
        })
        .catch(() => {});
    },

    close() {
      this.$nextTick(() => {
        this.$refs["setForm"].clearValidate();
      });
    },
    recursionRiskListLibraryList(dataList) {
      dataList.forEach((item) => {
        if (item.children) {
          item.children = this.recursionRiskListLibraryList(item.children);
        }
        item.disabled = item.ancestors.split(",").length < 4; // 禁用回收站选项
      });
      return dataList;
    },
    getRiskListLibraryList() {
      getRiskListLibraryTreePageApi({
        projectSn: this.$store.state.projectSn,
      }).then((res) => {
        if (res.success) {
          // ancestors
          this.riskPointTreeList = this.recursionRiskListLibraryList(res.result.records);
        }
      });
    },
    // 获取字典工程类别列表
    getDicProjectTypeList() {
      // 风险清单库工程类别
      //   getDictionaryItemApi({
      //     dictionaryEncoding: "risk_list_project_type",
      //     projectSn: this.projectSn,
      //   }).then((res) => {
      //     if (res.result.length > 0) {
      //       this.projectTypeList = res.result;
      //     }
      //   });
      //   // 风险因素类型
      //   getDictionaryItemApi({
      //     dictionaryEncoding: "risk_factor_type",
      //     projectSn: this.projectSn,
      //   }).then((res) => {
      //     if (res.result.length > 0) {
      //       this.riskFactorTypeList = res.result;
      //     }
      //   });
      // 潜在事故类型
      getRiskListPotentialAccidentTypeApi({
        // sn: this.$store.state.userInfo.headquartersSn,
        projectSn: this.projectSn,
      }).then((res) => {
        if (res.result.length > 0) {
          this.accidentTypeList = res.result.sort(
            (a, b) => Date.parse(a.createTime) - Date.parse(b.createTime)
          );
        }
      });
      getRegionV2TreePageApi({
        projectSn: this.projectSn,
        pageNo: 1,
        pageSize: -1,
      }).then((res) => {
        if (res.result.records.length > 0) {
          this.regionV2TreeList = res.result.records;
        }
      });
    },
    // 获取整改单位列表
    getUpdateUnitListFn() {
      selectHierarchyEnterpriseListApi({ projectSn: this.projectSn }).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.enterpriseInfoList = res.result;
        }
      });
    },
  },
  computed: {
    setNameUp() {
      return (rowId, dataList, id, name) => {
        const find = dataList.find((item) => item[id] === rowId);
        return find ? find[name] : "--";
      };
    },
    accidentTypeUp() {
      return (accidentTypeId) => {
        const find = this.accidentTypeList.find((item) => accidentTypeId === item.id);
        return find ? find.type : "--";
      };
    },
    concatenationTextUp() {
      return (row) => {
        const engineeringMeasure = row.engineeringMeasure ? row.engineeringMeasure : "--";
        const managementMeasure = row.managementMeasure ? row.managementMeasure : "--";
        const personalProtection = row.personalProtection ? row.personalProtection : "--";
        const emergencyMeasure = row.emergencyMeasure ? row.emergencyMeasure : "--";
        const educationalMeasure = row.educationalMeasure ? row.educationalMeasure : "--";

        return `工程措施：${engineeringMeasure}\n管理措施：${managementMeasure}\n个体防护：${personalProtection}\n应急措施：${emergencyMeasure}\n教育措施：${educationalMeasure}\n`;
      };
    },
  },
};
</script>
<style lang="less" scoped>
// :deep(.el-cascader .el-checkbox.is-disabled) {
//     display: none;
// }

.setForm {
  margin: 0 86px;
  //   height: 460px;
  .el-date-editor,
  .el-input-number,
  .el-cascader {
    width: 100%;
  }
  .el-form-item {
    margin-bottom: 20px;
  }
}
:deep(.el-dialog__body) {
  padding: 10px 20px 20px;
  .dialog_content {
    padding-left: 0;
    padding-right: 0pc;
  }
  .form_box {
    margin: 0 65px;
    color: #272d45;
    font-size: 14px;
    > div {
      margin-top: 6px;
    }
  }
}
.riskpoint-dialog {
  display: flex;
  justify-content: space-between;
  height: 420px;
  .unselected_point {
    width: 280px;
    .treeBox {
      margin-top: 12px;
      height: calc(100% - 12px - 24px - 16px);
      // background-color: rgba(216, 216, 216, 0.2);
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      padding: 12px 6px;
      position: relative;
      :deep(.el-checkbox.is-disabled) {
        display: none;
      }
      .treeStyle();
    }
  }
  .selected_point {
    width: 280px;
    .selected_point_scroll {
      margin-top: 12px;
      height: calc(100% - 2px - 24px);
      max-height: initial;
      padding: 12px 6px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      .risk_point {
        width: 100%;
        margin-top: 6px;
        > div {
          justify-content: space-between;
          display: flex;
          align-items: center;
        }
      }
    }
  }
}
.source-danger {
  .pagination-container {
    padding: 16px 0 0 0;
  }
}
.tables {
  min-height: initial;
}
.check_box {
  display: flex;
  font-size: 14px;
  > .el-button {
    padding: 0;
    margin-left: 10px;
  }
  > .el-button:first-child {
    color: #eb4047;
  }
}
.flex {
  display: flex;
}
.flex2 {
  display: flex;
  align-items: center;
}
.container_main {
  height: calc(100% - 49px);
}
.checkPoint {
  box-sizing: border-box;
  position: relative;
  height: 100%;
  .header_title {
    padding: 20px 20px 0 20px;
    :deep(.el-cascader__search-input) {
      min-width: 10px;
    }
  }
  :deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
    color: #5181f6;
    background-color: transparent;
    border-color: #d7dbe9;
    box-shadow: none;
  }
  .pagination-container {
    padding: 0;
    width: 100%;
    position: absolute;
    bottom: 16px;
    left: 50%;
    transform: translateX(-50%);
  }
  .el-form-item {
    margin-bottom: 20px;
    margin-right: 30px;
  }
  .el-form-item:last-child {
    margin-right: 0;
  }
  .el-button + .el-button {
    margin-left: 20px;
  }
  .el-radio {
    margin-right: 20px;
  }
  .el-select,
  .el-input {
    width: 192px;
    height: 34px;
  }
  .el-date-editor {
    width: 247px;
    height: 34px;
  }
  .radio-group {
    margin-bottom: 20px;
    /deep/ .el-radio-button__inner {
      width: 100px;
      height: 33px;
      color: #b2b8c2;
    }
  }
  .edit {
    width: 100%;
    justify-content: center;
    cursor: pointer;
    img {
      margin-right: 5px;
    }
  }
}
.treeStyle() {
  /deep/.el-tree {
    font-size: 15px;
    width: 100%;
    background-color: transparent;
    .el-tree-node {
      white-space: normal;
      &:focus > .el-tree-node__content {
        background-color: transparent;
      }
      &.is-current > .el-tree-node__content {
        background-color: rgba(81, 129, 246, 0.14);
        color: #5181f6;
      }
    }
    .el-tree-node__content {
      // height: 32px;
      padding: 7px 0;
      height: auto;
      line-height: 16px;
      position: relative;
      // margin-bottom: 7px;
      &:hover {
        background-color: rgba(81, 129, 246, 0.14);
        color: #5181f6;
      }

      .videoName {
        font-size: 14px;
      }
      .projectName {
        font-size: 14px;
        width: calc(100% - 55px);
        display: inline-block;
      }
      .companyName2 {
        font-size: 16px;
        font-weight: bold;
        display: inline-block;
        width: 192px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .el-tree-node__expand-icon {
      font-size: 16px;
      padding: 0 6px;
      &.is-leaf {
        color: transparent !important;
      }
    }
    .treeTitle {
      background-color: #f7f7f7;
      margin-bottom: 10px;
    }
  }
}
.risk_detail_main_title {
  font-size: 16px;
  font-weight: bold;
  color: #4d4d4d;
  margin-bottom: 20px;
}
.risk_detail_main {
  .detail_flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 36px;
  }
  .detail_table2 {
    width: calc(100% - 320px) !important;
    :deep(.el-input-number) {
      width: 320px !important;
      .el-input__inner {
        width: 320px !important;
      }
    }
  }
  .detail_table3 {
    width: calc(100% - 320px - 120px) !important;
    .el-select,
    .el-input,
    .box1 {
      width: 440px !important;
    }
  }
  .detail_table {
    width: 100%;
    > div:first-child {
      display: flex;
      align-items: center;
      padding: 10px 17px;
      background-color: #fafafa;
      margin-bottom: 10px;
      justify-content: space-between;
      > .box1 {
        width: 320px;
      }
      > .box1:last-child {
        text-align: center;
      }
      > .box2 {
        margin: 0 6px;
      }
    }
    > div:last-child {
      display: flex;
      justify-content: space-between;
      padding: 10px 17px;
      border: 1px dashed #e4e7ed;
      .el-select,
      .el-input {
        width: 320px;
        height: 34px;
        :deep(.el-input__inner) {
          height: 34px;
          line-height: 34px;
        }
      }
    }
  }
  .detail_table1 {
    display: flex;
    padding: 10px 17px;
    border: 1px dashed #e4e7ed;
    .el-radio-group {
      display: flex;
      flex-wrap: wrap;
      // justify-content: space-between;
      .el-radio:nth-child(n + 3) {
        margin-top: 10px;
      }
      .el-radio {
        width: 604px;
        :deep(.el-input-number) {
          width: 320px !important;
          height: 34px !important;
          .el-input__inner {
            width: 320px !important;
            height: 34px !important;
          }
        }
        :deep(.el-radio__label) {
          span {
            width: 70px;
            display: inline-block;
          }
          > span:last-child {
            margin: 0 20px;
            color: #aaabb6;
          }
        }
      }
    }
  }
}
.detail_table4 {
  margin: 16px 0;
  .detail_table4_title {
    margin-bottom: 16px;
  }
  table {
    width: 100%;
    border: 1px solid #ccc;
    border-collapse: collapse;
    font-size: 14px;
  }
  th,
  td {
    height: 30px;
    border: 1px solid #ccc;
    text-align: center;
    min-width: 80px;
  }
  thead {
    background-color: #f2f2f2;
  }
}
.risk_detail_top {
  width: 76%;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
  .el-input,
  .el-select,
  .el-date-editor,
  .el-input-number,
  .el-textarea,
  .risk_detail_top_box {
    width: 320px;
    height: 34px;
  }
}
.riskcolor {
  color: white;
  padding: 4px 6px;
  width: 64px;
}
.riskcolor_table {
  padding: 1px 6px;
  display: inline-block;
}
.riskcolor1 {
  background-color: #eb4047;
}
.riskcolor2 {
  background-color: #ffbf00;
}
.riskcolor3 {
  background-color: #ffff00;
}
.riskcolor4 {
  background-color: #006fbf;
}
</style>
