<template>
  <yhtopbar :applyStatus="applyStatus" showtype="detail"></yhtopbar>

  <van-overlay :show="overlayloading">
    <div class="wrapper">
      <van-loading color="#0094ff"> 加载中... </van-loading>
    </div>
  </van-overlay>
  <van-sticky :offset-top="50">
    <van-tabs v-model:active="active" type="card">
      <van-tab title="隐患详情">
        <van-form @submit="onSubmit('1')">
          <van-collapse v-model="activeNames">
            <van-collapse-item title="隐患信息" name="7101">
              <template #title>
                <div class="collapseTitle">隐患信息</div>
              </template>
              <van-cell-group inset>
                <van-field
                  v-model="yinhuanDetail.troubleType.text"
                  name="troubleType"
                  label="隐患类型"
                  placeholder="选择隐患类型"
                  readonly
                  @click="newdisabled ? '' : openPicker('troubleType')"
                />
                <van-field
                  v-model="yinhuanDetail.troubleCharType.text"
                  name="troubleCharType"
                  label="隐患小类"
                  placeholder="选择隐患小类"
                  readonly
                  @click="
                    newdisabled || troubleCharTypeDisabled
                      ? ''
                      : openPicker('troubleCharType')
                  "
                />
                <van-field
                  v-model="yinhuanDetail.findDate"
                  name="findDate"
                  label="发现时间"
                  placeholder="选择发现时间"
                  readonly
                  @click="newdisabled ? '' : openPicker('findDate')"
                  required
                />
                <van-field
                  v-model="yinhuanDetail.findNameCode.name"
                  name="findNameCode"
                  label="发现人"
                  placeholder="选择发现人"
                  readonly
                  @click="newdisabled ? '' : openFullPicker('findNameCode')"
                  required
                />
                <van-field
                  v-model="yinhuanDetail.otherFindNameCode.name"
                  name="otherFindNameCode"
                  label="其他发现人"
                  placeholder="选择其他发现人"
                  readonly
                  @click="
                    newdisabled ? '' : openFullPicker('otherFindNameCode')
                  "
                />
                <van-field
                  v-model="yinhuanDetail.troubleDesc"
                  rows="1"
                  autosize
                  label="隐患描述"
                  type="textarea"
                  placeholder="请输入隐患描述"
                  required
                  :readonly="newdisabled"
                />
                <van-field
                  v-model="yinhuanDetail.troubleLevel.text"
                  name="troubleLevel"
                  label="隐患等级"
                  placeholder="选择隐患等级"
                  readonly
                  @click="newdisabled ? '' : openPicker('troubleLevel')"
                  required
                />
                <van-field
                  v-model="yinhuanDetail.troubleAddrCodeName.text"
                  name="troubleAddrCodeName"
                  label="隐患地点"
                  placeholder="选择隐患地点"
                  readonly
                  @click="
                    newdisabled ? '' : openFullPicker('troubleAddrCodeName')
                  "
                />
                <van-field
                  v-model="yinhuanDetail.remarks"
                  rows="1"
                  autosize
                  label="备注"
                  type="textarea"
                  placeholder="请输入备注"
                  :readonly="newdisabled"
                />
                <van-field
                  name="dengjiUploader"
                  label="图片上传"
                  :disabled="newdisabled"
                >
                  <template #input>
                    <van-uploader
                      :disabled="newdisabled"
                      v-model="dengjiFileList"
                      multiple
                      accept="image/*"
                      :after-read="(file) => afterRead(file, 'dengji')"
                      :before-read="(file) => beforeRead(file, 'img')"
                      :max-size="5 * 1024 * 1024"
                      @oversize="onOversize"
                      :before-delete="
                        (file, cb) => beforeDel(file, cb, 'dengji')
                      "
                    />
                  </template>
                </van-field>
              </van-cell-group>
            </van-collapse-item>
            <!-- ------------------确认信息---------------------- -->
            <van-collapse-item
              name="7102"
              v-show="
                ['7102', '7103', '7104', '7106'].indexOf(applyStatus) != -1
              "
            >
              <template #title>
                <div class="collapseTitle">确认信息</div>
              </template>
              <van-cell-group inset>
                <van-field
                  v-model="yinhuanDetail.rectifyNameCode.name"
                  name="rectifyNameCode"
                  label="整改人"
                  placeholder="选择整改人"
                  readonly
                  @click="
                    fenxidisabled ? '' : openFullPicker('rectifyNameCode')
                  "
                  required
                />
                <van-field
                  v-model="yinhuanDetail.rectifyDeptNameCode.name"
                  name="rectifyDeptNameCode"
                  label="整改部门"
                  placeholder="选择整改部门"
                  readonly
                  @click="
                    fenxidisabled ? '' : openFullPicker('rectifyDeptNameCode')
                  "
                />
                <van-field
                  v-model="yinhuanDetail.rectifySuggest"
                  rows="1"
                  autosize
                  label="整改建议"
                  type="textarea"
                  placeholder="请输入整改建议"
                  required
                  :readonly="fenxidisabled"
                />
                <van-field
                  v-model="yinhuanDetail.preFinishDate"
                  name="preFinishDate"
                  label="整改期限"
                  placeholder="选择整改期限"
                  readonly
                  @click="fenxidisabled ? '' : openPicker('preFinishDate')"
                />
                <van-field
                  v-model="yinhuanDetail.checkNameCode.name"
                  name="checkNameCode"
                  label="复核人"
                  placeholder="选择复核人"
                  readonly
                  @click="fenxidisabled ? '' : openFullPicker('checkNameCode')"
                  required
                />
                <van-field
                  v-model="yinhuanDetail.otherCheckNameCode.name"
                  name="otherCheckNameCode"
                  label="其他复核人"
                  placeholder="选择其他复核人"
                  readonly
                  @click="
                    fenxidisabled ? '' : openFullPicker('otherCheckNameCode')
                  "
                />
              </van-cell-group>
            </van-collapse-item>
            <!-- ------------------整改---------------------- -->
            <van-collapse-item
              name="7103"
              v-show="['7103', '7104', '7106'].indexOf(applyStatus) != -1"
            >
              <template #title>
                <div class="collapseTitle">临时管控与整改</div>
              </template>
              <van-cell-group inset>
                <van-field name="guankongImgUploader" label="临时管控图片上传">
                  <template #input>
                    <van-uploader
                      :disabled="zhenggaidisabled"
                      v-model="guankongImgFileList"
                      multiple
                      accept="image/*"
                      :after-read="(file) => afterRead(file, 'guankongImg')"
                      :before-read="(file) => beforeRead(file, 'img')"
                      :max-size="5 * 1024 * 1024"
                      @oversize="onOversize"
                      :before-delete="
                        (file, cb) => beforeDel(file, cb, 'guankongImg')
                      "
                    />
                  </template>
                </van-field>
                <van-field name="guankonggaozhiuploader" label="临时管控告知书">
                  <template #input>
                    <van-uploader
                      :disabled="zhenggaidisabled"
                      v-model="guankonggaozhiFileList"
                      multiple
                      accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                      :after-read="(file) => afterRead(file, 'guankonggaozhi')"
                      :before-read="(file) => beforeRead(file, 'file')"
                      :max-size="5 * 1024 * 1024"
                      @oversize="onOversize"
                      :before-delete="
                        (file, cb) => beforeDel(file, cb, 'guankonggaozhi')
                      "
                    >
                      <van-button icon="plus" size="small" type="primary">
                        上传文件
                      </van-button>
                    </van-uploader>
                  </template>
                </van-field>
                <van-field
                  name="guankongxiaohaouploader"
                  label="临时管控销号单"
                >
                  <template #input>
                    <van-uploader
                      :disabled="zhenggaidisabled"
                      v-model="guankongxiaohaoFileList"
                      multiple
                      accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                      :after-read="(file) => afterRead(file, 'guankongxiaohao')"
                      :before-read="(file) => beforeRead(file, 'file')"
                      :max-size="5 * 1024 * 1024"
                      @oversize="onOversize"
                      :before-delete="
                        (file, cb) => beforeDel(file, cb, 'guankongxiaohao')
                      "
                    >
                      <van-button icon="plus" size="small" type="primary">
                        上传文件
                      </van-button>
                    </van-uploader>
                  </template>
                </van-field>
                <van-field name="zhenggaiImguploader" label="整改图片上传">
                  <template #input>
                    <van-uploader
                      :disabled="zhenggaidisabled"
                      v-model="zhenggaiImgFileList"
                      multiple
                      accept="image/*"
                      :after-read="(file) => afterRead(file, 'zhenggaiImg')"
                      :before-read="(file) => beforeRead(file, 'img')"
                      :max-size="5 * 1024 * 1024"
                      @oversize="onOversize"
                      :before-delete="
                        (file, cb) => beforeDel(file, cb, 'zhenggaiImg')
                      "
                    />
                  </template>
                </van-field>
                <van-field
                  v-model="yinhuanDetail.rectifySuggest"
                  rows="1"
                  autosize
                  label="整改情况"
                  type="textarea"
                  placeholder="请输入整改情况"
                  required
                  :readonly="zhenggaidisabled"
                />
              </van-cell-group>
            </van-collapse-item>
            <!-- ------------------复核信息---------------------- -->
            <!-- <van-collapse-item name="7104" v-show="applyStatus == '7104'">
        <template #title>
          <div class="collapseTitle">复核信息</div>
        </template>
        <van-cell-group inset>
          <van-field
            v-model="yinhuanDetail.traceSource"
            rows="2"
            autosize
            label="溯源情况"
            type="textarea"
            placeholder="请输入溯源情况"
            :disabled="xiaodisabled"
          />
        </van-cell-group>
      </van-collapse-item> -->
            <!-- ------------------销号信息---------------------- -->
            <van-collapse-item name="7106" v-show="applyStatus == '7106'">
              <template #title>
                <div class="collapseTitle">销号信息</div>
              </template>
              <van-cell-group inset>
                <van-field
                  v-model="yinhuanDetail.traceSource"
                  rows="2"
                  autosize
                  label="溯源情况"
                  type="textarea"
                  placeholder="请输入溯源情况"
                  :readonly="xiaodisabled"
                />
              </van-cell-group>
            </van-collapse-item>
          </van-collapse>
          <!-- ------------------审核信息---------------------- -->
          <van-cell
            title="审核信息"
            class="collapseTitle"
            v-show="['7102', '7103', '7104'].indexOf(applyStatus) != -1"
          />
          <div
            style="padding: 12px 16px"
            v-show="['7102', '7103', '7104'].indexOf(applyStatus) != -1"
          >
            <!-- <van-cell-group> -->
            <van-field
              v-model="yinhuanDetail.auditReason.text"
              name="auditReason"
              label="审核意见"
              placeholder="选择审核意见"
              readonly
              @click="openPicker('auditReason')"
            />
            <!-- <div>
        <van-button type="primary" size="small" @click="auditClick('1')">
          通过
        </van-button>
        <van-button type="default" size="small" @click="auditClick('0')">
          不通过
        </van-button>
      </div> -->
            <van-field
              v-model="yinhuanDetail.auditStateDesc"
              rows="2"
              autosize
              label="审核备注"
              type="textarea"
              placeholder="请输入审核备注"
            />
            <!-- </van-cell-group> -->
          </div>
          <van-popup v-model:show="showPicker" round position="bottom">
            <!-- 弹出隐患类型 -->
            <van-picker
              v-if="popupType === 'troubleType'"
              :columns="troubleTypeColumns"
              @cancel="showPicker = false"
              @confirm="troubleTypeConfirm"
            />
            <!-- 弹出隐患小类 -->
            <van-picker
              v-if="popupType === 'troubleCharType'"
              :columns="troubleCharTypeColumns"
              @cancel="showPicker = false"
              @confirm="troubleCharTypeConfirm"
            />
            <!-- 弹出时间 -->
            <van-picker-group
              v-if="popupType === 'findDate' || popupType === 'preFinishDate'"
              title="时间"
              :tabs="['选择日期', '选择时间']"
              next-step-text="下一步"
              @confirm="dateConfirm"
              @cancel="showPicker = false"
            >
              <van-date-picker
                v-model="currentDate"
                :min-date="minDate"
                :max-date="maxDate"
              />
              <van-time-picker v-model="currentTime" />
            </van-picker-group>
            <!-- 弹出隐患等级 -->
            <van-picker
              v-if="popupType === 'troubleLevel'"
              :columns="troubleLevelColumns"
              @cancel="showPicker = false"
              @confirm="troubleLevelConfirm"
            />
            <!-- 弹出审批意见 -->
            <van-picker
              v-if="popupType === 'auditReason'"
              :columns="auditReasonColumns"
              @cancel="showPicker = false"
              @confirm="auditReasonConfirm"
            />
          </van-popup>
          <!-- 弹出人员选择 -->
          <van-popup
            v-model:show="showFullPicker"
            style="height: 100%; width: 100%"
          >
            <!-- v-if="
          fullPickerType == 'findNameCode' ||
          fullPickerType == 'otherFindNameCode' ||
          fullPickerType == 'rectifyNameCode' ||
          fullPickerType == 'rectifyDeptNameCode' ||
          fullPickerType == 'rectifyDeptNameCode'
        " -->
            <personList
              v-if="
                [
                  'findNameCode',
                  'otherFindNameCode',
                  'rectifyNameCode',
                  'checkNameCode',
                  'otherCheckNameCode',
                ].indexOf(fullPickerType) !== -1
              "
              :key="fullPickerKey"
              @closeFullPicker="closeFullPicker"
              :selPer="selPer"
            ></personList>
            <addressList
              v-if="fullPickerType == 'troubleAddrCodeName'"
              :key="fullPickerKey"
              @closeFullPicker="closeFullPicker"
              :selAddr="selAddr"
            ></addressList>
            <deptList
              v-if="fullPickerType == 'rectifyDeptNameCode'"
              :key="fullPickerKey"
              @closeFullPicker="closeFullPicker"
              :selDept="selDept"
            ></deptList>
          </van-popup>

          <div style="height: 60px"></div>

          <!-- <van-sticky position="bottom" style="border: 1px #000 solid"> -->
          <div class="submitBottom">
            <van-row
              justify="space-around"
              style="height: 60px; display: flex; align-items: center"
            >
              <van-col span="12">
                <van-button round block type="primary" native-type="submit">
                  提交
                </van-button>
              </van-col>
              <van-col span="5">
                <van-button round block color="#e3e3e3" @click="onSubmit('0')">
                  <span style="color: #000">保存</span>
                </van-button>
              </van-col>
              <van-col span="5">
                <van-button round block type="default" @click="closeDetail">
                  关闭
                  <!-- {{ id === "" ? "取消" : "删除" }} -->
                </van-button>
              </van-col>
            </van-row>
          </div>
          <!-- </van-sticky> -->
        </van-form>
      </van-tab>
      <van-tab title="流程进度">
        <van-steps direction="vertical" active="-1">
          <van-step v-for="(flow, idx) in flowInfo" :key="idx">
            <h3>{{ flow.fkNodeName }}</h3>
            <p>{{ flow.fkEmpName }}</p>
            <p>{{ flow.rdt }}</p>
          </van-step>
        </van-steps>
      </van-tab>
    </van-tabs>
  </van-sticky>
</template>

<script setup>
import { ref, onMounted, reactive, watch, toRaw } from "vue";
// import DataTime from "@/components/datatime/index.vue";   日期时间在一起的
import yhtopbar from "./top.vue";
import personList from "@/components/personList.vue";
import addressList from "@/components/addressList.vue";
import deptList from "@/components/deptList.vue";

import {
  getYinhuanDetail,
  getYinhuanType,
  saveYinhuan,
  getYinhuanNew,
  getFlowInfo,
} from "@/api/yinhuan.js";
import { uploadData, getDist } from "@/api/index.js";
// import uploaderImage from "@/components/uploader.vue";
//上传图片调用企微的js-sdk
// import { initWxConfig } from "@/utils/initWxConfig.js";
import { fileToMD5 } from "@/utils/fileToMD5";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
const props = defineProps({
  showtype: String,
});
const overlayloading = ref(false);
const troubleCharTypeDisabled = ref(false);

const id = ref(route.query.id);
const applyStatus = ref(route.query.applyStatus);
const flowId = ref(route.query.flowId);
const newdisabled = ref(applyStatus.value == "7101" ? false : true);
const fenxidisabled = ref(applyStatus.value == "7102" ? false : true);
const zhenggaidisabled = ref(applyStatus.value == "7103" ? false : true);
const xiaodisabled = ref(applyStatus.value == "7106" ? false : true);

const activeNames = ref([applyStatus.value]);
console.log("----activeNames", applyStatus.value);

const saveDetail = reactive({});

const yinhuanDetail = reactive({
  //   id: route.query.id,
  // code: {},
  troubleType: {},
  troubleCharType: {},
  findDate: "",
  findNameCode: {},
  otherFindNameCode: {},
  //隐患描述
  troubleAddrCodeName: {},
  troubleDesc: "",
  //隐患等级
  troubleLevel: {},
  //备注
  remarks: "",
  //-------分析确认-------
  rectifyNameCode: {},
  rectifyDeptNameCode: {},
  rectifySuggest: "",
  preFinishDate: "",
  checkNameCode: {},
  otherCheckNameCode: {},

  //溯源情况
  traceSource: "",
  //   applyStatus: route.query.applyStatus,
  //   flowId: route.query.flowId,

  //----审核信息-----
  auditReason: {},
  auditStateDesc: "",
});

onMounted(async () => {
  setCurrenDateTime();
  init();
  // await getTroubleType();
  // if (yinhuanDetail.id !== "") {
  //   await getDetail();
  // }
  //企业微信API
  // const apiList = [
  //   "chooseImage",
  //   "previewImage",
  //   "uploadImage",
  //   "downloadImage",
  //   "getLocalImgData",
  // ];
  // initWxConfig(window.location.href, apiList);
});

// const code = ref("");
// const troubleType = ref({});
// const troubleCharType = ref({});

// 发现时间
// const findDate = ref("");
const currentDate = ref([]);
const currentTime = ref([]);
const minDate = ref("");
const maxDate = ref("");

const setCurrenDateTime = () => {
  //设置当前日期和时间
  let curDateTime = new Date();
  let Y = curDateTime.getFullYear();
  let M = curDateTime.getMonth() + 1;
  let D = curDateTime.getDate();
  currentDate.value = [Y, M, D];
  let h = curDateTime.getHours();
  let m = curDateTime.getMinutes();

  currentTime.value = [h, m];
  // 设置最小日期和最大日期
  let curYear = new Date().getFullYear();
  minDate.value = new Date(curYear - 2, 0, 1);
  maxDate.value = new Date(curYear + 2, 11, 31);
};

//popup弹出类型 隐患类型、发现时间
const popupType = ref("");
const showPicker = ref(false);

let troubleAllTypeColumns = [];
const troubleTypeColumns = [];
async function getTroubleType() {
  let data = {
    systemId: 0,
  };
  await getYinhuanType(data).then((res) => {
    console.log(res);
    if (res && res.code == "200") {
      troubleAllTypeColumns = res.data;
      const firstLevel = troubleAllTypeColumns.map((item) => {
        let firstItem = {};
        firstItem.value = item.value;
        firstItem.text = item.text;
        return firstItem;
      });
      troubleTypeColumns.push(...firstLevel);
    } else {
      showFailToast("获取隐患类型失败:" + JSON.stringify(res));
    }
  });
}

let troubleCharTypeColumns = [];
const openPicker = (val) => {
  if (val === "troubleType") {
    yinhuanDetail.troubleCharType = {};
  }
  if (val === "troubleCharType" && troubleCharTypeDisabled.value === true) {
    popupType.value = val;
    showPicker.value = false;
  } else {
    popupType.value = val;
    showPicker.value = true;
  }
};
//选中隐患类型
const troubleTypeConfirm = ({ selectedOptions }) => {
  let sopt = selectedOptions[0];
  yinhuanDetail.troubleType = sopt;
  showPicker.value = false;

  for (let i = 0; i < troubleAllTypeColumns.length; i++) {
    if (troubleAllTypeColumns[i].value === sopt.value) {
      let typechild = troubleAllTypeColumns[i].children;
      if (typechild.length > 0) {
        troubleCharTypeDisabled.value = false;
        troubleCharTypeColumns = typechild.map((item) => {
          let c = {};
          c.text = item.text;
          c.value = item.value;
          return c;
        });
        yinhuanDetail.troubleCharType = troubleCharTypeColumns[0];
      } else {
        troubleCharTypeDisabled.value = true;
        troubleCharTypeColumns = [];
        yinhuanDetail.troubleCharType = { text: "", value: "" };
      }
      break;
    }
  }
};
//选中隐患小类
const troubleCharTypeConfirm = ({ selectedOptions }) => {
  if (selectedOptions[0] != undefined) {
    yinhuanDetail.troubleCharType = selectedOptions[0];
  }
  showPicker.value = false;
};
//选中发现时间
const dateConfirm = () => {
  let curDate = `${currentDate.value.join("-")} ${currentTime.value.join(":")}`;
  console.log(curDate);
  curDate = curDate + ":00";
  if (popupType.value == "findDate") {
    yinhuanDetail.findDate = curDate;
  } else if (popupType.value == "preFinishDate") {
    yinhuanDetail.preFinishDate = curDate;
  }

  showPicker.value = false;
};

//popup人员/地点弹出
// const findNameCode = reactive({});
// const otherFindNameCode = reactive({});
const selPer = reactive([]);
const selDept = reactive([]);
const fullPickerKey = ref(0);

// const troubleAddr = reactive({});
const selAddr = reactive([]);
const addressListKey = ref(0);

const fullPickerType = ref("");
const showFullPicker = ref(false);

const openFullPicker = (val) => {
  selPer.length = 0;
  selAddr.length = 0;
  selDept.length = 0;
  console.log(
    val,
    JSON.stringify(yinhuanDetail.findNameCode),
    JSON.stringify(yinhuanDetail.rectifyNameCode)
  );
  fullPickerKey.value++;
  if (
    val == "findNameCode" &&
    JSON.stringify(yinhuanDetail.findNameCode) != "{}"
  ) {
    selPer.push(yinhuanDetail.findNameCode);
  } else if (
    val == "otherFindNameCode" &&
    JSON.stringify(yinhuanDetail.otherFindNameCode) != "{}"
  ) {
    selPer.push(yinhuanDetail.otherFindNameCode);
  } else if (
    val == "troubleAddrCodeName" &&
    JSON.stringify(yinhuanDetail.troubleAddrCodeName) != "{}"
  ) {
    console.log("-------", yinhuanDetail.troubleAddrCodeName);
    selAddr.push(yinhuanDetail.troubleAddrCodeName);
    console.log("-------", selAddr);
  } else if (
    val == "rectifyNameCode" &&
    JSON.stringify(yinhuanDetail.rectifyNameCode) != "{}"
  ) {
    selPer.push(yinhuanDetail.rectifyNameCode);
  } else if (
    val == "rectifyDeptNameCode" &&
    JSON.stringify(yinhuanDetail.rectifyDeptNameCode) != "{}"
  ) {
    console.log("selDept", selDept);
    selDept.push(yinhuanDetail.rectifyDeptNameCode);
  } else if (
    val == "checkNameCode" &&
    JSON.stringify(yinhuanDetail.checkNameCode) != "{}"
  ) {
    selPer.push(yinhuanDetail.checkNameCode);
  } else if (
    val == "otherCheckNameCode" &&
    JSON.stringify(yinhuanDetail.otherCheckNameCode) != "{}"
  ) {
    selPer.push(yinhuanDetail.otherCheckNameCode);
  }

  fullPickerType.value = val;
  showFullPicker.value = true;
};
// 关闭选择人员并赋值
const closeFullPicker = (type) => {
  if (type == "ok") {
    if (fullPickerType.value == "findNameCode") {
      console.log("....", selPer);
      yinhuanDetail.findNameCode.id = selPer[0].id;
      yinhuanDetail.findNameCode.name = selPer[0].name;
      console.log("....", selPer);
      // selPer.length = 0;
    } else if (fullPickerType.value == "otherFindNameCode") {
      yinhuanDetail.otherFindNameCode.id = selPer[0].id;
      yinhuanDetail.otherFindNameCode.name = selPer[0].name;
      selPer.length = 0;
    } else if (fullPickerType.value == "troubleAddrCodeName") {
      yinhuanDetail.troubleAddrCodeName.id = selAddr[0].id;
      yinhuanDetail.troubleAddrCodeName.text = selAddr[0].text;
      selAddr.length = 0;
    } else if (fullPickerType.value == "rectifyNameCode") {
      yinhuanDetail.rectifyNameCode.id = selPer[0].id;
      yinhuanDetail.rectifyNameCode.name = selPer[0].name;
      selPer.length = 0;
    } else if (fullPickerType.value == "rectifyDeptNameCode") {
      yinhuanDetail.rectifyDeptNameCode.id = selDept[0].id;
      yinhuanDetail.rectifyDeptNameCode.name = selDept[0].text;
      selDept.length = 0;
    } else if (fullPickerType.value == "checkNameCode") {
      yinhuanDetail.checkNameCode.id = selPer[0].id;
      yinhuanDetail.checkNameCode.name = selPer[0].name;
      selPer.length = 0;
    } else if (fullPickerType.value == "otherCheckNameCode") {
      yinhuanDetail.otherCheckNameCode.id = selPer[0].id;
      yinhuanDetail.otherCheckNameCode.name = selPer[0].name;
      selPer.length = 0;
    }
  }
  showFullPicker.value = false;
};

// //隐患描述
// const troubleAddr = reactive({});
// const troubleDesc = ref("");

// //隐患等级
// const troubleLevel = ref({});
// const troubleLevelColumns = [
//   { text: "重大隐患", value: "2" },
//   { text: "一般隐患", value: "1" },
// ];
const troubleLevelColumns = reactive([]);
// await getAuditReason();

async function getTroubleLevel() {
  await getDist("dss_partrol_sample_level").then((res) => {
    if (typeof res === "object" && Array.isArray(res)) {
      res.forEach((item) => {
        let level = { text: item.dictLabel, value: item.dictValue };
        troubleLevelColumns.push(level);
      });
    } else {
      showFailToast("获取隐患等级失败");
    }
  });
}

//选中隐患等级
const troubleLevelConfirm = ({ selectedOptions }) => {
  yinhuanDetail.troubleLevel = selectedOptions[0];
  showPicker.value = false;
};

// 整改前图片上传
const dengjiFileList = ref([]);
const dengjiUploadfiles = ref([]); // ref("");
//--------------------------整改---------------------------
//临时管控图片上传
const guankongImgFileList = ref([]);
const guankongImgUploadfiles = ref([]); // ref("");
//临时管控告知书
const guankonggaozhiFileList = ref([]);
const guankonggaozhiUploadfiles = ref([]); // ref("");
//临时管控销号单
const guankongxiaohaoFileList = ref([]);
const guankongxiaohaoUploadfiles = ref([]); // ref("");
//整改图片上传
const zhenggaiImgFileList = ref([]);
const zhenggaiImgUploadfiles = ref([]); // ref("");

//审批意见
// const auditReasonColumns = [
//   { text: "通过", value: "1" },
//   { text: "不通过", value: "2" },
// ];
const auditReasonColumns = reactive([]);
async function getAuditReason() {
  await getDist("sys_audit_status").then((res) => {
    console.log(res);
    if (typeof res === "object" && Array.isArray(res)) {
      res.forEach((item) => {
        let resson = { text: item.dictLabel, value: item.dictValue };
        auditReasonColumns.push(resson);
      });
    } else {
      showFailToast("获取审批意见失败");
    }
  });
}

//选中审批意见
const auditReasonConfirm = ({ selectedOptions }) => {
  yinhuanDetail.auditReason = selectedOptions[0];
  showPicker.value = false;
};

const onOversize = (file) => {
  showToast("图片大小不能超过 5MB");
};

const beforeRead = (file, type) => {
  if (file instanceof Array) {
    // 多张图片
    file.forEach((f) => {
      if (type == "img" && f.type.indexOf("image/") == -1) {
        showToast("请上传 jpg 格式图片");
        return false;
      }
    });
  } else {
    if (type == "img" && file.type.indexOf("image/") == -1) {
      showToast("请上传 jpg 格式图片");
      return false;
    }
  }
  return true;
};

const afterRead = (file, id) => {
  file.status = "uploading";
  file.message = "上传中...";

  if (file instanceof Array) {
    // 多张图片
    file.forEach((f) => {
      // file.status = "done";
      uploadImgFile(f, id);
    });
  } else {
    // 单张图片
    uploadImgFile(file, id);
  }
};
const beforeDel = (file, cb, id) => {
  console.log(file, cb, id);
  if (id == "dengji") {
    dengjiUploadfiles.value.splice(cb.index, 1);
  } else if (id == "guankongImg") {
    guankongImgUploadfiles.value.splice(cb.index, 1);
  } else if (id == "guankonggaozhi") {
    guankonggaozhiUploadfiles.value.splice(cb.index, 1);
  } else if (id == "guankongxiaohao") {
    guankongxiaohaoUploadfiles.value.splice(cb.index, 1);
  } else if (id == "zhenggaiImg") {
    zhenggaiImgUploadfiles.value.splice(cb.index, 1);
  }

  return true;
};

async function uploadImgFile(file, id) {
  const fileMd5 = await fileToMD5(file.file);
  // 使用 FormData 来包装文件z
  // const formData = new FormData();
  // formData.append("file", file.file);
  let fileData = {
    fileMd5: fileMd5,
    fileName: file.file.name,
  };
  // formData.append("fileData", JSON.stringify(fileData));
  // return;
  console.log(fileData);
  await uploadData(fileData).then((res) => {
    console.log(res);
    if (res.result == "true") {
      // if (res.data.result === "true") {
      let fileid = res.fileUpload.id;
      if (id == "dengji") {
        dengjiUploadfiles.value.push(fileid);
      } else if (id == "guankongImg") {
        guankongImgUploadfiles.value.push(fileid);
      } else if (id == "guankonggaozhi") {
        guankonggaozhiUploadfiles.value.push(fileid);
      } else if (id == "guankongxiaohao") {
        guankongxiaohaoUploadfiles.value.push(fileid);
      } else if (id == "zhenggaiImg") {
        zhenggaiImgUploadfiles.value.push(fileid);
      }

      showSuccessToast("上传成功");
      file.status = "done";
      // } else {
      //   showFailToast("上传失败");
      //   file.status = "failed";
      // }
    } else {
      showFailToast(res.message);
      file.status = "failed";
    }
  });
}

// 调用后端上传
// async function uploadImg(file) {
//   const fileMd5 = await fileToMD5(file.file);
//   // 使用 FormData 来包装文件z
//   const formData = new FormData();
//   formData.append("file", file.file);
//   let fileData = {
//     fileMd5: fileMd5,
//     fileName: file.file.name,
//   };
//   formData.append("fileData", JSON.stringify(fileData));
//   // return;
//   await uploadData(formData).then((res) => {
//     if (res.code == 200) {
//       if (res.data.result === "true") {
//         let fileid = res.data.fileUpload.id;
//         uploadfiles.value.push(fileid);
//         showSuccessToast("上传成功");
//         file.status = "done";
//       } else {
//         showFailToast("上传失败");
//         file.status = "failed";
//       }
//     } else {
//       showFailToast(res.msg);
//       file.status = "failed";
//     }
//   });
// }
/////
async function init() {
  overlayloading.value = true;

  //
  if (applyStatus.value == "7101") {
    await getTroubleType();
    await getTroubleLevel();
    await getNew();
  } else {
    await getDetail();
    await getAuditReason();
    await openFlow();
  }

  overlayloading.value = false;
}

async function getNew() {
  let data = { id: "" };
  await getYinhuanNew(data).then((res) => {
    if (res) {
      if (res.code == "200") {
        yinhuanDetail.value = res.data.sppSrzHiddenTrouble;
        Object.assign(saveDetail, res.data.sppSrzHiddenTrouble);
      } else {
        showFailToast("新增隐患登记失败," + JSON.stringify(res));
      }
    } else {
      showFailToast("新增隐患登记失败");
    }
  });
}
async function getDetail() {
  await getYinhuanDetail(id.value).then((res) => {
    console.log("res-----", res);
    if (res && res.code == "200") {
      let initData = res.data.sppSrzHiddenTrouble;
      yinhuanDetail.value = res.data.sppSrzHiddenTrouble;
      Object.assign(saveDetail, res.data.sppSrzHiddenTrouble);
      console.log(yinhuanDetail.value);
      //隐患类型
      if (initData.troubleTypeValue) {
        let troubleTypeValue = initData.troubleTypeValue;
        yinhuanDetail.troubleType = troubleTypeColumns.find((item) => {
          return item.value == troubleTypeValue;
        });
        //隐患小类下拉数据列表填充
        for (let i = 0; i < troubleAllTypeColumns.length; i++) {
          if (troubleAllTypeColumns[i].value === troubleTypeValue) {
            let typechild = troubleAllTypeColumns[i].children;
            if (typechild.length > 0) {
              troubleCharTypeDisabled.value = false;
              troubleCharTypeColumns = typechild.map((item) => {
                let c = {};
                c.text = item.text;
                c.value = item.value;
                return c;
              });
            } else {
              troubleCharTypeDisabled.value = true;
              troubleCharTypeColumns = [];
              yinhuanDetail.troubleCharType = { text: "", value: "" };
            }
            break;
          }
        }

        //隐患小类数据填充
        let troubleCharType = initData.troubleCharType;
        yinhuanDetail.troubleCharType = troubleCharTypeColumns.find((i) => {
          return i.value == troubleCharType;
        });
      }

      let findData = initData.findDate;
      yinhuanDetail.findDate = findData.substring(0, findData.lastIndexOf(":"));

      //发现人
      let findCode = initData.findCode;
      let findName = initData.findName;
      yinhuanDetail.findNameCode = { id: findCode, name: findName };
      //其他发现人
      let otherFindCode = initData.otherFindCode;
      let otherFindName = initData.otherFindName;
      yinhuanDetail.otherFindNameCode = {
        id: otherFindCode,
        name: otherFindName,
      };
      //发现地点
      let troubleAddrCode = initData.troubleAddrCode;
      let troubleAddr = initData.troubleAddr;
      yinhuanDetail.troubleAddrCodeName = {
        id: troubleAddrCode,
        text: troubleAddr,
      };
      // yinhuanDetail.troubleAddr = {
      //   name: initData.troubleAddr,
      // };

      //隐患描述
      yinhuanDetail.troubleDesc = initData.troubleDesc;

      //隐患等级
      let troubleLevel = initData.troubleLevel;
      let troubleLevelName = initData.troubleLevelName;
      yinhuanDetail.troubleLevel = {
        value: troubleLevel,
        text: troubleLevelName,
      };
      //备注
      yinhuanDetail.remarks = initData.remarks;
      let files = initData.files;
      // console.log(files);
      // files.forEach((item) => {
      //   let fileu = item.fileUrl;
      //   let tofile = "/tosecure" + fileu.substring(fileu.indexOf("/web"));
      //   let fileid = fileu.substring(
      //     fileu.lastIndexOf("/") + 1,
      //     fileu.lastIndexOf(".")
      //   );
      //   dengjiFileList.value.push({ id: fileid, url: tofile });
      //   dengjiUploadfiles.value.push(fileid);
      // });
      // dengjiFileList.value.push({ id: fileid, url: tofile });
      // dengjiUploadfiles.value.push(fileid);
      // ---------------------分析确认-----------------------
      //发现人
      if (initData.rectifyCode) {
        let rectifyCode = initData.rectifyCode;
        let rectifyName = initData.rectifyName;
        yinhuanDetail.rectifyNameCode = { id: rectifyCode, name: rectifyName };
      }

      if (initData.rectifyDept) {
        let rectifyDept = initData.rectifyDept;
        yinhuanDetail.rectifyDeptNameCode = {
          id: rectifyDept,
          name: rectifyDept,
        };
      }

      yinhuanDetail.rectifySuggest = initData.rectifySuggest
        ? initData.rectifySuggest
        : "";
      //整改期限
      if (initData.preFinishDate) {
        let preFinishDate = initData.preFinishDate;
        yinhuanDetail.preFinishDate = preFinishDate.substring(
          0,
          preFinishDate.lastIndexOf(":")
        );
      }

      //复核人
      if (initData.checkCode) {
        let checkCode = initData.checkCode;
        let checkName = initData.checkName;
        yinhuanDetail.checkNameCode = { id: checkCode, name: checkName };
      }
      //其他复核人
      if (initData.otherCheckCode) {
        let otherCheckCode = initData.otherCheckCode;
        let otherCheckName = initData.otherCheckName;
        yinhuanDetail.otherCheckNameCode = {
          id: otherCheckCode,
          name: otherCheckName,
        };
      }

      //审核意见
      yinhuanDetail.auditReason = initData.auditReason;

      //审核描述
      yinhuanDetail.auditStateDesc = initData.auditStateDesc;
    } else {
      showFailToast("获取隐患详情失败:" + JSON.stringify(res));
    }
  });
}

const validFeild = () => {
  let vresult = true;
  //   if (yinhuanDetail.troubleType.value === "") {
  //     showFailToast("隐患类型不能为空");
  //     vresult = false;
  //   }
  if (yinhuanDetail.findDate === "") {
    showFailToast("隐患发现时间不能为空");
    vresult = false;
  }
  // if (yinhuanDetail.findNameCode.name === undefined) {
  //   showFailToast("隐患发现人不能为空");
  //   vresult = false;
  // }
  if (yinhuanDetail.troubleDesc === "") {
    showFailToast("隐患描述不能为空");
    vresult = false;
  }
  if (yinhuanDetail.troubleLevel.value === undefined) {
    showFailToast("隐患等级不能为空");
    vresult = false;
  }
  return vresult;
};

const onSubmit = (submittype) => {
  console.log("yinhuanDetail--", yinhuanDetail);
  console.log("submittype--", submittype);
  // if (!validFeild()) {
  //   return;
  // }
  // let files = uploadfiles.value.substring(0, uploadfiles.value.length - 1);
  let files = dengjiUploadfiles.value + "";
  console.log("savefiles==", files);

  // let data = {
  //   id: id.value,
  //   // code: yinhuanDetail.code,
  //   applyStatus: applyStatus.value,
  //   applyStatusName: "隐患登记",
  //   flowId: flowId.value,
  //   systemId: 0,
  //   findCode: yinhuanDetail.findNameCode.id,
  //   findDate: yinhuanDetail.findDate,
  //   findName: yinhuanDetail.findNameCode.name,
  //   otherFindName: yinhuanDetail.otherFindNameCode.name,
  //   otherFindCode: yinhuanDetail.otherFindNameCode.id,
  //   troubleAddr: yinhuanDetail.troubleAddr.name,
  //   troubleDesc: yinhuanDetail.troubleDesc,
  //   troubleType: yinhuanDetail.troubleType.value,
  //   troubleCharType: yinhuanDetail.troubleCharType.value,
  //   troubleLevel: yinhuanDetail.troubleLevel.value,
  //   remarks: yinhuanDetail.remarks,
  //   sppSrzHiddenTrouble_image: files,
  //   permi: { submit: submittype },
  // };
  saveDetail.id = id.value;
  saveDetail.workId = saveDetail.workId ? saveDetail.workId : "0";
  saveDetail.findCode = yinhuanDetail.findNameCode.id;
  saveDetail.findDate = yinhuanDetail.findDate;
  saveDetail.findName = yinhuanDetail.findNameCode.name;
  saveDetail.otherFindName = yinhuanDetail.otherFindNameCode.name;
  saveDetail.otherFindCode = yinhuanDetail.otherFindNameCode.id;
  saveDetail.troubleAddr = yinhuanDetail.troubleAddrCodeName.text;
  saveDetail.troubleAddrCode = yinhuanDetail.troubleAddrCodeName.id;
  saveDetail.troubleDesc = yinhuanDetail.troubleDesc;
  // saveDetail.troubleType = yinhuanDetail.troubleType.value;
  // saveDetail.troubleCharType = yinhuanDetail.troubleCharType.value;
  saveDetail.troubleLevel = yinhuanDetail.troubleLevel.value;
  saveDetail.remarks = yinhuanDetail.remarks;
  saveDetail.sppSrzHiddenTrouble_image = files;

  // ---------分析确认---------------

  saveDetail.rectifyCode = yinhuanDetail.rectifyNameCode.id;
  saveDetail.rectifyName = yinhuanDetail.rectifyNameCode.name;
  // 整改部门
  //     saveDetail.rectifyCode = yinhuanDetail.rectifyDeptNameCode.id;
  //      saveDetail.rectifyName = yinhuanDetail.rectifyDeptNameCode.name;
  // rectifyDeptNameCode: {},
  saveDetail.rectifySuggest = yinhuanDetail.rectifySuggest;
  saveDetail.preFinishDate = yinhuanDetail.preFinishDate;
  saveDetail.checkCode = yinhuanDetail.checkNameCode.id;
  saveDetail.checkName = yinhuanDetail.checkNameCode.name;
  saveDetail.otherCheckCode = yinhuanDetail.otherCheckNameCode.id;
  saveDetail.otherCheckName = yinhuanDetail.otherCheckNameCode.name;

  saveDetail.permi = { submit: submittype };

  let data = toRaw(saveDetail);

  // let data = {
  //   isNewRecord: true,
  //   flowId: "071",
  //   auditState: 0,
  //   auditReason: "",
  //   findName: "测试01",
  //   findCode: "ceshi01_qqsp",
  //   applyStatus: 7101,
  //   analysisCode: "anquanyuantest_ho76,baiming_2jjv,fangmaofeng_p8st",
  //   analysisName: "安全员测试,白明,方茂峰",
  //   isMy: 0,
  //   files: [],
  //   fhFiles: [],
  //   zgFiles: [],
  //   lsgkPicFiles: [],
  //   lsgkFiles: [],
  //   xhFiles: [],
  //   applyStatusName: "隐患登记",
  //   code: "YH-6525",
  //   systemId: 0,
  //   systemDel: 0,
  //   opid: 6525,
  //   auditStateDesc: "提交申请",
  //   id: "",
  //   workId: "0",
  //   findDate: "2024-11-11 16:25:00",
  //   troubleDesc: "1111",
  //   // troubleType: "1",
  //   troubleCharType: "1002",
  //   troubleLevel: "2",
  //   remarks: "",
  //   sppSrzHiddenTrouble_image: "",
  //   permi: {
  //     submit: "1",
  //   },
  // };
  // let data = {
  //   id: "",
  //   applyStatus: 7102,
  //   applyStatusName: "隐患登记",
  //   systemId: 0,
  //   flowId: "071",
  //   workId: "0",
  //   code: "YH-6371",
  //   opid: 6371,
  //   analysisCode:
  //     "zhaoxueai_ek6q,zhushibao_m3dd,anquantest_cvz7,dangyong_toth,hanxue_fiqk",
  //   analysisName: "赵学爱,朱世保,安全管理部测试,党勇,韩雪",
  //   troubleType: "1250724508810235904",
  //   findDate: "2024-11-09 21:30:23",
  //   troubleCharType: "2001",
  //   findName: "韩雪",
  //   findCode: "hanxue_fiqk",
  //   otherFindName: "",
  //   otherFindCode: "",
  //   troubleDesc: 1,
  //   troubleLevel: 2,
  //   troubleAddr: "厂前（机关办公区）",
  //   troubleAddrCode: "YH-01101001",
  //   remarks: "11",
  //   sppSrzHiddenTrouble_image: "1855189536840024064",
  //   sppSrzHiddenTrouble_image__del: "",
  //   permi: { submit: "1" },
  // };
  console.log(data);
  saveYinhuan(data).then((res) => {
    if (res.code == "200") {
      showSuccessToast(res.msg);
      router.push("/yinhuanList/" + applyStatus.value);
    } else {
      showFailToast(res.msg);
    }
  });
};

const closeDetail = () => {
  router.go(-1);
};

const flowInfo = reactive([]);
async function openFlow() {
  await getFlowInfo(saveDetail.id).then((res) => {
    if (typeof res === "object" && Array.isArray(res)) {
      flowInfo.push(...res);
    } else {
      showFailToast("获取流程进度失败");
    }
  });
}
</script>

<style>
/* 设置人员弹出的背景 */
.van-popup--center {
  max-width: 100%;
}
/* 遮罩 */
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.van-overlay {
  z-index: 2;
  background-color: rgba(0, 0, 0, 0.5);
}
.collapseTitle {
  font-weight: bold;
}
.submitBottom {
  height: 60px;
  line-height: 60px;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #f7f8fa;
}
.van-button--round {
  border-radius: 12px;
}
.van-tabs__wrap {
  background: #fff;
  /* background: var(--van-gray-2); */
}
.van-tabs--card > .van-tabs__wrap {
  height: 36px;
}
.van-step {
  color: #323233;
}
</style>
