<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
        label-position="top"
      >
        <u-radio-group v-model="form.INSPECTTYPE" class="mt-10">
          <div class="radio-group-wrap">
            <div v-for="(item, index) in inspectTypeList" :key="index">
              <u-radio
                :name="item.BIANMA"
                :label="item.NAME"
                style="margin-left: 10upx"
              />
            </div>
          </div>
        </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" width="80">内容来源</uni-th>
          <uni-th align="center">帮扶内容</uni-th>
          <uni-th align="center" width="90">操作</uni-th>
        </uni-tr>
        <uni-tr
          v-for="(item, index) in inspectionContentList"
          :key="item.CONTENT_ID"
        >
          <uni-td align="center">{{ index + 1 }}</uni-td>
          <uni-td>{{
            item.INSPECT_CONTENT_SOURCE === 2 ? "手动录入" : "帮扶标准"
          }}</uni-td>
          <uni-td>{{ item.INSPECT_CONTENT }}</uni-td>
          <uni-td align="center">
            <u-radio-group
              :value="item.INSPECT_STATE"
              placement="column"
              @change="fnInspectStateChange($event, index)"
            >
              <u-radio
                :custom-style="{ marginBottom: '8px' }"
                label="合格"
                name="1"
              />
              <u-radio
                :custom-style="{ marginBottom: '8px' }"
                label="不合格"
                name="2"
              />
            </u-radio-group>
            <u-button
              text="删除"
              type="error"
              size="small"
              @click="fnInspectionContentDelete(index)"
            />
          </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
          :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
      />
      <!--      <view style="display: flex; justify-content: end">
        <u-button
          type="primary"
          text="添加其它隐患"
          :custom-style="{ width: '200upx', margin: 0, height: '50upx' }"
          @click="fnHiddenAdd('')"
        />
      </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">隐患描述</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>{{ item.CONTENT_ID }}</uni-td>-->
          <!--          <uni-td>{{item.SUPERVISE_INSPECT_CONTENT_ID}} </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 {
  getDepartment,
  getInspectionStandards,
  getInspectType,
  getSupervisionInspectionRecordView,
  getUser,
  setSupervisionInspectionAdd,
  setSupervisionInspectionHiddenImgAdd,
  setSupervisionInspectionImgAdd,
} from "@/api";
import TkiTree from "@/components/tki-tree/tki-tree.vue";
import { arrayObjectDeduplication } from "@/utils/utils";
import debounce from "@/utils/debounce";
import {
  setSupervisionInspectionImgDel,
  setSupervisionInspectionUpdate,
} from "../../api";

export default {
  components: {
    TkiTree,
  },
  data() {
    return {
      LOGIN_DEPARTMENT_ID:
        this.$store.getters.getUserInfo.DEPARTMENT_FULL_ID.split(",")[0],
      form: {
        CORP_NAME: "",
        CORP_ADDRESS: "",
        LR_NAME: "",
        LR_PHONE: "",
        INSPECTNO: "",
        INSPECT_PLACE: "",
        CORPINFO_ID: "",
        INSPECTTYPE: "",
        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: [],
      SUPERVISE_INSPECT_ID: "",
      hiddenListRemoveId: [],
      inspectUserRemoveId: [],
      hiddenDeleteImgsId: [],
      SUPERVISE_INSPECT_FILES_ID: [],
    };
  },
  onLoad(query) {
    if (query.SUPERVISE_INSPECT_ID) {
      this.SUPERVISE_INSPECT_ID = query.SUPERVISE_INSPECT_ID;
      this.fnGetData(query.SUPERVISE_INSPECT_ID);
    } else {
      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();
  },
  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.$emit("CORPINFO_ID", this.form.CORPINFO_ID);
            uni.navigateBack();
          }
        },
      });
      return true;
    }
    return false;
  },
  methods: {
    async fnGetData(SUPERVISE_INSPECT_ID) {
      const resData = await getSupervisionInspectionRecordView({
        SUPERVISE_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;
      for (let i = 0; i < resData.pd.hiddenList.length; i++) {
        resData.pd.hiddenList[i].id =
          resData.pd.hiddenList[i].SUPERVISE_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 contentList = [];
      for (let i = 0; i < resData.pd.contentList.length; i++) {
        for (let j = 0; j < this.hiddenList.length; j++) {
          if (
            resData.pd.contentList[i].CONTENT_ID ===
            this.hiddenList[j].SUPERVISE_INSPECT_CONTENT_ID
          ) {
            resData.pd.contentList[i].HIDDENDESCR =
              this.hiddenList[j].HIDDENDESCR;
            resData.pd.contentList[i].DISPOSE = this.hiddenList[j].DISPOSE;
            break;
          }
        }
      }
      this.inspectionContentList = resData.pd.contentList;
      const contentListOld = []; // 从表中查询出来的帮扶内容id集合
      for (let i = 0; i < resData.pd.contentList.length; i++) {
        resData.pd.contentList[i].CONTENT_ID =
          resData.pd.contentList[i].SUPERVISE_INSPECT_CONTENT_ID;
        const CHECK_CATEGORY =
          resData.pd.contentList[i].SUPERVISE_INSPECT_STANDARD_ID +
          "_" +
          resData.pd.contentList[i].CHECK_CATEGORY;
        const CHECK_ITEM =
          resData.pd.contentList[i].SUPERVISE_INSPECT_STANDARD_ID +
          "_" +
          resData.pd.contentList[i].CHECK_ITEM;
        contentList.push(
          resData.pd.contentList[i].SUPERVISE_INSPECT_STANDARD_ITEM_ID,
          resData.pd.contentList[i].SUPERVISE_INSPECT_STANDARD_ID,
          CHECK_CATEGORY,
          CHECK_ITEM,
        );
        contentListOld.push(
          resData.pd.contentList[i].SUPERVISE_INSPECT_CONTENT_ID,
        );
      }

      this.OldinspectionContentList = resData.pd.contentList;
      this.inspectionContentListOld = contentListOld;
      this.inspectionContentListAll = [...new Set(contentList)];

      const userList = [];
      for (let i = 0; i < resData.pd.userList.length; i++) {
        userList.push({
          id: uni.$u.guid(),
          DEPARTMENT_NAME: resData.pd.userList[i].DEPARTMENT_NAME || "",
          DEPARTMENT_ID: resData.pd.userList[i].DEPARTMENT_ID || "",
          USER_NAME: resData.pd.userList[i].USER_NAME || "",
          USER_ID: resData.pd.userList[i].USER_ID || "",
          SUPERVISE_INSPECT_USER_ID:
            resData.pd.userList[i].SUPERVISE_INSPECT_USER_ID || "",
          userList: [],
          userPickerShow: false,
        });
      }
      this.inspectUserList = userList;
      for (let i = 0; i < resData.pd.userList.length; i++) {
        if (resData.pd.userList[i].DEPARTMENT_ID)
          this.fnGetUser(resData.pd.userList[i].DEPARTMENT_ID, i);
      }
      if (this.inspectUserList.length === 0) this.fnAddInspectUserList();
    },
    fnPreview(current) {
      uni.previewImage({
        current,
        urls: this.form.imgsList.map((item) => item.FILEPATH),
      });
    },
    getInspectionStandards,
    async fnGetDepartment() {
      const resData = await getDepartment(this.LOGIN_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);
    },
    async fnOnSiteInspectionPhotosDelete(event) {
      // await setSupervisionInspectionImgDel({
      //   formData: {
      //     SUPERVISE_INSPECT_FILES_ID: event.file.SUPERVISE_INSPECT_FILES_ID,
      //   },
      // });
      if (event.file.SUPERVISE_INSPECT_FILES_ID) {
        this.SUPERVISE_INSPECT_FILES_ID.push(
          event.file.SUPERVISE_INSPECT_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(),
              SUPERVISE_INSPECT_STANDARD_ITEM_ID: "",
              INSPECT_CONTENT: this.inspectionContent.form.INSPECT_CONTENT,
              INSPECT_CONTENT_SOURCE: 2,
              INSPECT_STATE: "",
            });
          } 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].SUPERVISE_INSPECT_CONTENT_ID ===
                this.inspectionContentList[this.inspectionContent.index]
                  .SUPERVISE_INSPECT_CONTENT_ID
              ) {
                this.hiddenList[i].INSPECT_CONTENT =
                  this.inspectionContentList[
                    this.inspectionContent.index
                  ].INSPECT_CONTENT;
              }
              if (this.OldinspectionContentList) {
                this.OldinspectionContentList.map((item) => {
                  if (
                    item.SUPERVISE_INSPECT_CONTENT_ID ===
                    this.inspectionContentList[this.inspectionContent.index]
                      .SUPERVISE_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].SUPERVISE_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].SUPERVISE_INSPECT_CONTENT_ID === currentContentId
        ) {
          message = "该帮扶项已添加隐患信息，会同步删除隐患信息，确认删除？";
          deleteHiddenListContentId.push(currentContentId);
          deleteHiddenListHiddenId.push(
            this.hiddenList[i].SUPERVISE_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.SUPERVISE_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.SUPERVISE_INSPECT_STANDARD_ITEM_ID);
            const currentIds = checkList.map(
              (item) =>
                item.SUPERVISE_INSPECT_STANDARD_ITEM_ID || item.CONTENT_ID,
            );
            if (currentIds.length === 0) {
              uni.navigateBack();
              return;
            }
            const difference = previousIds
              .filter((x) => !currentIds.includes(x))
              .join(",");
            const newPreviousIds = this.inspectionContentList
              .filter((item) => item.INSPECT_CONTENT_SOURCE === 1)
              .filter((item) =>
                difference.includes(item.SUPERVISE_INSPECT_STANDARD_ITEM_ID),
              );

            const newDifference = newPreviousIds.map(
              (item) => item.SUPERVISE_INSPECT_CONTENT_ID,
            );
            const joinDifference = newDifference.join(",");
            const needDeleteHiddenIndexList = [];
            for (let i = 0; i < this.hiddenList.length; i++) {
              if (
                joinDifference.indexOf(
                  this.hiddenList[i].SUPERVISE_INSPECT_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.hiddenListRemoveId.push(
                        this.hiddenList[needDeleteHiddenIndexList[i]]
                          .SUPERVISE_INSPECT_HIDDEN_ID,
                      );
                      this.hiddenList.splice(needDeleteHiddenIndexList[i], 1);
                    }
                    this.fnInspectionStandardsAdd(
                      checkList,
                      checkListAll,
                      difference,
                    );
                  }
                },
              });
            } else {
              this.fnInspectionStandardsAdd(
                checkList,
                checkListAll,
                difference,
              );
            }
          },
        },
        success: (event) => {
          event.eventChannel.emit(
            "inspectionStandardsEdit",
            this.inspectionContentList.map(
              (item) => item.SUPERVISE_INSPECT_STANDARD_ITEM_ID,
            ),
            // eslint-disable-next-line array-callback-return
            // this.inspectionContentListAll.map((item) => {
            //   if (typeof item === "object") {
            //     return item.id;
            //   } else {
            //     return item;
            //   }
            // }),
          );
        },
      });
    },
    fnInspectionStandardsAdd(checkList, checkListAll) {
      const newItemList = this.inspectionContentList.filter(
        (item) => !item.SUPERVISE_INSPECT_STANDARD_ITEM_ID,
      );
      let inspectionContentList = this.inspectionContentList.filter(
        (item) => item.SUPERVISE_INSPECT_STANDARD_ITEM_ID,
      );
      inspectionContentList.push(...checkList);
      inspectionContentList = arrayObjectDeduplication(
        inspectionContentList,
        "SUPERVISE_INSPECT_STANDARD_ITEM_ID",
      );
      const difference = checkList.map(
        (item) => item.SUPERVISE_INSPECT_STANDARD_ITEM_ID,
      );
      const newInspectionContentList = [];
      if (difference.length > 0) {
        for (let i = 0; i < inspectionContentList.length; i++) {
          if (
            difference.indexOf(
              inspectionContentList[i].SUPERVISE_INSPECT_STANDARD_ITEM_ID,
            ) !== -1
          ) {
            newInspectionContentList.push(inspectionContentList[i]);
          }
        }
      }
      this.inspectionContentList = newInspectionContentList.concat(newItemList);
      this.inspectionContentList = this.inspectionContentList.map((item) => ({
        ...item,
        CONTENT_ID: item.CONTENT_ID || item.SUPERVISE_INSPECT_STANDARD_ITEM_ID,
      }));
      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].SUPERVISE_INSPECT_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.fnGetUser(event[0].id, index);
    },
    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.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);
    },
    fnInspectStateChange(event, index) {
      if (this.inspectionContentList[index].INSPECT_STATE === event) return;
      if (event === "2") {
        this.inspectionContentList[index].INSPECT_STATE =
          Math.random().toString();
        this.fnHiddenAdd(index);
      } else {
        this.inspectionContentList[index].INSPECT_STATE = "1";
        const currentContentId =
          this.inspectionContentList[index].CONTENT_ID ||
          this.inspectionContentList[index].SUPERVISE_INSPECT_CONTENT_ID;
        let deleteHiddenListIndex = -1;
        for (let i = 0; i < this.hiddenList.length; i++) {
          if (
            this.hiddenList[i].SUPERVISE_INSPECT_CONTENT_ID === currentContentId
          ) {
            deleteHiddenListIndex = i;
            break;
          }
        }
        if (deleteHiddenListIndex !== -1) {
          uni.showModal({
            title: "提示",
            content:
              "该帮扶项已添加隐患信息，会同步删除隐患信息，确认改为合格吗？",
            success: (res) => {
              if (res.confirm) {
                this.hiddenListRemoveId.push(
                  this.hiddenList[deleteHiddenListIndex]
                    .SUPERVISE_INSPECT_HIDDEN_ID,
                );
                this.hiddenList.splice(deleteHiddenListIndex, 1);
              } else {
                this.inspectionContentList[index].INSPECT_STATE = "2";
              }
            },
          });
        }
      }
    },
    fnHiddenAdd(index) {
      uni.navigateTo({
        url:
          "/pages/supervision_inspection/hidden_add?type=add&CONTENT_ID=" +
          (index !== "" ? this.inspectionContentList[index].CONTENT_ID : "") +
          "&INSPECT_CONTENT=" +
          (index !== ""
            ? this.inspectionContentList[index].INSPECT_CONTENT
            : "") +
          "&SUPERVISE_INSPECT_CONTENT_ID=" +
          (index !== ""
            ? this.inspectionContentList[index].SUPERVISE_INSPECT_CONTENT_ID
            : "") +
          "&HIDDENDESCR=" +
          (index !== "" ? this.inspectionContentList[index].HIDDENDESCR : "") +
          "&DISPOSE=" +
          (index !== "" ? this.inspectionContentList[index].DISPOSE : ""),
        events: {
          hiddenAdd: (event) => {
            if (event.type === "add") {
              this.hiddenList.push(event.form);
              index !== "" &&
                (this.inspectionContentList[index].INSPECT_STATE = "2");
            } 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", {
            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: this.hiddenList[index].SUPERVISE_INSPECT_CONTENT_ID
          ? "删除此隐患，对应的帮扶项将进行重置，确认删除吗？"
          : "确认删除吗？",
        success: (res) => {
          if (res.confirm) {
            this.hiddenListRemoveId.push(
              this.hiddenList[index].SUPERVISE_INSPECT_HIDDEN_ID,
            );
            if (this.hiddenList[index].SUPERVISE_INSPECT_CONTENT_ID) {
              for (let i = 0; i < this.inspectionContentList.length; i++) {
                if (
                  this.inspectionContentList[i].CONTENT_ID ===
                  this.hiddenList[index].SUPERVISE_INSPECT_CONTENT_ID
                ) {
                  this.inspectionContentList[i].INSPECT_STATE =
                    Math.random().toString();
                  break;
                }
              }
            }
            this.hiddenList.splice(index, 1);
          }
        },
      });
    },
    async fntempleSubmit() {
      debounce(async () => {
        uni.showLoading({
          title: "数据提交中",
        });
        if (this.hiddenList) {
          const hiddenList = await this.fnUploadHiddenImg();
          const SUPERVISE_INSPECT_ID =
            await this.fntempleSubmitForm(hiddenList);
          await this.fnUploadOnSiteInspectionPhotos(SUPERVISE_INSPECT_ID);
        }
        uni.hideLoading();
        uni.$u.toast("保存成功");
        uni.navigateBack();
      });
    },
    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;
              }
            }
            const validContentList = this.inspectionContentList.filter(
              (item) => item.INSPECT_CONTENT_SOURCE === 1,
            );
            if (validContentList.length === 0) {
              uni.$u.toast("请选择帮扶标准");
              return;
            }
            for (let i = 0; i < this.inspectionContentList.length; i++) {
              if (
                this.inspectionContentList[i].INSPECT_STATE !== "1" &&
                this.inspectionContentList[i].INSPECT_STATE !== "2"
              ) {
                uni.$u.toast(`第${i + 1}条帮扶标准请选择是否合格`);
                return;
              }
            }
            uni.showLoading({
              title: "数据提交中",
            });
            const hiddenList = await this.fnUploadHiddenImg();
            const SUPERVISE_INSPECT_ID = await this.fnSubmitForm(hiddenList);
            await this.fnUploadOnSiteInspectionPhotos(SUPERVISE_INSPECT_ID);
            uni.hideLoading();
            uni.$u.toast("保存成功");
            uni.navigateBack();
          })
          .catch(() => {
            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",
            });
          }
        }
        // if (files.length === 0) {
        //   continue;
        // }
        const newPathList = [];
        for (let i = 0; i < files.length; i++) {
          const newFile = [];
          newFile.push(files[i]);
          const {
            pathList,
            // hiddenIndex
          } = await setSupervisionInspectionHiddenImgAdd({
            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,
          SUPERVISE_INSPECT_USER_ID:
            this.inspectUserList[i].SUPERVISE_INSPECT_USER_ID || "",
        });
      }
      for (let i = 0; i < this.SUPERVISE_INSPECT_FILES_ID.length; i++) {
        await setSupervisionInspectionImgDel({
          SUPERVISE_INSPECT_FILES_ID: this.SUPERVISE_INSPECT_FILES_ID[i],
        });
      }
      for (let i = 0; i < this.hiddenDeleteImgsId.length; i++) {
        await setSupervisionInspectionImgDel({
          SUPERVISE_INSPECT_FILES_ID: this.hiddenDeleteImgsId[i],
        });
      }
      const inspectionContentListOld = this.inspectionContentListOld;
      const inspectionContentListNew = [];
      for (let i = 0; i < this.inspectionContentList.length; i++) {
        inspectionContentListNew.push(this.inspectionContentList[i].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.OldinspectionContentList),
        delInspectContentList: resDel.join(","),
        hiddenListRemoveList: this.hiddenListRemoveId.join(","),
        inspectUserRemoveList: this.inspectUserRemoveId.join(","),
      };
      const {
        pd: { SUPERVISE_INSPECT_ID },
      } = !this.SUPERVISE_INSPECT_ID
        ? await setSupervisionInspectionAdd(params)
        : await setSupervisionInspectionUpdate(params);
      return SUPERVISE_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,
          SUPERVISE_INSPECT_USER_ID:
            this.inspectUserList[i].SUPERVISE_INSPECT_USER_ID || "",
        });
      }
      for (let i = 0; i < this.SUPERVISE_INSPECT_FILES_ID.length; i++) {
        await setSupervisionInspectionImgDel({
          SUPERVISE_INSPECT_FILES_ID: this.SUPERVISE_INSPECT_FILES_ID[i],
        });
      }
      for (let i = 0; i < this.hiddenDeleteImgsId.length; i++) {
        await setSupervisionInspectionImgDel({
          SUPERVISE_INSPECT_FILES_ID: this.hiddenDeleteImgsId[i],
        });
      }
      const inspectionContentListOld = this.inspectionContentListOld;
      const inspectionContentListNew = [];
      for (let i = 0; i < this.inspectionContentList.length; i++) {
        inspectionContentListNew.push(this.inspectionContentList[i].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: { SUPERVISE_INSPECT_ID },
      } = !this.SUPERVISE_INSPECT_ID
        ? await setSupervisionInspectionAdd(params)
        : await setSupervisionInspectionUpdate(params);
      return SUPERVISE_INSPECT_ID;
    },
    async fnUploadOnSiteInspectionPhotos(SUPERVISE_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 setSupervisionInspectionImgAdd({
          files: newFile,
          formData: {
            SUPERVISE_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;
}
.u-icon {
  justify-content: center;
}
.radio-group-wrap {
  display: flex;
  flex-wrap: wrap;
  > div {
    padding: 10upx;
  }
}
</style>
