<template>
  <view class="container">
    <u--form
      ref="formRef"
      label-position="left"
      :model="form"
      :rules="rules"
      label-width="auto"
    >
      <u-divider
        text="检查人"
        text-position="left"
        text-color="rgb(42, 86, 247)"
        line-color="rgb(42, 86, 247)"
        dashed
      />
      <view style="display: flex; justify-content: end">
        <u-button
          type="primary"
          text="添加"
          :custom-style="{ width: '150upx', margin: 0, height: '50upx' }"
          @click="fnAddInspectUserList"
        />
      </view>
      <view
        v-for="(item, index) in inspectUserList"
        :key="item.id"
        class="user_item"
      >
        <u-form-item
          label="检查部门"
          border-bottom
          required
          @click="fnInspectionDepartmentTreeShow(index, item.count === 1)"
        >
          <u--input
            :value="item.DEPARTMENT_NAME || '请选择'"
            readonly
            border="none"
            input-align="right"
          />
          <u-icon name="arrow-right" color="#999999"></u-icon>
        </u-form-item>
        <u-form-item
          label="检查人"
          border-bottom
          required
          @click="fnInspectionUserPickerShow(index, item.count === 1)"
        >
          <u--input
            :value="item.USER_NAME || '请选择'"
            readonly
            border="none"
            input-align="right"
          />
          <u-icon name="arrow-right" color="#999999"></u-icon>
        </u-form-item>
        <view v-if="index !== 0" class="delete">
          <u-icon
            v-if="item.count !== 1"
            name="close-circle-fill"
            color="red"
            :size="20"
            @click="fnDeleteInspectUserList(index)"
          />
        </view>
        <tki-tree
          ref="inspectionDepartmentTreeRef"
          :range="inspectionDepartment"
          id-key="id"
          range-key="name"
          children-name="nodes"
          select-parent
          @confirm="fnInspectionDepartmentTreeConfirm($event, index)"
        />
        <u-picker
          :show="item.userPickerShow"
          :columns="item.userList"
          key-name="NAME"
          @cancel="fnInspectionUserPickerShow(index, false)"
          @confirm="fnInspectionUserPickerConfirm($event, index)"
        />
      </view>
      <div style="display: flex; gap: 20rpx">
        <u-button type="primary" text="保存" @click="fnSubmit" />
      </div>
    </u--form>
  </view>
</template>

<script>
import {
  getInspectType,
  getUser,
  setSpecialRectificationInspectionAdd,
  setSpecialRectificationInspectionHiddenImgAdd,
  setSpecialRectificationInspectionImgAdd,
} from "@/api";
import TkiTree from "@/components/tki-tree/tki-tree.vue";
import { arrayObjectDeduplication } from "@/utils/utils";
import debounce from "@/utils/debounce";
import {
  getAssignSpecific,
  getWorkDepartment,
  setSpecialRectificationInspectionUserAdd,
} from "../../api";

export default {
  components: {
    // eslint-disable-next-line vue/no-unused-components
    TkiTree,
  },
  data() {
    return {
      form: {
        SPECIAL_RECTIFICATION_INSPECT_ID: "",
        // 专项整治活动id
        SPECIAL_RECTIFICATION_ACTIVITY_ID: "",
        // 专项整治活动任务id
        SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID: "",
        CORP_NAME: "",
        CORP_ADDRESS: "",
        LR_NAME: "",
        LR_PHONE: "",
        INSPECTNO: "",
        INSPECT_PLACE: "",
        CORPINFO_ID: "",
        INSPECTTYPE: "checkType0002",
        INSPECTTIME: "",
        HASEXPERTS: "",
        // 现场检查照片
        onSiteInspectionPhotos: [],
      },
      count: "0",
      rules: {
        CORP_NAME: {
          type: "string",
          required: true,
          message: "请输入公司名称",
          trigger: ["blur", "change"],
        },
        CORP_ADDRESS: {
          type: "string",
          required: true,
          message: "请输入地址",
          trigger: ["blur", "change"],
        },
        LR_NAME: {
          type: "string",
          required: true,
          message: "请输入姓名",
          trigger: ["blur", "change"],
        },
        LR_PHONE: {
          type: "string",
          required: true,
          message: "请输入联系电话",
          trigger: ["blur", "change"],
        },
        INSPECTNO: {
          type: "string",
          required: true,
          message: "请输入检查编号",
          trigger: ["blur", "change"],
        },
        INSPECT_PLACE: {
          type: "string",
          required: true,
          message: "请输入检查场所",
          trigger: ["blur", "change"],
        },
        INSPECTTYPE: {
          type: "string",
          required: true,
          message: "请选择检查类型",
          trigger: ["change"],
        },
        INSPECTTIME: {
          type: "string",
          required: true,
          message: "请选择检查时间",
          trigger: ["change"],
        },
        HASEXPERTS: {
          type: "string",
          required: true,
          message: "请选择邀请专家",
          trigger: ["change"],
        },
        onSiteInspectionPhotos: {
          type: "array",
          required: true,
          message: "请上传现场检查照片",
          trigger: ["change"],
        },
      },
      inspectionContent: {
        show: false,
        type: "",
        index: "",
        form: {
          CONTENT_ID: "",
          INSPECT_CONTENT: "",
        },
        rules: {
          INSPECT_CONTENT: {
            type: "string",
            required: true,
            message: "请输入检查内容",
            trigger: ["blur", "change"],
          },
        },
      },
      inspectTypeList: [],
      inspectTimeShow: false,
      inspectTimeCurrent: Number(new Date()),
      inspectionDepartment: [],
      inspectionUser: [],
      inspectUserList: [],
      hiddenList: [],
      inspectionContentList: [],
      inspectionContentListAll: [],
    };
  },
  onLoad(query) {
    this.fnGetInspectType();
    this.fnAddInspectUserList();
    this.fnGetDepartment(
      query.SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID,
      query.DEPARTMENT_ID,
    );
    this.fnAssignSpecific(
      query.SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID,
      query.DEPARTMENT_ID,
    );
    this.SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID =
      query.SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID;
    this.DEPARTMENT_ID = query.DEPARTMENT_ID;
  },
  computed: {
    userInfo() {
      return this.$store.getters.getUserInfo;
    },
  },
  methods: {
    async fnAssignSpecific(
      SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID,
      DEPARTMENT_ID,
    ) {
      const resData = await getAssignSpecific({
        USER_TYPE: "2",
        SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID,
        DEPARTMENT_ID,
      });
      for (let i = 0; i < resData.varList.length; i++) {
        this.fnGetUser(resData.varList[i].DEPARTMENT_ID, i);
      }
      this.inspectUserList = resData.varList;
    },
    async fnGetDepartment(
      SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID,
      DEPARTMENT_ID,
    ) {
      const resData = await getWorkDepartment(
        SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID,
        DEPARTMENT_ID,
      );
      this.inspectionDepartment = JSON.parse(resData.zTreeNodes);
    },
    async fnGetInspectType() {
      const resData = await getInspectType();
      this.inspectTypeList = resData.list;
    },
    fnInspectTimeShowChange() {
      this.inspectTimeShow = !this.inspectTimeShow;
    },
    fnInspectTimeConfirm(event) {
      this.form.INSPECTTIME = uni.$u.timeFormat(
        event.value,
        "yyyy-mm-dd hh:MM",
      );
      this.fnInspectTimeShowChange();
    },
    fnOnSiteInspectionPhotosAfterRead(event) {
      this.form.onSiteInspectionPhotos.push(...event.file);
    },
    fnOnSiteInspectionPhotosDelete(event) {
      this.form.onSiteInspectionPhotos.splice(event.index, 1);
    },
    async fnInspectionContentAdd() {
      this.inspectionContent.show = true;
      await this.$nextTick();
      this.inspectionContent.type = "add";
    },
    async fnInspectionContentEdit(index) {
      this.inspectionContent.show = true;
      await this.$nextTick();
      this.inspectionContent.index = index;
      this.inspectionContent.type = "edit";
      this.inspectionContent.form = uni.$u.deepClone(
        this.inspectionContentList[index],
      );
    },
    fnInspectionContentClose() {
      this.inspectionContent.show = false;
      this.$refs.inspectionContentFormRef.resetFields();
    },
    fnInspectionContentConfirm() {
      this.$refs.inspectionContentFormRef
        .validate()
        .then(() => {
          if (this.inspectionContent.type === "add") {
            this.inspectionContentList.push({
              CONTENT_ID: uni.$u.guid(),
              SPECIAL_RECTIFICATION_INSPECT_STANDARD_ITEM_ID: "",
              INSPECT_CONTENT: this.inspectionContent.form.INSPECT_CONTENT,
              INSPECT_CONTENT_SOURCE: 2,
            });
          } else {
            this.inspectionContentList[this.inspectionContent.index] =
              uni.$u.deepClone(this.inspectionContent.form);
            for (let i = 0; i < this.hiddenList.length; i++) {
              if (
                this.hiddenList[i].CONTENT_ID ===
                this.inspectionContent.form.CONTENT_ID
              ) {
                this.hiddenList[i].INSPECT_CONTENT =
                  this.inspectionContent.form.INSPECT_CONTENT;
              }
            }
          }
          this.fnInspectionContentClose();
        })
        .catch(() => {
          uni.$u.toast("请填写完整信息");
        });
    },
    fnInspectionContentDelete(index) {
      let message = "确认删除吗？";
      const currentContentId = this.inspectionContentList[index].CONTENT_ID;
      let deleteHiddenListIndex = -1;
      for (let i = 0; i < this.hiddenList.length; i++) {
        if (this.hiddenList[i].CONTENT_ID === currentContentId) {
          message = "该检查项已添加隐患信息，会同步删除隐患信息，确认删除？";
          deleteHiddenListIndex = i;
          break;
        }
      }
      uni.showModal({
        title: "提示",
        content: message,
        success: (res) => {
          if (res.confirm) {
            deleteHiddenListIndex !== -1 &&
              this.hiddenList.splice(deleteHiddenListIndex, 1);
            this.inspectionContentList.splice(index, 1);
          }
        },
      });
    },
    fnSelectInspectionStandards() {
      uni.navigateTo({
        url: "/pages/supervision_inspection/inspection_standards",
        events: {
          inspectionStandardsAdd: (event) => {
            const { checkList, checkListAll } = event;
            const previousIds = this.inspectionContentList
              .filter((item) => item.INSPECT_CONTENT_SOURCE === 1)
              .map((item) => item.CONTENT_ID);
            const currentIds = checkList.map((item) => item.CONTENT_ID);
            if (currentIds.length === 0) {
              uni.navigateBack();
              return;
            }
            const difference = previousIds
              .filter((x) => !currentIds.includes(x))
              .join(",");
            const needDeleteHiddenIndexList = [];
            for (let i = 0; i < this.hiddenList.length; i++) {
              if (difference.indexOf(this.hiddenList[i].CONTENT_ID) !== -1) {
                needDeleteHiddenIndexList.push(i);
              }
            }
            if (needDeleteHiddenIndexList.length > 0) {
              uni.showModal({
                title: "提示",
                content:
                  "原有选择的检查内容中有存在隐患信息的检查内容未包含在本次勾选检查内容中，确定后将删除原检查内容及隐患信息，确认是否继续？",
                success: (res) => {
                  if (res.confirm) {
                    for (
                      let i = needDeleteHiddenIndexList.length - 1;
                      i >= 0;
                      i--
                    ) {
                      this.hiddenList.splice(needDeleteHiddenIndexList[i], 1);
                    }
                    this.fnInspectionStandardsAdd(
                      checkList,
                      checkListAll,
                      difference,
                    );
                  }
                },
              });
            } else {
              this.fnInspectionStandardsAdd(
                checkList,
                checkListAll,
                difference,
              );
            }
          },
        },
        success: (event) => {
          event.eventChannel.emit(
            "inspectionStandardsEdit",
            this.inspectionContentListAll.map((item) => item.id),
          );
        },
      });
    },
    fnInspectionStandardsAdd(checkList, checkListAll, difference) {
      let inspectionContentList = this.inspectionContentList;
      inspectionContentList.push(...checkList);
      inspectionContentList = arrayObjectDeduplication(
        inspectionContentList,
        "CONTENT_ID",
      );
      if (difference.length > 0) {
        for (let i = 0; i < inspectionContentList.length; i++) {
          if (difference.indexOf(inspectionContentList[i].CONTENT_ID) !== -1) {
            inspectionContentList.splice(i, 1);
            i--;
          }
        }
      }
      this.inspectionContentList = inspectionContentList;
      this.inspectionContentListAll = checkListAll;
      uni.navigateBack();
    },
    fnAddInspectUserList() {
      this.inspectUserList.push({
        id: uni.$u.guid(),
        DEPARTMENT_NAME: "",
        DEPARTMENT_ID: "",
        USER_NAME: "",
        USER_ID: "",
        userList: [],
        userPickerShow: false,
      });
    },
    fnDeleteInspectUserList(index) {
      uni.showModal({
        title: "提示",
        content: "确认删除吗？",
        success: (res) => {
          if (res.confirm) {
            this.inspectUserList.splice(index, 1);
          }
        },
      });
    },
    fnInspectionDepartmentTreeShow(index, disabled) {
      if (disabled) {
        uni.$u.toast("该部门的人员已进行检查，不可更改");
        return;
      }
      this.$refs.inspectionDepartmentTreeRef[index]._show();
    },
    fnInspectionDepartmentTreeConfirm(event, index) {
      this.inspectUserList[index].DEPARTMENT_NAME = event[0].name;
      this.inspectUserList[index].DEPARTMENT_ID = event[0].id;
      this.inspectUserList[index].USER_NAME = "";
      this.inspectUserList[index].USER_ID = "";
      this.fnGetUser(event[0].id, index);
    },
    async fnGetUser(DEPARTMENT_ID, index) {
      const resData = await getUser({ DEPARTMENT_ID });
      this.$set(this.inspectUserList[index], "userList", [resData.userList]);
    },
    fnInspectionUserPickerShow(index, disabled) {
      if (disabled) {
        uni.$u.toast("该人员已进行检查，不可更改");
        return;
      }
      if (this.inspectUserList[index].userList.length === 0) {
        uni.$u.toast("请选择部门");
        return;
      }
      if (this.inspectUserList[index].userList[0].length === 0) {
        uni.$u.toast("当前部门下没有人员");
        return;
      }
      this.$set(
        this.inspectUserList[index],
        "userPickerShow",
        !this.inspectUserList[index].userPickerShow,
      );
    },
    fnInspectionUserPickerConfirm(event, index) {
      for (let i = 0; i < this.inspectUserList.length; i++) {
        if (
          i !== index &&
          this.inspectUserList[i].USER_ID === event.value[0].USER_ID
        ) {
          uni.showToast({
            title: "不能选择相同的检查人",
            icon: "none",
          });
          return;
        }
      }
      this.inspectUserList[index].USER_NAME = event.value[0].NAME;
      this.inspectUserList[index].USER_ID = event.value[0].USER_ID;
      this.fnInspectionUserPickerShow(index, false);
    },
    fnHiddenAdd(index) {
      uni.navigateTo({
        url:
          "/pages/supervision_inspection/hidden_add?type=add&CONTENT_ID=" +
          this.inspectionContentList[index].CONTENT_ID +
          "&INSPECT_CONTENT=" +
          this.inspectionContentList[index].INSPECT_CONTENT,
        events: {
          hiddenAdd: (event) => {
            if (event.type === "add") this.hiddenList.push(event.form);
            else if (event.type === "edit")
              this.hiddenList.splice(event.index, 1, event.form);
          },
        },
      });
    },
    fnHiddenEdit(index) {
      uni.navigateTo({
        url:
          "/pages/supervision_inspection/hidden_add?type=edit&index=" + index,
        success: (event) => {
          event.eventChannel.emit("hiddenEdit", this.hiddenList[index]);
        },
      });
    },
    fnHiddenDelete(index) {
      uni.showModal({
        title: "提示",
        content: "确认删除吗？",
        success: (res) => {
          if (res.confirm) {
            this.hiddenList.splice(index, 1);
          }
        },
      });
    },
    async fntempleSubmit() {
      if (this.hiddenList) {
        for (let i = 0; i < this.inspectUserList.length; i++) {
          if (!this.inspectUserList[i].USER_ID) {
            uni.$u.toast("请选择检查人");
            return;
          }
        }
        const hiddenList = await this.fnUploadHiddenImg();
        const SPECIAL_RECTIFICATION_INSPECT_ID =
          await this.fntempleSubmitForm(hiddenList);
        await this.fnUploadOnSiteInspectionPhotos(
          SPECIAL_RECTIFICATION_INSPECT_ID,
        );
      }
      uni.$u.toast("保存成功");
      uni.navigateBack();
    },
    async fntempleSubmitForm(hiddenList) {
      const inspectUserList = [];
      for (let i = 0; i < this.inspectUserList.length; i++) {
        inspectUserList.push({
          DEPARTMENT_ID: this.inspectUserList[i].DEPARTMENT_ID,
          USER_ID: this.inspectUserList[i].USER_ID,
        });
      }
      const {
        pd: { SPECIAL_RECTIFICATION_INSPECT_ID },
      } = await setSpecialRectificationInspectionAdd({
        loading: false,
        USER_NAME: this.userInfo.NAME,
        DEPARTMENT_ID: this.DEPARTMENT_ID,
        ...this.form,
        isStore: 0,
        inspectUserList: JSON.stringify(inspectUserList),
        inspectContentList: JSON.stringify(this.inspectionContentList),
        hiddenList: JSON.stringify(hiddenList),
      });
      return SPECIAL_RECTIFICATION_INSPECT_ID;
    },

    async fnSubmit() {
      debounce(async () => {
        this.$refs.formRef
          .validate()
          .then(async () => {
            for (let i = 0; i < this.inspectUserList.length; i++) {
              if (!this.inspectUserList[i].USER_ID) {
                uni.$u.toast("请选择检查人");
                return;
              }
            }
            uni.showLoading({
              title: "数据提交中",
            });
            const inspectUserList = [];
            for (let i = 0; i < this.inspectUserList.length; i++) {
              inspectUserList.push({
                DEPARTMENT_ID: this.inspectUserList[i].DEPARTMENT_ID,
                USER_ID: this.inspectUserList[i].USER_ID,
              });
              // if (
              //   inspectUserList.indexOf(this.inspectUserList[i].USER_ID) === -1
              // ) {
              //   inspectUserList.push({
              //     DEPARTMENT_ID: this.inspectUserList[i].DEPARTMENT_ID,
              //     USER_ID: this.inspectUserList[i].USER_ID,
              //   });
              // }
            }
            await setSpecialRectificationInspectionUserAdd({
              loading: false,
              USER_NAME: this.userInfo.NAME,
              DEPARTMENT_ID: this.userInfo.DEPARTMENT_ID,
              isStore: 0,
              SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID:
                this.SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID,
              inspectUserList: JSON.stringify(inspectUserList),
            });
            uni.hideLoading();
            uni.$u.toast("保存成功");
            // uni.navigateBack();
            uni.redirectTo({
              url: "/pages/special_rectification/task_list",
            });
          })
          .catch((e) => {
            uni.$u.toast("请填写完整信息");
          });
      });
    },
    async fnUploadHiddenImg() {
      const hiddenList = [];
      for (let i = 0; i < this.hiddenList.length; i++) {
        const hiddenImgs = [];
        for (let j = 0; j < this.hiddenList[i].hiddenImgs.length; j++) {
          const files = [];
          files.push({
            uri: this.hiddenList[i].hiddenImgs[j].url,
            name: "hiddenImgs",
          });
          const {
            pathList,
            // hiddenIndex
          } = await setSpecialRectificationInspectionHiddenImgAdd({
            loading: false,
            files,
            formData: {
              CORPINFO_ID: this.form.CORPINFO_ID,
              hiddenIndex: i,
            },
          });
          hiddenImgs.push(pathList[0]);
        }
        hiddenList.push({
          ...this.hiddenList[i],
          hiddenImgs,
          hiddenImgsStr: hiddenImgs.join(","),
          hiddenFiles: [],
        });
      }
      return hiddenList;
    },
    async fnSubmitForm(hiddenList) {
      const inspectUserList = [];
      for (let i = 0; i < this.inspectUserList.length; i++) {
        inspectUserList.push({
          DEPARTMENT_ID: this.inspectUserList[i].DEPARTMENT_ID,
          USER_ID: this.inspectUserList[i].USER_ID,
        });
      }
      const {
        pd: { SPECIAL_RECTIFICATION_INSPECT_ID },
      } = await setSpecialRectificationInspectionAdd({
        loading: false,
        USER_NAME: this.userInfo.NAME,
        DEPARTMENT_ID: this.userInfo.DEPARTMENT_ID,
        ...this.form,
        inspectUserList: JSON.stringify(inspectUserList),
        inspectContentList: JSON.stringify(this.inspectionContentList),
        hiddenList: JSON.stringify(hiddenList),
      });
      return SPECIAL_RECTIFICATION_INSPECT_ID;
    },
    async fnUploadOnSiteInspectionPhotos(SPECIAL_RECTIFICATION_INSPECT_ID) {
      for (let i = 0; i < this.form.onSiteInspectionPhotos.length; i++) {
        const files = [];
        files.push({
          uri: this.form.onSiteInspectionPhotos[i].url,
          name: "imgsList",
        });
        await setSpecialRectificationInspectionImgAdd({
          loading: false,
          files,
          formData: {
            SPECIAL_RECTIFICATION_INSPECT_ID,
            USER_NAME: this.userInfo.NAME,
            CORPINFO_ID: this.form.CORPINFO_ID,
          },
        });
      }
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  padding: 20upx;

  .user_item {
    border: 1px dashed #ccc;
    margin: 30upx 0;
    padding: 0 30upx 30upx 30upx;
    position: relative;

    .delete {
      position: absolute;
      right: -20upx;
      top: -20upx;
    }
  }
}

.u-icon {
  justify-content: center;
}
// 隐藏
.hide {
  display: none;
}
</style>
