<template>
  <layout-card>
    <el-divider content-position="left">清单信息</el-divider>
    <el-form
      ref="formRef"
      :model="data.form"
      :rules="rules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="清单名称" prop="NAME">
            <el-input v-model="data.form.NAME" placeholder="请输入内容" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            v-if="SPECIAL_ENTERPRISES.includes(CORPINFO_ID)"
            label="是否包保责任人任务"
            prop="BAO_BAO_TYPE"
            label-width="160px"
          >
            <el-select v-model="data.form.BAO_BAO_TYPE">
              <el-option
                v-for="item in [
                  { BIANMA: '0', NAME: '否' },
                  { BIANMA: '1', NAME: '是' },
                ]"
                :key="item.BIANMA"
                :label="item.NAME"
                :value="item.BIANMA"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="data.form.BAO_BAO_TYPE === '1'" :span="6">
          <el-form-item label="任务类型" prop="TASK_TYPE">
            <el-select v-model="data.form.TASK_TYPE">
              <el-option
                v-for="item in taskTypeList"
                :key="item.DICTIONARIES_ID"
                :label="item.NAME"
                :value="item.DICTIONARIES_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item prop="DEPARTMENT_ID" label="部门">
            <layout-department
              v-model="data.form.DEPARTMENT_ID"
              @update:model-value="fnDepartmentChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="岗位" prop="POST_ID">
            <el-select v-model="data.form.POST_ID" @change="fnPostChange">
              <el-option
                v-for="item in data.postList"
                :key="item.POST_ID"
                :label="item.NAME"
                :value="item.POST_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item v-if="!LISTMANAGER_ID" label="负责人" prop="USER_IDS">
            <el-select v-model="data.form.USER_IDS" multiple>
              <el-option
                v-for="item in data.userList"
                :key="item.USER_ID"
                :label="item.NAME"
                :value="item.USER_ID"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-else-if="LISTMANAGER_ID"
            label="负责人"
            prop="USER_ID"
          >
            <el-select v-model="data.form.USER_ID">
              <el-option
                v-for="item in data.userList"
                :key="item.USER_ID"
                :label="item.NAME"
                :value="item.USER_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="排查类型" prop="SCREENTYPE">
            <el-select v-model="data.form.SCREENTYPE">
              <el-option
                v-for="item in troubleshootingTypeList"
                :key="item.BIANMA"
                :label="item.NAME"
                :value="item.BIANMA"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="排查周期" prop="PERIOD">
            <el-select v-model="data.form.PERIOD">
              <el-option
                v-for="item in troubleshootingCycleList"
                :key="item.BIANMA"
                :label="item.NAME"
                :value="item.BIANMA"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="清单类型" prop="TYPE">
            <el-select v-model="data.form.TYPE">
              <el-option
                v-for="item in inventoryTypeList"
                :key="item.BIANMA"
                :label="item.NAME"
                :value="item.BIANMA"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          v-if="
            data.form.TYPE === 'listType0005' ||
            data.form.TYPE === 'listType0006'
          "
          :key="data.form.TYPE"
          :span="6"
        >
          <el-form-item label="排查日期" prop="dates">
            <el-date-picker
              v-model="data.form.dates"
              :disabled-date="
                data.form.TYPE === 'listType0006' ? fnDisabledDate : null
              "
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-divider content-position="left">检查内容</el-divider>
    <el-form
      :model="data.searchForm"
      label-width="130px"
      @submit.prevent="fnGetDataFilter"
    >
      <el-row>
        <el-col :span="6">
          <el-form-item label="风险点/辨识部位" prop="KEYWORDS">
            <el-input
              v-model="data.searchForm.KEYWORDS"
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="10px">
            <el-button type="primary" native-type="submit">搜索</el-button>
            <el-button native-type="reset" @click="fnGetDataFilter">
              重置
            </el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="end">
            <el-button
              type="primary"
              @click="data.selectRiskDialogVisible = true"
            >
              选择其他存在风险
            </el-button>
            <el-button
              type="primary"
              @click="data.addOrEditDialog.visible = true"
            >
              添加存在风险
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <layout-table
      ref="tableRef"
      :data="data.list"
      :show-pagination="false"
      max-height="400"
      row-key="RISKCHECKITEM_ID"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column prop="RISKUNITNAME" label="风险点（单元）" width="180" />
      <el-table-column prop="PARTSNAME" label="辨识部位" width="180" />
      <el-table-column prop="RISK_DESCR" label="存在风险" width="300" />
      <el-table-column prop="DNAME5" label="风险分级" width="180" />
      <el-table-column prop="USERNAME" label="管控负责人" width="180" />
      <el-table-column prop="CHECK_CONTENT" label="检查内容" />
    </layout-table>
    <div class="tc mt-10">
      <el-button type="primary" @click="fnSubmit">保存</el-button>
    </div>
    <add-risk
      title="添加存在风险"
      type="add"
      v-model:visible="data.addOrEditDialog.visible"
      v-model:form="data.addOrEditDialog.form"
      :control="false"
      @get-data="fnAddRiskSubmit"
    />
    <select-risk v-model:visible="data.selectRiskDialogVisible" />
  </layout-card>
</template>

<script setup>
import { nextTick, reactive, ref, watchEffect } from "vue";
import { SPECIAL_ENTERPRISES } from "@/assets/js/constant.js";
import { useUserStore } from "@/pinia/user.js";
import {
  layoutFnGetInventoryType,
  layoutFnGetTaskType,
  layoutFnGetTroubleshootingCycle,
  layoutFnGetTroubleshootingType,
} from "@/assets/js/data_dictionary.js";
import LayoutDepartment from "@/components/department/index.vue";
import { getPostListAll, getUserListAll } from "@/request/data_dictionary.js";
import { useRoute, useRouter } from "vue-router";
import { getInventoryManagementInspectionItems } from "@/request/hazard_investigation.js";
import { debounce } from "throttle-debounce";
import useFormValidate from "@/assets/js/useFormValidate.js";
import { ElMessage } from "element-plus";
import AddRisk from "@/views/risk_control/ledger/components/add.vue";
import SelectRisk from "./components/select_risk.vue";

const route = useRoute();
const router = useRouter();
const { LISTMANAGER_ID } = route.query;
const userStore = useUserStore();
const CORPINFO_ID = userStore.getUserInfo.CORPINFO_ID;
const rules = {
  NAME: [{ required: true, message: "清单名称不能为空", trigger: "blur" }],
  BAO_BAO_TYPE: [
    {
      required: true,
      message: "是否包保责任人任务不能为空",
      trigger: "change",
    },
  ],
  TASK_TYPE: [
    { required: true, message: "任务类型不能为空", trigger: "change" },
  ],
  DEPARTMENT_ID: [
    { required: true, message: "部门不能为空", trigger: "change" },
  ],
  POST_ID: [{ required: true, message: "岗位不能为空", trigger: "change" }],
  USER_IDS: [{ required: true, message: "负责人不能为空", trigger: "change" }],
  USER_ID: [{ required: true, message: "负责人不能为空", trigger: "change" }],
  SCREENTYPE: [
    { required: true, message: "排查类型不能为空", trigger: "change" },
  ],
  PERIOD: [{ required: true, message: "排查周期不能为空", trigger: "change" }],
  TYPE: [{ required: true, message: "清单类型不能为空", trigger: "change" }],
  dates: [{ required: true, message: "排查日期不能为空", trigger: "change" }],
};
const formRef = ref(null);
const tableRef = ref(null);
const data = reactive({
  form: {
    NAME: "",
    BAO_BAO_TYPE: "",
    TASK_TYPE: "",
    DEPARTMENT_ID: "",
    POST_ID: "",
    USER_IDS: [],
    USER_ID: "",
    SCREENTYPE: "",
    PERIOD: "",
    TYPE: "",
    dates: [],
  },
  postList: [],
  userList: [],
  list: [],
  listAll: [],
  searchForm: {},
  selectRiskDialogVisible: false,
  addOrEditDialog: {
    visible: false,
    form: {
      DEPARTMENT_ID: "",
      USER_ID: "",
      RISK_UNIT_ID: "",
      IDENTIFICATION_ID: "",
      RISK_DESCR: "",
      LIKELIHOOD: "",
      EXPOSURE: "",
      CONSEQUENCE: "",
      LEVEL_NAME: "",
      DANGER: "",
      MEASURES: "",
      ACCIDENTS: [],
      EME_MEASURES: "",
    },
  },
});
const taskTypeList = await layoutFnGetTaskType();
const troubleshootingTypeList = await layoutFnGetTroubleshootingType();
const troubleshootingCycleList = await layoutFnGetTroubleshootingCycle();
const inventoryTypeList = await layoutFnGetInventoryType();
const fnGetData = async () => {
  const resData = await getInventoryManagementInspectionItems({
    DEPARTMENT_ID: data.form.DEPARTMENT_ID,
    POST_ID: data.form.POST_ID,
  });
  data.list = [...tableRef.value.getSelectionRows(), ...resData.varList];
  data.listAll = [...tableRef.value.getSelectionRows(), ...resData.varList];
  fnTableSelection();
};
const fnDepartmentChange = () => {
  data.postList = [];
  data.userList = [];
  data.form.POST_ID = "";
  data.form.USER_IDS = [];
  data.form.USER_ID = "";
};
const fnPostChange = () => {
  data.userList = [];
  data.form.USER_IDS = [];
  data.form.USER_ID = "";
  fnGetData();
};
const fnGetPost = async (DEPARTMENT_ID) => {
  const resData = await getPostListAll({ DEPARTMENT_ID });
  data.postList = resData.postList;
};
const fnGetUser = async (POST_ID) => {
  const resData = await getUserListAll({ POST_ID });
  data.userList = resData.userList;
};
const fnDisabledDate = (time) => {
  return time.getTime() < Date.now();
};
const fnGetDataFilter = () => {
  const keyword = data.searchForm.KEYWORDS;
  if (keyword) {
    data.list = data.listAll.filter(
      (item) =>
        item.RISKUNITNAME.indexOf(keyword) > -1 ||
        item.PARTSNAME.indexOf(keyword) > -1
    );
  } else {
    data.list = data.listAll;
  }
  fnTableSelection();
};
const fnTableSelection = async () => {
  const selectionData = tableRef.value.getSelectionRows();
  await nextTick();
  selectionData.forEach((item) => {
    tableRef.value.toggleRowSelection(item, true);
  });
};
const fnAddRiskSubmit = (row) => {
  data.list.push(row);
  data.listAll.push(row);
};
const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    ElMessage.success("保存成功");
    router.back();
  },
  { atBegin: true }
);
watchEffect(() => {
  if (data.form.DEPARTMENT_ID) fnGetPost(data.form.DEPARTMENT_ID);
  if (data.form.POST_ID) fnGetUser(data.form.POST_ID);
});
</script>

<style scoped lang="scss"></style>
