<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 v-if="WHETHER_HAZARDS === '1'" :span="6">
          <el-form-item
            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 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="60px"
      @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.selectStandardDialogVisible = true"
            >
              选择其他检查标准
            </el-button>
            <el-button type="primary" @click="addStandard">
              添加检查标准
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <layout-table
      ref="tableRef"
      :data="data.list"
      :show-pagination="false"
      max-height="400"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column
        prop="CHECK_CATEGORY_NAME"
        label="检查类别"
        width="180"
      />
      <el-table-column prop="CHECK_ITEM_NAME" label="检查项目" width="180" />
      <el-table-column prop="CHECK_CONTENT" label="检查内容" width="200" />
      <el-table-column prop="CHECK_STANDARD" label="检查标准" width="200" />
      <el-table-column prop="REFERENCE_BASIS" label="参考依据" width="200" />
      <el-table-column prop="CHECK_QUALIFIED" label="检查合格项" width="200" />
      <el-table-column
        prop="CHECK_UNQUALIFIED"
        label="检查不合格项"
        width="200"
      />
      <el-table-column label="操作类型">
        <template #default="{ row }">
          <span v-if="row.OPERATION_TYPE === 1">选择</span>
          <span v-if="row.OPERATION_TYPE === 2">填写</span>
        </template>
      </el-table-column>
    </layout-table>
    <div class="tc mt-10">
      <el-button type="primary" @click="fnSubmit">保存</el-button>
    </div>
    <add-checkstandard
      v-model:visible="data.addOrEditDialog.visible"
      v-model:form="data.addOrEditDialog.form"
      title="添加检查标准"
      type="add"
      :standard-data="data.checkStandardList"
      :category-data="data.categoryList"
      @submit="fnAddStandardSubmit"
    />
    <select-custom
      v-model:visible="data.selectStandardDialogVisible"
      v-model:list-data="data.listAll"
      :standard-data="data.checkStandardList"
      :category-data="data.categoryList"
      @submit="fnSelectStandardSubmit"
    />
  </layout-card>
</template>

<script setup>
import { nextTick, reactive, ref, watchEffect } from "vue";
import {
  layoutFnGetInventoryType,
  layoutFnGetTaskType,
  layoutFnGetTroubleshootingCycle,
  layoutFnGetTroubleshootingType,
} from "@/assets/js/data_dictionary.js";
import LayoutDepartment from "@/components/department/index.vue";
import {
  getPostListAll,
  getStandardLevels,
  getUserListAll,
} from "@/request/data_dictionary.js";
import { useRoute, useRouter } from "vue-router";
import {
  getCheckStandardManagementView,
  setCheckStandardManagementAdd,
  setCheckStandardManagementEdit,
} from "@/request/hazard_investigation.js";
import { debounce } from "throttle-debounce";
import useFormValidate from "@/assets/js/useFormValidate.js";
import { ElMessage } from "element-plus";
import AddCheckstandard from "@/views/hazard_investigation/inventory_management/components/checkstandard_add.vue";
import SelectCustom from "./components/select_custom.vue";

const route = useRoute();
const router = useRouter();
const { ID, WHETHER_HAZARDS } = route.query;
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: {},
  selectStandardDialogVisible: false,
  addOrEditDialog: {
    visible: false,
    form: {
      CHECK_CATEGORY_NAME: "",
      CHECK_ITEM_NAME: "",
      CHECK_CONTENT: "",
      CHECK_STANDARD: "",
      REFERENCE_BASIS: "",
      CHECK_QUALIFIED: "",
      CHECK_UNQUALIFIED: "",
      OPERATION_TYPE: "",
      letItemType: "",
      letCategoryType: "",
    },
  },
  checkStandardList: [],
  categoryList: [],
  itemList: [],
});
const taskTypeList = await layoutFnGetTaskType();
const troubleshootingTypeList = await layoutFnGetTroubleshootingType();
const troubleshootingCycleList = await layoutFnGetTroubleshootingCycle();
const inventoryTypeList = await layoutFnGetInventoryType();

const fnGetData = async () => {
  if (!ID) return;
  const resData = await getCheckStandardManagementView({ ID });
  data.form = resData.pd;
  data.form.dates = [resData.pd.START_DATE, resData.pd.END_DATE];
  data.list = resData.varList;
  data.listAll = [...resData.varList];
};
fnGetData();
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 = "";
};
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.CHECK_CATEGORY_NAME?.indexOf(keyword) > -1 ||
        item.CHECK_ITEM_NAME?.indexOf(keyword) > -1 ||
        item.CHECK_CONTENT?.indexOf(keyword) > -1 ||
        item.CHECK_STANDARD?.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);
  });
};
const addStandard = () => {
  data.addOrEditDialog.visible = true;
};
const fnAddStandardSubmit = (item) => {
  data.list.push({ ...item });
  data.listAll.push(JSON.stringify({ ...item }));
  fnTableSelection();
};
const fnSelectStandardSubmit = (listData) => {
  data.list.push(...listData);
  data.listAll.push(...listData);
  fnTableSelection();
};
const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    const selectionData = tableRef.value.getSelectionRows();
    if (selectionData.length === 0) {
      ElMessage.error("请选择检查内容");
      return;
    }
    const params = {
      ...data.form,
      USER_IDS: data.form.USER_IDS?.join(","),
      LISTITEM: JSON.stringify(selectionData),
      BAO_BAO_DEPARTMENT_ID: data.form.DEPARTMENT_ID,
      BAO_BAO_USER_ID: data.form.USER_ID,
      START_DATE: data.form.dates[0],
      END_DATE: data.form.dates[1],
      BAO_BAO_TYPE: data.form.BAO_BAO_TYPE || "0",
    };
    !ID
      ? await setCheckStandardManagementAdd(params)
      : await setCheckStandardManagementEdit(params);
    ElMessage.success("保存成功");
    router.back();
  },
  { atBegin: true }
);
const fnCheckStandard = async () => {
  const list = await getStandardLevels();
  list.varList.forEach((item) => {
    data.checkStandardList.push({
      DICTIONARIES_ID: item.DICTIONARY_ID,
      NAME: item.DICTIONARY_NAME,
      PARENT_IDS: item.PARENT_IDS,
      PARENT_ID: item.PARENT_ID,
    });
    if (item.PARENT_ID === "0") {
      data.categoryList.push({
        DICTIONARIES_ID: item.DICTIONARY_ID,
        NAME: item.DICTIONARY_NAME,
        PARENT_IDS: item.PARENT_IDS,
        PARENT_ID: item.PARENT_ID,
      });
    }
  });
};
fnCheckStandard();
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>
