<template>
  <view class="container">
    <view class="tips_text">
      严禁在本互联网非涉密平台处理、传输国家秘密和工作秘密，请确认扫描、传输的文件资料不涉及国家秘密和工作秘密
    </view>
    <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
      />
      <u-form-item label="公司名称" prop="CORP_NAME" border-bottom required>
        <u--input
          v-model="form.CORP_NAME"
          readonly
          border="none"
          input-align="right"
        />
      </u-form-item>
      <u-form-item
        label="地址"
        prop="CORP_ADDRESS"
        border-bottom
        required
        label-position="top"
      >
        <u--input v-model="form.CORP_ADDRESS" border="none" />
      </u-form-item>
      <u-form-item label="姓名" prop="LR_NAME" border-bottom required>
        <u--input v-model="form.LR_NAME" border="none" input-align="right" />
      </u-form-item>
      <u-form-item label="联系电话" prop="LR_PHONE" border-bottom required>
        <u--input v-model="form.LR_PHONE" border="none" input-align="right" />
      </u-form-item>
      <u-form-item
        label="检查编号"
        prop="INSPECTNO"
        border-bottom
        required
        label-position="top"
      >
        <view
          style="
            flex: 1;
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <u-input v-model="form.INSPECTNO" border="none" />
        </view>
      </u-form-item>
      <u-form-item
        label="检查场所"
        prop="INSPECT_PLACE"
        border-bottom
        required
        label-position="top"
      >
        <u--input v-model="form.INSPECT_PLACE" border="none" />
      </u-form-item>
      <u-form-item label="检查类型" prop="INSPECTTYPE" border-bottom required>
        <u-radio-group v-model="form.INSPECTTYPE" class="mt-10">
          <u-radio
            v-for="(item, index) in inspectTypeList"
            :key="index"
            :name="item.BIANMA"
            :label="item.NAME"
            :class="{ hide: form.INSPECTTYPE !== item.BIANMA }"
            style="margin-left: 10upx"
          />
        </u-radio-group>
      </u-form-item>
      <u-form-item
        label="检查时间"
        prop="INSPECTTIME"
        border-bottom
        required
        @click="fnInspectTimeShowChange"
      >
        <u--input
          :value="form.INSPECTTIME || '请选择'"
          readonly
          border="none"
          input-align="right"
        />
        <u-icon name="arrow-right" color="#999999"></u-icon>
      </u-form-item>
      <u-form-item label="邀请专家" prop="HASEXPERTS" border-bottom required>
        <u-radio-group v-model="form.HASEXPERTS" style="justify-content: end">
          <u-radio
            v-for="(item, index) in [
              { ID: '1', NAME: '是' },
              { ID: '0', NAME: '否' },
            ]"
            :key="index"
            :name="item.ID"
            :label="item.NAME"
            style="margin-left: 10upx"
          />
        </u-radio-group>
      </u-form-item>
      <u-form-item
        label="现场检查照片"
        prop="onSiteInspectionPhotos"
        border-bottom
        required
        label-position="top"
      >
        <u-upload
          class="mt-10"
          :file-list="form.onSiteInspectionPhotos"
          multiple
          :max-count="10"
          @afterRead="fnOnSiteInspectionPhotosAfterRead"
          @delete="fnOnSiteInspectionPhotosDelete"
        />
      </u-form-item>
      <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="fnSelectInspectionStandards"
        />-->
        <u-button
          type="primary"
          text="录入"
          :custom-style="{
            width: '150upx',
            margin: 0,
            marginLeft: '20upx',
            height: '50upx',
          }"
          @click="fnInspectionContentAdd"
        />
      </view>
      <uni-table border stripe empty-text="暂无更多数据" class="mt-10 mb-10">
        <uni-tr>
          <uni-th align="center" width="50">序号</uni-th>
          <uni-th align="center">检查内容</uni-th>
          <uni-th align="center" width="80">操作</uni-th>
        </uni-tr>
        <uni-tr
          v-for="(item, index) in inspectionContentList"
          :key="item.SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID"
        >
          <uni-td align="center">{{ index + 1 }}</uni-td>
          <uni-td>{{ item.INSPECT_CONTENT }}</uni-td>
          <uni-td align="center">
            <view style="display: flex; justify-content: space-evenly">
              <u-icon
                name="edit-pen-fill"
                size="20"
                @click="fnInspectionContentEdit(index)"
              />
              <u-icon
                name="trash-fill"
                color="red"
                size="20"
                @click="fnInspectionContentDelete(index)"
              />
              <u-icon
                name="plus-circle-fill"
                color="#19be6b"
                size="20"
                @click="fnHiddenAdd(index)"
              />
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>
      <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)"
        >
          <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)"
        >
          <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
            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
          :key="item.DEPARTMENT_ID"
          :show="item.userPickerShow"
          :columns="item.userList"
          key-name="NAME"
          @cancel="fnInspectionUserPickerShow(index)"
          @confirm="fnInspectionUserPickerConfirm($event, index)"
        />
      </view>
      <u-divider
        text="隐患"
        text-position="left"
        text-color="rgb(42, 86, 247)"
        line-color="rgb(42, 86, 247)"
        dashed
      />
      <uni-table border stripe empty-text="暂无更多数据" class="mt-10 mb-10">
        <uni-tr>
          <uni-th align="center" width="50">序号</uni-th>
          <uni-th align="center">所属检查</uni-th>
          <uni-th align="center">隐患描述</uni-th>
          <uni-th align="center" width="60">操作</uni-th>
        </uni-tr>
        <uni-tr v-for="(item, index) in hiddenList" :key="item.id">
          <uni-td align="center">{{ index + 1 }}</uni-td>
          <uni-td>{{ item.INSPECT_CONTENT }}</uni-td>
          <uni-td>{{ item.HIDDENDESCR }}</uni-td>
          <uni-td align="center">
            <view style="display: flex; justify-content: space-evenly">
              <u-icon
                name="edit-pen-fill"
                size="20"
                @click="fnHiddenEdit(index)"
              />
              <u-icon
                name="trash-fill"
                color="red"
                size="20"
                @click="fnHiddenDelete(index)"
              />
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>
      <div style="display: flex; gap: 20rpx">
        <u-button type="primary" text="保存" @click="fnSubmit" />
        <u-button type="success" text="暂存" @click="fntempleSubmit" />
      </div>
    </u--form>
    <u-datetime-picker
      v-model="inspectTimeCurrent"
      :show="inspectTimeShow"
      mode="datetime"
      @cancel="fnInspectTimeShowChange"
      @confirm="fnInspectTimeConfirm"
    />
    <u-modal
      :show="inspectionContent.show"
      title="检查内容"
      show-cancel-button
      cancel-text="关闭"
      @confirm="fnInspectionContentConfirm"
      @cancel="fnInspectionContentClose"
    >
      <view style="flex: 1">
        <u--form
          ref="inspectionContentFormRef"
          label-position="left"
          :model="inspectionContent.form"
          :rules="inspectionContent.rules"
          label-width="auto"
        >
          <u-form-item
            label="检查内容"
            prop="INSPECT_CONTENT"
            required
            label-position="top"
          >
            <u--textarea
              v-model="inspectionContent.form.INSPECT_CONTENT"
              auto-height
              input-align="right"
            />
          </u-form-item>
        </u--form>
      </view>
    </u-modal>
  </view>
</template>

<script>
import {
  getRegDepartment,
  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 {
  getSpecialRectificationInspectionRecordView,
  getSpecialRectificationUserList,
  setSpecialRectificationInspectionImgDel,
  setSpecialRectificationInspectionUpdate,
} 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: [],
      },
      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: [],
      inspectionContentListOld: [],
      hiddenListRemoveId: [],
      inspectUserRemoveId: [],
      hiddenDeleteImgsId: [],
      SPECIAL_RECTIFICATION_FILES_ID: [],
    };
  },
  onLoad(query) {
    if (query.SPECIAL_RECTIFICATION_INSPECT_ID) {
      this.SPECIAL_RECTIFICATION_INSPECT_ID =
        query.SPECIAL_RECTIFICATION_INSPECT_ID;
      this.fnGetData(query.SPECIAL_RECTIFICATION_INSPECT_ID);
    } else {
      this.form.SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID =
        query.SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID;
      this.form.CORPINFO_ID = query.CORPINFO_ID;
      this.form.CORP_NAME = query.CORP_NAME;
      this.form.CORP_ADDRESS = query.ADDRESS_BUSINESS;
      this.form.LR_NAME = query.LR_NAME || "";
      this.form.LR_PHONE = query.LR_PHONE || "";
      this.fnAddInspectUserList();
    }
    this.fnGetInspectType();
    this.fnGetDepartment(query.SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID);
  },
  computed: {
    userInfo() {
      return this.$store.getters.getUserInfo;
    },
  },
  onBackPress(event) {
    if (event.from === "backbutton") {
      uni.showModal({
        title: "提示",
        content: "是否保存该页面数据",
        success: async (res) => {
          if (res.confirm) {
            this.fntempleSubmit();
          } else {
            uni.navigateBack();
          }
        },
      });
      return true;
    }
    return false;
  },
  methods: {
    async fnGetData(SPECIAL_RECTIFICATION_INSPECT_ID) {
      const resData = await getSpecialRectificationInspectionRecordView({
        SPECIAL_RECTIFICATION_INSPECT_ID,
      });
      for (let i = 0; i < resData.pd.imgsList.length; i++) {
        resData.pd.imgsList[i].FILEPATH =
          this.$filePath + resData.pd.imgsList[i].FILEPATH;
      }
      this.form = resData.pd;
      for (let i = 0; i < resData.pd.imgsList.length; i++) {
        resData.pd.imgsList[i].url = resData.pd.imgsList[i].FILEPATH;
      }
      this.form.onSiteInspectionPhotos = resData.pd.imgsList;
      this.inspectionContentList = resData.pd.contentList;
      this.OldinspectionContentList = uni.$u.deepClone(resData.pd.contentList);

      const contentListOld = []; // 从表中查询出来的检查内容id集合
      if (resData.pd.contentList) {
        for (let i = 0; i < resData.pd.contentList.length; i++) {
          contentListOld.push(
            resData.pd.contentList[i].SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID,
          );
        }
      }
      this.inspectionContentListOld = uni.$u.deepClone(contentListOld);
      for (let i = 0; i < resData.pd.hiddenList.length; i++) {
        resData.pd.hiddenList[i].id =
          resData.pd.hiddenList[i].SPECIAL_RECTIFICATION_INSPECT_HIDDEN_ID;
        for (let j = 0; j < resData.pd.hiddenList[i].hiddenImgs.length; j++) {
          resData.pd.hiddenList[i].hiddenImgs[j].url =
            this.$filePath + resData.pd.hiddenList[i].hiddenImgs[j].FILEPATH;
        }
      }
      this.hiddenList = resData.pd.hiddenList;

      const userList = [];
      for (let i = 0; i < resData.pd.checkUserList.length; i++) {
        userList.push({
          id: uni.$u.guid(),
          DEPARTMENT_NAME:
            resData.pd.checkUserList[i].DEPARTMENT_FULL_NAME || "",
          DEPARTMENT_ID: resData.pd.checkUserList[i].DEPARTMENT_ID || "",
          USER_NAME: resData.pd.checkUserList[i].USER_NAME || "",
          USER_ID: resData.pd.checkUserList[i].USER_ID || "",
          SPECIAL_RECTIFICATION_ACTIVITY_TASK_USER_ID:
            resData.pd.checkUserList[i]
              .SPECIAL_RECTIFICATION_ACTIVITY_TASK_USER_ID || "",
          userList: [],
          userPickerShow: false,
        });
      }
      this.inspectUserList = userList;

      for (let i = 0; i < resData.pd.checkUserList.length; i++) {
        if (resData.pd.checkUserList[i].DEPARTMENT_ID)
          this.fnGetUserList(resData.pd.checkUserList[i].DEPARTMENT_ID, i);
      }
      if (this.inspectUserList.length === 0) this.fnAddInspectUserList();
    },
    // getInspectionStandards,
    async fnGetDepartment(SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID) {
      const resData = await getRegDepartment(
        SPECIAL_RECTIFICATION_ACTIVITY_TASK_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);
    },
    async fnOnSiteInspectionPhotosDelete(event) {
      // await setSpecialRectificationInspectionImgDel({
      //   formData: {
      //     SPECIAL_RECTIFICATION_FILES_ID:
      //       event.file.SPECIAL_RECTIFICATION_FILES_ID,
      //   },
      // });
      if (event.file.SPECIAL_RECTIFICATION_FILES_ID) {
        this.SPECIAL_RECTIFICATION_FILES_ID.push(
          event.file.SPECIAL_RECTIFICATION_FILES_ID,
        );
      }
      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_CONTENT_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].SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID ===
                this.inspectionContentList[this.inspectionContent.index]
                  .SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID
              ) {
                this.hiddenList[i].INSPECT_CONTENT =
                  this.inspectionContentList[
                    this.inspectionContent.index
                  ].INSPECT_CONTENT;
              }
              if (this.OldinspectionContentList) {
                this.OldinspectionContentList.map((item) => {
                  if (
                    item.SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID ===
                    this.inspectionContentList[this.inspectionContent.index]
                      .SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID
                  ) {
                    item.INSPECT_CONTENT =
                      this.inspectionContentList[
                        this.inspectionContent.index
                      ].INSPECT_CONTENT;
                  }
                });
              }
            }
          }
          this.fnInspectionContentClose();
        })
        .catch(() => {
          uni.$u.toast("请填写完整信息");
        });
    },
    fnInspectionContentDelete(index) {
      let message = "确认删除吗？";
      const currentContentId =
        this.inspectionContentList[index].CONTENT_ID ||
        this.inspectionContentList[index]
          .SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID;
      const deleteHiddenListContentId = [];
      const deleteHiddenListHiddenId = [];
      for (let i = 0; i < this.hiddenList.length; i++) {
        if (
          this.hiddenList[i].CONTENT_ID === currentContentId ||
          this.hiddenList[i].SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID ===
            currentContentId
        ) {
          message = "该检查项已添加隐患信息，会同步删除隐患信息，确认删除？";
          deleteHiddenListContentId.push(currentContentId);
          deleteHiddenListHiddenId.push(
            this.hiddenList[i].SPECIAL_RECTIFICATION_INSPECT_HIDDEN_ID,
          );
          break;
        }
      }
      uni.showModal({
        title: "提示",
        content: message,
        success: (res) => {
          if (res.confirm) {
            if (deleteHiddenListContentId.length > 0) {
              this.hiddenListRemoveId.push(...deleteHiddenListHiddenId);
              this.hiddenList = this.hiddenList.filter(
                (item) =>
                  !deleteHiddenListContentId.includes(
                    item.SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID,
                  ),
              );
            }
            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) {
      let inspectionContentList = this.inspectionContentList.map((item) => ({
        ...item,
        CONTENT_ID:
          item.CONTENT_ID || item.SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID,
      }));
      inspectionContentList.push(...checkList);
      const newInspectionContentList = arrayObjectDeduplication(
        inspectionContentList,
        "CONTENT_ID",
      );
      inspectionContentList = newInspectionContentList;

      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.inspectUserRemoveId.push(
              this.inspectUserList[index]
                .SPECIAL_RECTIFICATION_ACTIVITY_TASK_USER_ID,
            );
            this.inspectUserList.splice(index, 1);
          }
        },
      });
    },
    fnInspectionDepartmentTreeShow(index) {
      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.fnGetUserList(event[0].id, index);
    },
    async fnGetUserList(DEPARTMENT_ID, index) {
      const resData = await getSpecialRectificationUserList({
        DEPARTMENT_ID,
        SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID:
          this.form.SPECIAL_RECTIFICATION_ACTIVITY_TASK_ID,
        USER_TYPE: "2",
      });
      // this.inspectUserList[index].userList.push(resData.userList);
      this.$set(this.inspectUserList[index], "userList", [resData.userList]);
    },
    async fnGetUser(DEPARTMENT_ID, index) {
      this.inspectUserList[index].userList = [];
      const resData = await getUser({ DEPARTMENT_ID });
      this.inspectUserList[index].userList.push(resData.userList);
    },
    fnInspectionUserPickerShow(index) {
      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) {
      this.inspectUserList[index].USER_NAME = event.value[0].NAME;
      this.inspectUserList[index].USER_ID = event.value[0].USER_ID;
      this.fnInspectionUserPickerShow(index);
    },
    fnHiddenAdd(index) {
      uni.navigateTo({
        url:
          "/pages/special_rectification/hidden_add?type=add&CONTENT_ID=" +
          this.inspectionContentList[index].CONTENT_ID +
          "&INSPECT_CONTENT=" +
          this.inspectionContentList[index].INSPECT_CONTENT +
          "&SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID=" +
          this.inspectionContentList[index]
            .SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID,
        events: {
          hiddenAdd: (event) => {
            if (event.type === "add") this.hiddenList.push(event.form);
          },
        },
      });
    },
    fnHiddenEdit(index) {
      uni.navigateTo({
        url: "/pages/special_rectification/hidden_add?type=edit&index=" + index,
        success: (event) => {
          event.eventChannel.emit("hiddenEdit", {
            form: uni.$u.deepClone(this.hiddenList[index]),
          });
        },
        events: {
          hiddenAdd: (event) => {
            if (event.type === "edit") {
              this.hiddenList.splice(event.index, 1, event.form);
              this.hiddenDeleteImgsId = event.deleteImgsId;
            }
          },
        },
      });
    },
    fnHiddenDelete(index) {
      uni.showModal({
        title: "提示",
        content: "确认删除吗？",
        success: (res) => {
          if (res.confirm) {
            this.hiddenListRemoveId.push(
              this.hiddenList[index].SPECIAL_RECTIFICATION_INSPECT_HIDDEN_ID,
            );
            this.hiddenList.splice(index, 1);
          }
        },
      });
    },
    async fntempleSubmit() {
      debounce(async () => {
        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 fnSubmit() {
      debounce(async () => {
        this.$refs.formRef
          .validate()
          .then(async () => {
            if (this.inspectionContentList.length === 0) {
              uni.$u.toast("请填写检查内容");
              return;
            }
            for (let i = 0; i < this.inspectUserList.length; i++) {
              if (!this.inspectUserList[i].USER_ID) {
                uni.$u.toast("请选择检查人");
                return;
              }
            }
            uni.showLoading({
              title: "数据提交中",
            });
            const hiddenList = await this.fnUploadHiddenImg();
            const SPECIAL_RECTIFICATION_INSPECT_ID =
              await this.fnSubmitForm(hiddenList);
            await this.fnUploadOnSiteInspectionPhotos(
              SPECIAL_RECTIFICATION_INSPECT_ID,
            );
            uni.hideLoading();
            uni.$u.toast("保存成功");
            uni.navigateBack();
          })
          .catch((e) => {
            uni.$u.toast("请填写完整信息");
          });
      });
    },
    async fnUploadHiddenImg() {
      const hiddenList = [];
      for (let i = 0; i < this.hiddenList.length; i++) {
        const files = [];
        for (let j = 0; j < this.hiddenList[i].hiddenImgs.length; j++) {
          if (!this.hiddenList[i].hiddenImgs[j].FILEPATH) {
            files.push({
              uri: this.hiddenList[i].hiddenImgs[j].url,
              name: "hiddenImgs",
            });
          }
        }
        const newPathList = [];
        for (let i = 0; i < files.length; i++) {
          const newFile = [];
          newFile.push(files[i]);
          const {
            pathList,
            // hiddenIndex
          } = await setSpecialRectificationInspectionHiddenImgAdd({
            files: newFile,
            formData: {
              CORPINFO_ID: this.form.CORPINFO_ID,
              hiddenIndex: i,
            },
          });
          newPathList.push(pathList);
        }
        hiddenList.push({
          ...this.hiddenList[i],
          hiddenImgs: newPathList,
          hiddenImgsStr: newPathList.join(","),
          hiddenFiles: [],
        });
      }
      return hiddenList;
    },
    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,
          SPECIAL_RECTIFICATION_ACTIVITY_TASK_USER_ID:
            this.inspectUserList[i]
              .SPECIAL_RECTIFICATION_ACTIVITY_TASK_USER_ID || "",
        });
      }
      for (let i = 0; i < this.SPECIAL_RECTIFICATION_FILES_ID.length; i++) {
        await setSpecialRectificationInspectionImgDel({
          SPECIAL_RECTIFICATION_FILES_ID:
            this.SPECIAL_RECTIFICATION_FILES_ID[i],
        });
      }
      for (let i = 0; i < this.hiddenDeleteImgsId.length; i++) {
        await setSpecialRectificationInspectionImgDel({
          SPECIAL_RECTIFICATION_FILES_ID: this.hiddenDeleteImgsId[i],
        });
      }

      const inspectionContentListOld = this.inspectionContentListOld;

      const inspectionContentListNew = [];
      for (let i = 0; i < this.inspectionContentList.length; i++) {
        if (
          this.inspectionContentList[i]
            .SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID === "" ||
          this.inspectionContentList[i]
            .SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID == null
        ) {
          inspectionContentListNew.push(
            this.inspectionContentList[i].CONTENT_ID,
          );
        } else {
          inspectionContentListNew.push(
            this.inspectionContentList[i]
              .SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID,
          );
        }
      }

      const resAdd = inspectionContentListNew.filter(
        (item) => inspectionContentListOld.indexOf(item) === -1,
      ); // 新增的标准id
      const resDel = inspectionContentListOld.filter(
        (item) => inspectionContentListNew.indexOf(item) === -1,
      ); // 删除的标准id

      const addInspectionContentList = [];
      resAdd.map((i) => {
        this.inspectionContentList.filter((item) => {
          item.CONTENT_ID === i && addInspectionContentList.push(item);
        });
      }); // 新增的标准的集合
      const params = {
        USER_NAME: this.userInfo.NAME,
        DEPARTMENT_ID: this.userInfo.DEPARTMENT_ID,
        ...this.form,
        isStore: 0,
        inspectUserList: JSON.stringify(inspectUserList),
        addInspectContentList: JSON.stringify(addInspectionContentList),
        hiddenList: JSON.stringify(hiddenList),
        inspectContentList: JSON.stringify(this.inspectionContentList),
        delInspectContentList: resDel.join(","),
        hiddenListRemoveList: this.hiddenListRemoveId.join(","),
        inspectUserRemoveList: this.inspectUserRemoveId.join(","),
      };
      const {
        pd: { SPECIAL_RECTIFICATION_INSPECT_ID },
      } = !this.SPECIAL_RECTIFICATION_INSPECT_ID
        ? await setSpecialRectificationInspectionAdd(params)
        : await setSpecialRectificationInspectionUpdate(params);
      return SPECIAL_RECTIFICATION_INSPECT_ID;
    },
    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,
          SPECIAL_RECTIFICATION_ACTIVITY_TASK_USER_ID:
            this.inspectUserList[i]
              .SPECIAL_RECTIFICATION_ACTIVITY_TASK_USER_ID || "",
        });
      }

      for (let i = 0; i < this.SPECIAL_RECTIFICATION_FILES_ID.length; i++) {
        await setSpecialRectificationInspectionImgDel({
          SPECIAL_RECTIFICATION_FILES_ID:
            this.SPECIAL_RECTIFICATION_FILES_ID[i],
        });
      }
      for (let i = 0; i < this.hiddenDeleteImgsId.length; i++) {
        await setSpecialRectificationInspectionImgDel({
          SPECIAL_RECTIFICATION_FILES_ID: this.hiddenDeleteImgsId[i],
        });
      }
      const inspectionContentListOld = this.inspectionContentListOld;

      const inspectionContentListNew = [];
      for (let i = 0; i < this.inspectionContentList.length; i++) {
        if (
          this.inspectionContentList[i]
            .SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID === "" ||
          this.inspectionContentList[i]
            .SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID == null
        ) {
          inspectionContentListNew.push(
            this.inspectionContentList[i].CONTENT_ID,
          );
        } else {
          inspectionContentListNew.push(
            this.inspectionContentList[i]
              .SPECIAL_RECTIFICATION_INSPECT_CONTENT_ID,
          );
        }
      }

      const resAdd = inspectionContentListNew.filter(
        (item) => inspectionContentListOld.indexOf(item) === -1,
      ); // 新增的标准id
      const resDel = inspectionContentListOld.filter(
        (item) => inspectionContentListNew.indexOf(item) === -1,
      ); // 删除的标准id

      const addInspectionContentList = [];
      resAdd.map((i) => {
        this.inspectionContentList.filter((item) => {
          item.CONTENT_ID === i && addInspectionContentList.push(item);
        });
      }); // 新增的标准的集合

      const params = {
        USER_NAME: this.userInfo.NAME,
        DEPARTMENT_ID: this.userInfo.DEPARTMENT_ID,
        ...this.form,
        isStore: 1,
        inspectUserList: JSON.stringify(inspectUserList),
        addInspectContentList: JSON.stringify(addInspectionContentList),
        hiddenList: JSON.stringify(hiddenList),
        inspectContentList: JSON.stringify(this.OldinspectionContentList),
        delInspectContentList: resDel.join(","),
        hiddenListRemoveList: this.hiddenListRemoveId.join(","),
        inspectUserRemoveList: this.inspectUserRemoveId.join(","),
      };
      const {
        pd: { SPECIAL_RECTIFICATION_INSPECT_ID },
      } = !this.SPECIAL_RECTIFICATION_INSPECT_ID
        ? await setSpecialRectificationInspectionAdd(params)
        : await setSpecialRectificationInspectionUpdate(params);
      return SPECIAL_RECTIFICATION_INSPECT_ID;
    },
    async fnUploadOnSiteInspectionPhotos(SPECIAL_RECTIFICATION_INSPECT_ID) {
      const files = [];
      for (let i = 0; i < this.form.onSiteInspectionPhotos.length; i++) {
        if (!this.form.onSiteInspectionPhotos[i].FILEPATH) {
          files.push({
            uri: this.form.onSiteInspectionPhotos[i].url,
            name: "imgsList",
          });
        }
      }
      if (files.length === 0) {
        return Promise.resolve();
      }
      for (let i = 0; i < files.length; i++) {
        const newFile = [];
        newFile.push(files[i]);
        await setSpecialRectificationInspectionImgAdd({
          files: newFile,
          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>
