<template>
  <layout-card>
    <el-divider content-position="left">隐患排查清单信息</el-divider>
    <el-descriptions :column="2" border>
      <el-descriptions-item label="清单名称">
        {{ info.NAME }}
      </el-descriptions-item>
      <el-descriptions-item label="排查清单类型">
        {{ info.SCREENTYPENAME }}
      </el-descriptions-item>
      <el-descriptions-item
        :label="info.BAO_BAO_TYPE === '1' ? '包保责任人部门' : '所属部门'"
      >
        {{ info.DEPARTMENT_NAME }}
      </el-descriptions-item>
      <el-descriptions-item
        :label="info.BAO_BAO_TYPE === '1' ? '包保责任人岗位' : '所属岗位'"
      >
        {{ info.POST_NAME }}
      </el-descriptions-item>
      <el-descriptions-item label="排查周期">
        {{ info.PERIODNAME }}
      </el-descriptions-item>
      <el-descriptions-item label="清单类型">
        {{ info.TYPENAME }}
      </el-descriptions-item>
      <el-descriptions-item
        v-if="info.TYPE === 'listType0006'"
        label="排查日期"
      >
        {{ info.START_DATE }} - {{ info.END_DATE }}
      </el-descriptions-item>
      <el-descriptions-item v-if="info.BAO_BAO_TYPE === '1'" label="包保责任人">
        {{ info.USER_NAME }}
      </el-descriptions-item>
    </el-descriptions>
    <el-divider content-position="left">检查内容</el-divider>
    <layout-table :data="inspectionList" :show-pagination="false">
      <el-table-column label="序号" width="70" type="index" />
      <el-table-column
        prop="CHECK_CATEGORY_NAME"
        label="检查类别"
        width="150"
      />
      <el-table-column prop="CHECK_ITEM_NAME" label="检查项目" width="150" />
      <el-table-column prop="CHECK_CONTENT" label="检查内容" width="200" />
      <el-table-column prop="CHECK_STANDARD" label="检查标准" width="250" />
      <el-table-column prop="REFERENCE_BASIS" label="参考依据" width="250" />
      <el-table-column prop="CHECK_RESULT" label="检查结果" width="200" />
      <el-table-column label="操作">
        <template #default="{ row, $index }">
          <el-radio-group v-model="row.ISNORMAL" :disabled="row.HASHIDDEN > 0">
            <el-radio :label="0" @click.prevent="fnQualified($index, row)">
              合格
              <el-tooltip
                v-if="entrance === 'supplementaryRecording'"
                content="注意：补录时，不允许添加隐患"
                placement="top"
              >
                <el-icon><warning-filled /></el-icon>
              </el-tooltip>
            </el-radio>
            <el-radio
              :label="1"
              :disabled="entrance === 'supplementaryRecording'"
              @click.prevent="fnUnqualified($index, row)"
            >
              不合格
            </el-radio>
            <el-radio
              :label="2"
              :disabled="entrance === 'supplementaryRecording'"
              @click.prevent="fnNotInvolved($index, row)"
            >
              不涉及
            </el-radio>
          </el-radio-group>
        </template>
      </el-table-column>
    </layout-table>
    <el-divider content-position="left">其他隐患</el-divider>
    <div class="tr mb-10">
      <el-button
        :disabled="entrance === 'supplementaryRecording'"
        type="primary"
        @click="fnAddOrEditOtherHidden({}, 'add')"
      >
        添加
      </el-button>
    </div>
    <layout-table :data="otherHiddenList" :show-pagination="false">
      <el-table-column label="序号" width="70" type="index" />
      <el-table-column prop="HIDDENDESCR" label="隐患描述" />
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button
            type="primary"
            text
            link
            @click="fnAddOrEditOtherHidden(row, 'edit')"
          >
            修改
          </el-button>
          <el-button
            type="primary"
            text
            link
            @click="fnDeleteOtherHidden(row.HIDDEN_ID)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </layout-table>
    <el-form
      ref="formRef"
      :model="data.form"
      :rules="rules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="检查时间" prop="CHECK_TIME">
            <el-date-picker
              v-model="data.form.CHECK_TIME"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetime"
              placeholder="这里输入检查时间"
              :disabled-date="fnDisabledDate"
            />
          </el-form-item>
        </el-col>
        <template
          v-for="(item, index) in data.form.inspectedList"
          :key="item.id"
        >
          <el-col :span="11">
            <el-form-item
              label="检查部门"
              :prop="'inspectedList.' + index + '.DEPARTMENT_ID'"
              :rules="{
                required: true,
                message: '请选择检查部门',
                trigger: 'change',
              }"
            >
              <layout-department
                v-model="item.DEPARTMENT_ID"
                @update:model-value="fnInspectDepartmentChange($event, index)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item
              label="检查人"
              :prop="'inspectedList.' + index + '.USER_ID'"
              :rules="{
                required: true,
                message: '请选择检查人',
                trigger: 'change',
              }"
            >
              <el-select
                :model-value="item.USER_ID"
                @change="
                  verifyDuplicateSelection(
                    data.form.inspectedList,
                    index,
                    'USER_ID',
                    $event
                  )
                "
              >
                <el-option
                  v-for="item1 in item.userList"
                  :key="item1.USER_ID"
                  :label="item1.NAME"
                  :value="item1.USER_ID"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item label-width="10px">
              <el-button
                v-if="index === 0"
                type="primary"
                @click="fnAddInspectedList"
              >
                添加
              </el-button>
              <el-button
                v-if="index !== 0"
                type="danger"
                @click="data.form.inspectedList.splice(index, 1)"
              >
                删除
              </el-button>
            </el-form-item>
          </el-col>
        </template>
        <el-col v-if="entrance === 'supplementaryRecording'" :span="24">
          <el-form-item label="补录原因" prop="REASON">
            <el-input v-model="data.form.REASON" type="textarea" autosize />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="DESCR">
            <el-input
              v-model="data.form.DESCR"
              type="textarea"
              :autosize="{
                minRows: 3,
              }"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="tc mt-10">
      <el-button type="primary" @click="fnSubmit">保存</el-button>
    </div>
    <qualified
      :id="data.qualifiedDialog.RECORDITEM_ID"
      v-model:visible="data.qualifiedDialog.visible"
      v-model:form="data.qualifiedDialog.form"
      :index="data.qualifiedDialog.index"
      :writeresults="data.qualifiedDialog.writeresults"
      @submit="fnResultsSubmit"
    />
    <un-qualified
      v-model:visible="data.unQualifiedDialog.visible"
      v-model:form="data.unQualifiedDialog.form"
      :list-manager-id="ID"
      :type="data.unQualifiedDialog.type"
      :hidden-type="data.unQualifiedDialog.hiddenType"
      :info="{ ...data.unQualifiedDialog.info, ...info.value }"
      :longitude="data.longitude"
      :latitude="data.latitude"
      :list-type="2"
      @submit="fnHiddenSubmit"
    />
  </layout-card>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref } from "vue";
import {
  getCheckStandardOtherHiddenList,
  getCustomHiddenDangerView,
  setCustomHiddenDangerDelete,
  getCheckStandardManagementView,
  setCheckStandardSupplementaryRecordingSubmit,
  setCheckStandardSubmit,
} from "@/request/hazard_investigation.js";
import { useRoute, useRouter } from "vue-router";
import useListData from "@/assets/js/useListData.js";
import LayoutDepartment from "@/components/department/index.vue";
import UnQualified from "./components/un_qualified.vue";

import {
  addingPrefixToFile,
  getFileSuffix,
  verifyDuplicateSelection,
} from "@/assets/js/utils.js";
import { getUserListAll } from "@/request/data_dictionary.js";
import { getViewImg } from "@/request/api.js";
import { debounce } from "throttle-debounce";
import useFormValidate from "@/assets/js/useFormValidate.js";
import { ElMessage, ElMessageBox } from "element-plus";
import Qualified from "./components/qualified.vue";
import { cloneDeep } from "lodash-es";
import { WarningFilled } from "@element-plus/icons-vue";

const route = useRoute();
const router = useRouter();
const { ID, CHECKRECORD_ID, DATEEND, DATESTART } = route.query;
const props = defineProps({
  entrance: {
    type: String,
    default: "",
  },
});
const rules = {
  CHECK_TIME: [
    { required: true, message: "请选择检查时间", trigger: "change" },
  ],
  REASON: [{ required: true, message: "请输入补录原因", trigger: "blur" }],
};
const formRef = ref(null);
const info = ref({});
const data = reactive({
  longitude: 0,
  latitude: 0,
  form: {
    CHECK_TIME: "",
    REASON: "",
    inspectedList: [],
  },
  qualifiedDialog: {
    visible: false,
    writeresults: false,
    index: 0,
    RECORDITEM_ID: "",
    form: { file: [] },
  },
  unQualifiedDialog: {
    visible: false,
    type: "",
    index: "",
    hiddenType: "",
    info: {},
    form: {
      HIDDENPART: "",
      HIDDENDESCR: "",
      HIDDENLEVEL: "",
      HIDDEN_CATEGORY: "",
      HIDDENTYPE: [],
      hiddenImgs: [],
      videoFiles: [],
      RECTIFICATIONTYPE: "2",
      RECTIFYDESCR: "",
      rectifyImgs: [],
      RECTIFICATIONDEADLINE: "",
      RECTIFICATIONDEPT: "",
      RECTIFICATIONOR: "",
    },
  },
});
const { list: inspectionList } = useListData(getCheckStandardManagementView, {
  otherParams: { ID },
  usePagination: false,
  callbackFn: (list, resData) => {
    for (let i = 0; i < list.length; i++) {
      if (props.entrance === "supplementaryRecording") {
        continue;
      }
      list[i].CHECK_RESULT = "不涉及";
      if (list[i].HASHIDDEN <= 0) list[i].ISNORMAL = 2;
    }
    info.value = resData.pd;
  },
});
const { list: otherHiddenList, fnGetData: fnGetOtherHidden } = useListData(
  getCheckStandardOtherHiddenList,
  {
    otherParams: { ID },
    usePagination: false,
    key: "hiddenList",
  }
);
onMounted(() => {
  const geolocation = new window.BMapGL.Geolocation();
  geolocation.getCurrentPosition(async (r) => {
    if (!r) {
      await ElMessageBox.alert("获取位置信息失败，请刷新重试", {
        type: "warning",
      });
      window.location.reload();
    }
    data.longitude = r.longitude;
    data.latitude = r.latitude;
  });
});

const fnResultsSubmit = (CHECK_RESULT, index) => {
  if (CHECK_RESULT) {
    inspectionList.value[index].CHECK_RESULT = CHECK_RESULT;
  } else {
    inspectionList.value[index].CHECK_RESULT =
      inspectionList.value[index].CHECK_QUALIFIED;
  }
  inspectionList.value[index].ISNORMAL = 0;
};
const fnHiddenSubmit = (currentHiddenId, HIDDENDESCR) => {
  const { hiddenType, index } = data.unQualifiedDialog;
  if (hiddenType === "unqualified") {
    inspectionList.value[index].ISNORMAL = 1;
    inspectionList.value[index].HIDDEN_ID = currentHiddenId;
    inspectionList.value[index].CHECK_RESULT = HIDDENDESCR;
    inspectionList.value[index].CHECK_UNQUALIFIED = HIDDENDESCR;
    nextTick();
  }
  if (hiddenType === "otherHidden") {
    fnGetOtherHidden();
  }
};

const fnDisabledDate = (time) => {
  if (DATEEND && DATESTART)
    return (
      time.getTime() > new Date(DATEEND).getTime() ||
      time.getTime() < new Date(DATESTART).getTime()
    );
  else return false;
};
// 合格
const fnQualified = async (index, row) => {
  if (row.HASHIDDEN > 0) return;
  //  选择还是填写  OPERATION_TYPE 1选择 2填写
  if (row.OPERATION_TYPE === 1) {
    data.qualifiedDialog.writeresults = false;
  } else {
    data.qualifiedDialog.writeresults = true;
    data.qualifiedDialog.form.CHECK_RESULT =
      row.CHECK_RESULT !== "不涉及" ? row.CHECK_RESULT : row.CHECK_QUALIFIED;
  }
  data.qualifiedDialog.visible = true;
  data.qualifiedDialog.index = index;
  await nextTick();
  data.qualifiedDialog.RECORDITEM_ID = row.RECORDITEM_ID;
  if (row.ISNORMAL === 1) fnRemoveUnqualified(index);
  else if (row.ISNORMAL !== 1) {
    const resData = await getViewImg({
      FOREIGN_KEY: row.RECORDITEM_ID,
      TYPE: "14",
    });
    data.qualifiedDialog.form.file = addingPrefixToFile(resData.imgs);
  }
  // inspectionList.value[index].ISNORMAL = 0;
};
// 不涉及
const fnNotInvolved = (index, row) => {
  if (row.HASHIDDEN > 0 || props.entrance === "supplementaryRecording") return;
  fnRemoveUnqualified(index);
  inspectionList.value[index].ISNORMAL = 2;
  row.CHECK_RESULT = "不涉及";
};
const fnRemoveUnqualified = (index) => {
  inspectionList.value[index].HIDDEN_ID = "";
};
const fnUnqualified = async (index, row) => {
  if (row.HASHIDDEN > 0 || props.entrance === "supplementaryRecording") return;
  data.unQualifiedDialog.visible = true;
  await nextTick();
  if (
    inspectionList.value[index].ISNORMAL === 0 ||
    inspectionList.value[index].ISNORMAL === 2
  )
    data.unQualifiedDialog.type = "add";
  else if (inspectionList.value[index].ISNORMAL === 1) {
    data.unQualifiedDialog.type = "edit";
    await fnGetHiddenDangerView(inspectionList.value[index].HIDDEN_ID);
  }
  data.unQualifiedDialog.info = row;
  data.unQualifiedDialog.form.HIDDENDESCR = row.CHECK_UNQUALIFIED;
  data.unQualifiedDialog.index = index;
  data.unQualifiedDialog.hiddenType = "unqualified";
};
const fnGetHiddenDangerView = async (HIDDEN_ID) => {
  const resData = await getCustomHiddenDangerView({
    HIDDEN_ID,
  });
  data.unQualifiedDialog.form = resData.pd;
  const HIDDENTYPE = [];
  const videoFiles = [];
  const hiddenImgs = [];
  for (let i = 0; i < resData.hImgs.length; i++) {
    if (getFileSuffix(resData.hImgs[i].FILEPATH) === "mp4")
      videoFiles.push(...addingPrefixToFile([resData.hImgs[i]]));
    else hiddenImgs.push(...addingPrefixToFile([resData.hImgs[i]]));
  }
  data.unQualifiedDialog.form.videoFiles = videoFiles;
  data.unQualifiedDialog.form.hiddenImgs = hiddenImgs;
  data.unQualifiedDialog.form.rectifyImgs = addingPrefixToFile(resData.rImgs);
  if (resData.pd.HIDDENTYPE1) HIDDENTYPE.push(resData.pd.HIDDENTYPE1);
  if (resData.pd.HIDDENTYPE2) HIDDENTYPE.push(resData.pd.HIDDENTYPE2);
  if (resData.pd.HIDDENTYPE3) HIDDENTYPE.push(resData.pd.HIDDENTYPE3);
  data.unQualifiedDialog.form.HIDDENTYPE = HIDDENTYPE;
};
// const fnHiddenSubmit = (currentHiddenId) => {
//   const { hiddenType, index } = data.unQualifiedDialog;
//   if (hiddenType === "unqualified") {
//     inspectionList.value[index].ISNORMAL = 1;
//     inspectionList.value[index].HIDDEN_ID = currentHiddenId;
//   }
//   if (hiddenType === "otherHidden") {
//     fnGetOtherHidden();
//   }
// };
const fnAddInspectedList = () => {
  data.form.inspectedList.push({
    id: Math.random(),
    DEPARTMENT_ID: "",
    USER_ID: "",
    userList: [],
  });
};
fnAddInspectedList();
const fnInspectDepartmentChange = async (event, index) => {
  data.form.inspectedList[index].USER_ID = "";
  const resData = await getUserListAll({
    DEPARTMENT_ID: event,
    NOMAIN: "1",
  });
  data.form.inspectedList[index].userList = resData.userList;
};
const fnDeleteOtherHidden = async (HIDDEN_ID) => {
  await ElMessageBox.confirm("确定要删除吗？", {
    type: "warning",
  });
  await setCustomHiddenDangerDelete({ HIDDEN_ID });
  fnGetOtherHidden();
};
const fnAddOrEditOtherHidden = async (row, type) => {
  data.unQualifiedDialog.visible = true;
  await nextTick();
  data.unQualifiedDialog.type = type;
  data.unQualifiedDialog.info = row;
  data.unQualifiedDialog.hiddenType = "otherHidden";
  data.unQualifiedDialog.form.HIDDENDESCR = "";
  if (type === "edit") await fnGetHiddenDangerView(row.HIDDEN_ID);
};
const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    const items = [];
    const ids = [];
    for (let i = 0; i < inspectionList.value.length; i++) {
      const item = {};
      item.CUSTOM_ITEM_ID = inspectionList.value[i].CUSTOM_ITEM_ID;
      item.ISNORMAL = inspectionList.value[i].ISNORMAL;
      item.RECORDITEM_ID = inspectionList.value[i].RECORDITEM_ID;
      item.CHECK_RESULT = inspectionList.value[i].CHECK_RESULT;
      items.push(item);
      if (inspectionList.value[i].ISNORMAL === 1)
        ids.push(inspectionList.value[i].HIDDEN_ID);
    }
    const inspectedList = cloneDeep(data.form.inspectedList);
    if (inspectedList.length > 0) inspectedList.splice(0, 1);
    const params = {
      ID,
      CUSTOM_NAME: info.value.NAME,
      CHECK_TIME: data.form.CHECK_TIME,
      DESCR: data.form.DESCR,
      ITEMS: JSON.stringify(items),
      IDS: ids.join(","),
      CHECKDEPT: data.form.inspectedList[0].DEPARTMENT_ID,
      CHECKOR: data.form.inspectedList[0].USER_ID,
      OTHER: JSON.stringify(inspectedList),
      LONGITUDE: data.longitude,
      LATITUDE: data.latitude,
    };
    if (props.entrance === "supplementaryRecording") {
      params.REASON = data.form.REASON;
      params.CHECKRECORD_ID = CHECKRECORD_ID;
      await setCheckStandardSupplementaryRecordingSubmit(params);
    } else await setCheckStandardSubmit(params);
    ElMessage.success("操作成功");
    router.back();
  },
  { atBegin: true }
);
</script>

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