<template>
  <layout-card>
    <layout-hidden-view
      :hidden-id="HIDDEN_ID"
      :list-type="LIST_TYPE"
      @throw-data="data.info = $event"
    />
    <el-divider content-position="left">隐患整改</el-divider>
    <el-row :gutter="24">
      <el-col :span="12">
        <el-form
          ref="formRef"
          :model="data.form"
          :rules="rules"
          label-width="100px"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="正常整改" prop="IS_NORMAL">
                <el-radio-group
                  :model-value="data.form.IS_NORMAL"
                  @change="fnIsNormalChange"
                >
                  <el-radio label="1">是</el-radio>
                  <el-radio label="2">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <template v-if="data.form.IS_NORMAL === '2'">
              <el-col :span="12">
                <el-form-item label="整改部门" prop="RECTIFICATIONDEPT">
                  <layout-department
                    v-model="data.form.RECTIFICATIONDEPT"
                    @update:model-value="fnRectificationDepartmentChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="整改人" prop="RECTIFICATIONOR">
                  <el-select v-model="data.form.RECTIFICATIONOR">
                    <el-option
                      v-for="item in data.rectifierUserList"
                      :key="item.USER_ID"
                      :disabled="item.USER_ID === USER_ID"
                      :label="item.NAME"
                      :value="item.USER_ID"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </template>
            <template v-if="data.form.IS_NORMAL === '1'">
              <el-col :span="24">
                <el-form-item prop="RECTIFYDESCR" label="整改描述">
                  <el-input
                    v-model="data.form.RECTIFYDESCR"
                    type="textarea"
                    :autosize="{ minRows: 3 }"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="整改时间" prop="RECTIFICATIONTIME">
                  <el-date-picker
                    v-model="data.form.RECTIFICATIONTIME"
                    value-format="YYYY-MM-DD HH:mm"
                    format="YYYY-MM-DD HH:mm"
                    type="datetime"
                    placeholder="选择日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="整改后图片" prop="afterRectificationFile">
                  <layout-upload
                    v-model:file-list="data.form.afterRectificationFile"
                    :limit="4"
                    accept=".jpg,.jpeg,.png"
                    list-type="picture-card"
                  />
                </el-form-item>
              </el-col>
              <template v-if="data.info.ISCONFIRM === '0'">
                <template
                  v-for="(item, index) in data.form.acceptanceList"
                  :key="item.id"
                >
                  <el-col :span="11">
                    <el-form-item
                      label="验收部门"
                      :prop="'acceptanceList.' + 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="'acceptanceList.' + index + '.USER_ID'"
                      :rules="{
                        required: true,
                        message: '请选择验收人',
                        trigger: 'change',
                      }"
                    >
                      <el-select
                        :model-value="item.USER_ID"
                        @change="
                          verifyDuplicateSelection(
                            data.form.acceptanceList,
                            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.acceptanceList.splice(index, 1)"
                      >
                        删除
                      </el-button>
                    </el-form-item>
                  </el-col>
                </template>
              </template>
              <template v-if="data.info.ISCONFIRM === '1'">
                <el-col :span="12">
                  <el-form-item label="验收部门">
                    <el-input v-model="data.form.DEPARTMENT_NAME" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="验收人">
                    <el-input v-model="data.form.USER_NAME" disabled />
                  </el-form-item>
                </el-col>
              </template>
              <el-col :span="24">
                <el-form-item label="整改方案" prop="HAVESCHEME">
                  <el-radio-group v-model="data.form.HAVESCHEME">
                    <el-radio label="1" value="1">有</el-radio>
                    <el-radio :disabled="data.info.ISCONFIRM === '1'" label="0">
                      无
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <template v-if="data.form.HAVESCHEME === '1'">
                <el-col :span="24">
                  <el-form-item prop="SCREENINGDATE" label="排查日期">
                    <el-date-picker
                      v-model="data.form.SCREENINGDATE"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      type="date"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="LIST_NAME" label="隐患清单">
                    <el-input v-model="data.form.LIST_NAME" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="治理标准" prop="GOVERNSTANDARDS">
                    <el-input v-model="data.form.GOVERNSTANDARDS" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="治理方法" prop="GOVERNMETHOD">
                    <el-input v-model="data.form.GOVERNMETHOD" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="经费落实" prop="EXPENDITURE">
                    <el-input v-model="data.form.EXPENDITURE" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="负责人员" prop="PRINCIPAL">
                    <el-input v-model="data.form.PRINCIPAL" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="工时安排" prop="PROGRAMMING">
                    <el-input v-model="data.form.PROGRAMMING" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="时限要求" prop="TIMELIMITFOR">
                    <el-input v-model="data.form.TIMELIMITFOR" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="工作要求" prop="JOBREQUIREMENT">
                    <el-input v-model="data.form.JOBREQUIREMENT" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="其他事项" prop="OTHERBUSINESS">
                    <el-input v-model="data.form.OTHERBUSINESS" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="方案图片" prop="programmeFile">
                    <layout-upload
                      v-model:file-list="data.form.programmeFile"
                      :limit="99"
                      accept=".jpg,.jpeg,.png"
                      list-type="picture-card"
                    />
                  </el-form-item>
                </el-col>
              </template>
              <el-col :span="24">
                <el-form-item label="整改计划" prop="HAVEPLAN">
                  <el-radio-group v-model="data.form.HAVEPLAN">
                    <el-radio label="1" value="1">有</el-radio>
                    <el-radio :disabled="data.info.ISCONFIRM === '1'" label="0">
                      无
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col v-if="data.form.HAVEPLAN === '1'" :span="24">
                <el-form-item label="计划图片" prop="planFile">
                  <layout-upload
                    v-model:file-list="data.form.planFile"
                    :limit="99"
                    accept=".jpg,.jpeg,.png"
                    list-type="picture-card"
                  />
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </el-form>
      </el-col>
      <el-col :span="12">
        <div
          v-for="item in data.recordLibraryList"
          :key="item.HIDDEN_LIBRARY_ID"
          class="item"
          @click="fnChoice(item)"
        >
          <el-descriptions :column="1" border>
            <el-descriptions-item label="风险单元名称">
              {{ item.RISK_UNIT_NAME }}
            </el-descriptions-item>
            <el-descriptions-item label="隐患部位">
              {{ item.HIDDEN_PART }}
            </el-descriptions-item>
            <el-descriptions-item label="隐患描述">
              {{ item.INSPECTION_BASIS }}
            </el-descriptions-item>
            <el-descriptions-item label="整改意见">
              {{ item.RECTIFYDESCR }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-col>
    </el-row>
    <div class="tc mt">
      <el-button type="primary" @click="fnSubmit">提交</el-button>
    </div>
  </layout-card>
</template>

<script setup>
import LayoutHiddenView from "@/components/hidden_view/index.vue";
import { useRoute, useRouter } from "vue-router";
import { reactive, ref, watch } from "vue";
import LayoutDepartment from "@/components/department/index.vue";
import LayoutUpload from "@/components/upload/index.vue";
import { useUserStore } from "@/pinia/user.js";
import {
  getHiddenDangerRectificationWhy,
  setCustomHiddenDangerRectificationAbnormalSubmit,
  setCustomHiddenDangerRectificationNormalSubmit,
  setHiddenDangerRectificationAbnormalSubmit,
  setHiddenDangerRectificationNormalSubmit,
} from "@/request/hidden_danger_government.js";
import { verifyDuplicateSelection } from "@/assets/js/utils.js";
import { getUserListAll } from "@/request/data_dictionary.js";
import { debounce } from "throttle-debounce";
import useFormValidate from "@/assets/js/useFormValidate.js";
import { cloneDeep } from "lodash-es";
import { ElMessage } from "element-plus";
import { getHiddenDangerDatabaseList } from "@/request/hazard_investigation.js";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const USER_ID = userStore.getUserInfo.USER_ID;
const CORPINFO_ID = userStore.getUserInfo.CORPINFO_ID;
const { HIDDEN_ID, LIST_TYPE } = route.query;
const formRef = ref(null);
const rules = {
  IS_NORMAL: [
    { required: true, message: "正常整改不能为空", trigger: "change" },
  ],
  RECTIFICATIONDEPT: [
    { required: true, message: "整改部门不能为空", trigger: "change" },
  ],
  RECTIFICATIONOR: [
    { required: true, message: "整改人不能为空", trigger: "change" },
  ],
  RECTIFYDESCR: [
    { required: true, message: "整改描述不能为空", trigger: "blur" },
  ],
  RECTIFICATIONTIME: [
    { required: true, message: "整改时间不能为空", trigger: "change" },
  ],
  afterRectificationFile: [
    { required: true, message: "整改后图片不能为空", trigger: "change" },
  ],
  HAVESCHEME: [
    { required: true, message: "整改方案不能为空", trigger: "change" },
  ],
  SCREENINGDATE: [
    { required: true, message: "排查日期不能为空", trigger: "change" },
  ],
  LIST_NAME: [{ required: true, message: "隐患清单不能为空", trigger: "blur" }],
  GOVERNSTANDARDS: [
    { required: true, message: "治理标准不能为空", trigger: "blur" },
  ],
  GOVERNMETHOD: [
    { required: true, message: "治理方法不能为空", trigger: "blur" },
  ],
  EXPENDITURE: [
    { required: true, message: "经费落实不能为空", trigger: "blur" },
  ],
  PRINCIPAL: [{ required: true, message: "负责人员不能为空", trigger: "blur" }],
  PROGRAMMING: [
    { required: true, message: "工时安排不能为空", trigger: "blur" },
  ],
  TIMELIMITFOR: [
    { required: true, message: "时限要求不能为空", trigger: "blur" },
  ],
  JOBREQUIREMENT: [
    { required: true, message: "工作要求不能为空", trigger: "blur" },
  ],
  OTHERBUSINESS: [
    { required: true, message: "其他事项不能为空", trigger: "blur" },
  ],
  programmeFile: [
    { required: true, message: "方案图片不能为空", trigger: "change" },
  ],
  HAVEPLAN: [
    { required: true, message: "整改计划不能为空", trigger: "change" },
  ],
  planFile: [
    { required: true, message: "计划图片不能为空", trigger: "change" },
  ],
};
const data = reactive({
  info: {},
  form: {
    IS_NORMAL: "1",
    RECTIFICATIONDEPT: "",
    RECTIFICATIONOR: "",
    RECTIFYDESCR: "",
    RECTIFICATIONTIME: "",
    afterRectificationFile: [],
    HAVESCHEME: "0",
    SCREENINGDATE: "",
    LIST_NAME: "",
    GOVERNSTANDARDS: "",
    GOVERNMETHOD: "",
    EXPENDITURE: "",
    PRINCIPAL: "",
    PROGRAMMING: "",
    TIMELIMITFOR: "",
    JOBREQUIREMENT: "",
    OTHERBUSINESS: "",
    programmeFile: [],
    HAVEPLAN: "0",
    planFile: [],
    acceptanceList: [
      {
        id: Math.random(),
        DEPARTMENT_ID: "",
        USER_ID: "",
        userList: [],
      },
    ],
  },
  rectifierUserList: [],
  recordLibraryList: [],
  defaultDepartmentId: "",
  defaultUserId: "",
});
const fnGetData = async () => {
  const resData = await getHiddenDangerRectificationWhy({
    CORPINFO_ID,
  });
  data.defaultDepartmentId = resData.deppd.DEPARTMENT_ID;
  data.defaultUserId = resData.userpd.USER_ID;
  data.form.DEPARTMENT_NAME = resData.deppd.NAME;
  data.form.USER_NAME = resData.userpd.USERNAME;
  await fnInspectDepartmentChange(data.defaultDepartmentId, 0);
  // data.form.acceptanceList[0].DEPARTMENT_ID = data.defaultDepartmentId;
  // data.form.acceptanceList[0].USER_ID = data.defaultUserId;
};
fnGetData();
const fnAddInspectedList = () => {
  data.form.acceptanceList.push({
    id: Math.random(),
    DEPARTMENT_ID: "",
    USER_ID: "",
    userList: [],
  });
};
const fnInspectDepartmentChange = async (event, index) => {
  data.form.acceptanceList[index].USER_ID = "";
  const resData = await getUserListAll({
    DEPARTMENT_ID: event,
  });
  data.form.acceptanceList[index].userList = resData.userList;
};
const fnRectificationDepartmentChange = async (event) => {
  data.form.RECTIFICATIONOR = "";
  data.rectifierUserList = [];
  const resData = await getUserListAll({
    DEPARTMENT_ID: event,
  });
  data.rectifierUserList = resData.userList;
};
const fnIsNormalChange = async (event) => {
  formRef.value.resetFields();
  data.form.acceptanceList = [];
  fnAddInspectedList();
  await fnInspectDepartmentChange(data.defaultDepartmentId, 0);
  data.form.acceptanceList[0].DEPARTMENT_ID = data.defaultDepartmentId;
  data.form.acceptanceList[0].USER_ID = data.defaultUserId;
  data.rectifierUserList = [];
  data.form.IS_NORMAL = event;
};
const fnGetHiddenDangerDatabaseList = async () => {
  const resData = await getHiddenDangerDatabaseList({
    RISK_UNIT_NAME: data.info.RISK_UNIT,
    HIDDEN_PART: data.info.HIDDENPART,
  });
  data.recordLibraryList = resData.varList;
};
watch(
  () => data.info,
  () => {
    fnGetHiddenDangerDatabaseList();
  }
);
const fnChoice = (item) => {
  data.form.RECTIFYDESCR = item.RECTIFYDESCR;
};
const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    if (data.form.IS_NORMAL === "1") {
      const formData = new FormData();
      Object.keys(data.form).forEach((key) => {
        formData.append(key, data.form[key]);
      });
      formData.append("HIDDEN_ID", HIDDEN_ID);
      formData.append(
        "LISTNAME",
        data.form.LIST_NAME ? data.form.LIST_NAME : ""
      );
      for (let i = 0; i < data.form.programmeFile.length; i++) {
        formData.append("scheme_files", data.form.programmeFile[i].raw);
      }
      for (let i = 0; i < data.form.afterRectificationFile.length; i++) {
        formData.append(
          "rectify_files",
          data.form.afterRectificationFile[i].raw
        );
      }
      for (let i = 0; i < data.form.planFile.length; i++) {
        formData.append("plan_files", data.form.planFile[i].raw);
      }
      formData.append("CHECKDEPT", data.form.acceptanceList[0].DEPARTMENT_ID);
      formData.append("CHECKOR", data.form.acceptanceList[0].USER_ID);
      const acceptanceList = cloneDeep(data.form.acceptanceList);
      if (acceptanceList.length > 0) acceptanceList.splice(0, 1);
      formData.append("OTHER", JSON.stringify(acceptanceList));
      formData.delete("afterRectificationFile");
      formData.delete("programmeFile");
      formData.delete("planFile");
      formData.delete("acceptanceList");
      LIST_TYPE === "1"
        ? await setHiddenDangerRectificationNormalSubmit(formData)
        : await setCustomHiddenDangerRectificationNormalSubmit(formData);
    } else {
      LIST_TYPE === "1"
        ? await setHiddenDangerRectificationAbnormalSubmit({
            HIDDEN_ID,
            RECTIFICATIONOR: data.form.RECTIFICATIONOR,
            RECTIFICATIONDEPT: data.form.RECTIFICATIONDEPT,
          })
        : await setCustomHiddenDangerRectificationAbnormalSubmit({
            HIDDEN_ID,
            RECTIFICATIONOR: data.form.RECTIFICATIONOR,
            RECTIFICATIONDEPT: data.form.RECTIFICATIONDEPT,
          });
    }
    ElMessage.success("保存成功");
    router.back();
  },
  { atBegin: true }
);
</script>

<style scoped lang="scss">
.item {
  cursor: pointer;
  border-bottom: 1px dashed #ccc;
  padding: 10px 0;

  &:first-child {
    padding-top: 0;
  }
}
</style>
