<template>
  <view>
    <Navbar :title="opt.title" />
    <div class="tabs" v-if="!opt.isAdd && !opt.isRecord">
      <u-tabs :list="tabList" @click="handleTab" lineWidth="40"></u-tabs>
    </div>
    <div class="content">
      <div v-if="currentTab == 0">
        <u-form :model="formData" :rules="rules" ref="uForm" labelWidth="auto" labelPosition="left">
          <Title title="基本信息" />
          <u-form-item label="隐患问题编号" prop="pitfallCode">
            <u-input v-model="formData.pitfallCode" placeholder="隐患问题编号" border="bottom" disabled></u-input>
          </u-form-item>
          <u-form-item label="检查记录编号" prop="recordCode">
            <u-input v-model="formData.recordCode" placeholder="检查记录编号" border="bottom" disabled></u-input>
          </u-form-item>
          <u-form-item label="对应检查级别" prop="checkLevelName">
            <u-input v-model="formData.checkLevelName" placeholder="检查级别" border="bottom" disabled></u-input>
          </u-form-item>
          <u-form-item label="排查类型" prop="checkTypeName" :required="opt.isAdd">
            <u-cell-group :border="false">
              <u-cell
                :title="formData.checkTypeName"
                isLink
                :label="formData.checkTypeName ? '' : '请选择排查类型'"
                @click="handlePicker(8)"
                :disabled="!opt.isAdd || opt.checkType ? true : false"
              ></u-cell>
            </u-cell-group>
          </u-form-item>
          <u-form-item label="创建人" prop="createUserName">
            <u-input v-model="formData.createUserName" placeholder="创建人" border="bottom" disabled></u-input>
          </u-form-item>
          <u-form-item label="创建时间" prop="createTime">
            <u-input v-model="formData.createTime" placeholder="创建时间" border="bottom" disabled></u-input>
          </u-form-item>
          <u-form-item label="整改接收时间" prop="rectificationReceiveTime">
            <u-input
              v-model="formData.rectificationReceiveTime"
              placeholder="整改接收时间"
              border="bottom"
              disabled
            ></u-input>
          </u-form-item>
          <u-form-item label="整改反馈时间" prop="rectificationFeedbackTime">
            <u-input
              v-model="formData.rectificationFeedbackTime"
              placeholder="整改反馈时间"
              border="bottom"
              disabled
            ></u-input>
          </u-form-item>
          <u-form-item label="整改状态" prop="checkStatus">
            <u-input v-model="formData.checkStatus" placeholder="整改状态" border="bottom" disabled></u-input>
          </u-form-item>
          <!-- 检查方填写 -->
          <Title title="检查方填写" />
          <u-form-item label="检查人" prop="checkUserName" :required="opt.isAdd">
            <u-cell-group :border="false">
              <u-cell
                :title="formData.checkUserName"
                isLink
                :label="formData.checkUserName ? '' : '请选择检查人'"
                @click="handlePicker(1)"
                :disabled="!opt.isAdd"
              ></u-cell>
            </u-cell-group>
          </u-form-item>
          <u-form-item label="发现日期" prop="findTime" :required="opt.isAdd">
            <u-cell-group :border="false">
              <u-cell
                :title="formData.findTime"
                isLink
                :label="formData.findTime ? '' : '请选择发现日期'"
                @click="handlePicker2(1)"
                :disabled="!opt.isAdd"
              ></u-cell>
            </u-cell-group>
          </u-form-item>
          <u-form-item label="隐患工程" prop="proName" :required="opt.isAdd">
            <u-cell-group :border="false">
              <u-cell
                :title="formData.proName"
                isLink
                :label="formData.proName ? '' : '请选择隐患工程'"
                @click="handlePicker(2)"
                :disabled="!opt.isAdd"
              ></u-cell>
            </u-cell-group>
          </u-form-item>
          <u-form-item label="整改责任承包商" prop="subName" :required="opt.isAdd">
            <u-cell-group :border="false">
              <u-cell
                :title="formData.subName"
                isLink
                :label="formData.subName ? '' : '请选择整改责任承包商'"
                @click="handlePicker(9)"
                :disabled="!opt.isAdd ? true : formData.proId ? false : true"
              ></u-cell>
            </u-cell-group>
          </u-form-item>
          <u-form-item label="隐患问题类别" prop="pitfallTypeName" :required="opt.isAdd">
            <u-cell-group :border="false">
              <u-cell
                :title="formData.pitfallTypeName"
                isLink
                :label="formData.pitfallTypeName ? '' : '请选择隐患问题类别'"
                @click="handlePicker(3)"
                :disabled="!opt.isAdd"
              ></u-cell>
            </u-cell-group>
          </u-form-item>
          <u-form-item label="隐患问题级别" prop="pitfallLevelName" :required="opt.isAdd">
            <u-cell-group :border="false">
              <u-cell
                :title="formData.pitfallLevelName"
                isLink
                :label="formData.pitfallLevelName ? '' : '请选择隐患问题级别'"
                @click="handlePicker(4)"
                :disabled="!opt.isAdd"
              ></u-cell>
            </u-cell-group>
          </u-form-item>
          <u-form-item label="期限整改时间" prop="correctionTime" :required="opt.isAdd">
            <u-cell-group :border="false">
              <u-cell
                :title="formData.correctionTime"
                isLink
                :label="formData.correctionTime ? '' : '请选择期限整改时间'"
                @click="handlePicker2(2)"
                :disabled="!opt.isAdd"
              ></u-cell>
            </u-cell-group>
          </u-form-item>
          <u-form-item label="承包商责任人" prop="subPersonName" :required="opt.isAdd">
            <u-input v-model="formData.subPersonName" placeholder="承包商责任人" border="bottom" disabled></u-input>
          </u-form-item>
          <u-form-item label="上传图片" prop="checkPhotoList">
            <uni-file-picker
              v-model="formData.checkPhotoList"
              :auto-upload="false"
              ref="files"
              limit="9"
              @select="selectImg"
              @delete="deleteImg"
              :disabled="!opt.isAdd"
              :readonly="!opt.isAdd ? true : false"
            />
          </u-form-item>
          <u-form-item label="隐患问题描述" prop="pitfallDescription" :required="opt.isAdd">
            <u-textarea
              v-model="formData.pitfallDescription"
              placeholder="请输入隐患问题描述"
              :rows="5"
              :disabled="!opt.isAdd"
              maxlength="2000"
              count
            ></u-textarea>
          </u-form-item>
          <u-form-item label="整改措施建议" prop="suggestion">
            <u-textarea
              v-model="formData.suggestion"
              placeholder="请输入整改措施建议"
              :rows="5"
              :disabled="!opt.isAdd"
              maxlength="2000"
              count
            ></u-textarea>
          </u-form-item>
          <!-- 整改方填写 -->
          <Title title="整改方填写" />
          <u-form-item label="责任人" prop="dutyUserName">
            <u-input v-model="formData.dutyUserName" placeholder="责任人" border="bottom" disabled></u-input>
          </u-form-item>
          <u-form-item label="产生原因描述" prop="generateReason">
            <u-input v-model="formData.generateReason" placeholder="产生原因" border="bottom" disabled></u-input>
          </u-form-item>
          <u-form-item label="整改情况" prop="correctionStatus">
            <u-textarea
              v-model="formData.correctionStatus"
              placeholder="请输入整改情况"
              :rows="5"
              disabled
            ></u-textarea>
          </u-form-item>
          <u-form-item label="整改图片" prop="rectificationPhotoList">
            <Preview :dataList="formData.rectificationPhotoList" />
          </u-form-item>
          <u-form-item label="附件" prop="attachmentList">
            <Preview :dataList="formData.attachmentList" />
          </u-form-item>
          <!-- 验收方 -->
          <Title title="验收方" />
          <u-form-item label="验收部门" prop="deptName" :required="opt.isAdd">
            <u-cell-group :border="false">
              <u-cell
                :title="formData.deptName"
                isLink
                :label="formData.deptName ? '' : '请选择验收部门'"
                @click="handlePicker(5)"
                :disabled="!opt.isAdd"
              ></u-cell>
            </u-cell-group>
          </u-form-item>
          <u-form-item label="整改验收人" prop="userName" :required="opt.isAdd">
            <u-cell-group :border="false">
              <u-cell
                :title="formData.userName"
                isLink
                :label="formData.userName ? '' : '请选择整改验收人'"
                @click="handlePicker(6)"
                :disabled="!opt.isAdd ? true : formData.deptId ? false : true"
              ></u-cell>
            </u-cell-group>
          </u-form-item>
          <u-form-item label="是否进行流程审批" prop="isProcessLabel" :required="opt.isAdd">
            <u-cell-group :border="false">
              <u-cell
                :title="formData.isProcessLabel"
                isLink
                :label="formData.isProcessLabel ? '' : '请选择是否进行流程审批'"
                @click="handlePicker(7)"
                :disabled="!opt.isAdd"
              ></u-cell>
            </u-cell-group>
          </u-form-item>
          <u-form-item label="整改意见" prop="opinion" :required="opt.isReceive">
            <u-textarea
              v-model="formData.opinion"
              placeholder="请输入整改意见"
              :rows="5"
              :disabled="!opt.isReceive"
              maxlength="2000"
              count
            ></u-textarea>
          </u-form-item>
          <u-form-item label="备注" prop="remarks">
            <u-textarea
              v-model="formData.remarks"
              placeholder="请输入备注"
              :rows="5"
              :disabled="!opt.isReceive"
              maxlength="2000"
              count
            ></u-textarea>
          </u-form-item>
          <!-- 延期信息 -->
          <Title title="延期信息" />
          <u-form-item label="延期整改时间" prop="delayTime">
            <u-input v-model="formData.delayTime" placeholder="请选择延期整改时间" border="bottom" disabled></u-input>
          </u-form-item>
          <u-form-item label="延期原因" prop="delayReason">
            <u-textarea v-model="formData.delayReason" placeholder="请输入延期原因" :rows="5" disabled></u-textarea>
          </u-form-item>
        </u-form>
        <div>
          <u-button v-if="opt.isAdd" type="primary" shape="circle" @click="submitForm" style="margin: 30px 0">
            下 发
          </u-button>
          <div v-if="opt.isReceive" class="btns">
            <u-button type="primary" shape="circle" @click="submitForm2(1)" style="margin: 30px 0">验收通过</u-button>
            <u-button type="error" shape="circle" @click="submitForm2(2)" style="margin: 30px 0 30px 10px">
              驳 回
            </u-button>
          </div>
          <div v-if="opt.isAcceptance" class="btns">
            <u-button type="primary" shape="circle" @click="submitFormDelay(1)" style="margin: 30px 0">
              验收通过
            </u-button>
            <u-button type="error" shape="circle" @click="submitFormDelay(2)" style="margin: 30px 0 30px 10px">
              驳 回
            </u-button>
          </div>
        </div>
      </div>
      <div v-else-if="currentTab == 1">
        <Title title="审批意见" />
        <u-textarea
          v-model="approvalOpinion"
          placeholder="请输入内容"
          count
          height="105"
          @blur="filter"
          :disabled="!opt.isApprove"
        />
        <Title title="审批记录" />
        <Steps :data="approvalRecordList" />
        <TabbarBtn
          :showBtn="opt.finalCheck != 0 ? true : false"
          @reject="appReject"
          @handlePermit="handleAppPermit"
          @handleEnd="handleAppEnd"
          v-if="opt.isApprove"
        />
      </div>
    </div>
    <u-picker
      v-if="showPicker"
      :show="showPicker"
      :columns="columns"
      keyName="label"
      @cancel="showPicker = false"
      @confirm="confirm"
    ></u-picker>
    <ba-tree-picker
      ref="treePicker"
      :multiple="false"
      @select-change="changeDept"
      title="选择部门"
      :localdata="deptOpts"
      valueKey="id"
      textKey="label"
      childrenKey="children"
    />
    <!-- 日期 -->
    <u-datetime-picker
      :show="showPicker2"
      v-model="dataTime"
      :minDate="minDate"
      :maxDate="maxDate"
      mode="date"
      @cancel="showPicker2 = false"
      @confirm="confirm2"
    ></u-datetime-picker>

    <!-- 延期驳回弹框 -->
    <u-modal :show="delayReason" title="驳回原因" showCancelButton @close="delayReason = false" @confirm="submitDelayReason">
      <view class="slot-content" style="width: 100%">
        <div class="delay">
          <u-textarea
            v-model="rejectionDelay"
            placeholder="请输入驳回原因"
            :rows="5"
            maxlength="200"
            count
          ></u-textarea>
        </div>
      </view>
    </u-modal>
    <u-loading-page :loading="isLoading" icon-size="39" style="z-index: 99999"></u-loading-page>
  </view>
</template>

<script>
import { dictTableOption } from '@/api/tool/select'
import {
  getOwnerSelect,
  getProSelect,
  getTypeOfViolationSelect,
  getConsByProIdSelect,
  deptTreeSelect,
  getDeptUserSelect,
  addHiddenDangerRectification,
  uploadFileUrl,
  getHiddenDangerRectificationForm,
  updateHiddenDangerRectification,
  updateSuggestionsForRectification,
  submitApproval,
  submitPersonApproval,
  approvalHistory,
  updateDeferredAcceptancePassed, // 延期验收通过
  updateReasonForDelay // 延期驳回
} from '@/api/hiddenDangerViolation'
import { encryptCBC, decryptCBC } from '@/utils/aescbc'
import config from '@/config'
import { filterInput } from '@/utils/regular'
import Steps from 'pages/component/Steps'
import TabbarBtn from 'pages/projectApproval/component/TabbarBtn'
import baTreePicker from '@/components/ba-tree-picker/ba-tree-picker'

export default {
  components: { Steps, TabbarBtn, baTreePicker },
  data() {
    return {
      delayReason: false,
      rejectionDelay: '',
      token: '',
      isLoading: false,
      actionUrl: uploadFileUrl,
      currentPicker: 1, // 1-检查人, 2-隐患工程, 3-隐患问题类别, 4-隐患问题级别, 5-整改验收部门, 6-整改验收人, 7-是否进行流程审批, 8-排查类型
      showPicker: false,
      columns: [],
      currentTime: 1, // 1-发现日期, 2-期限整改时间
      showPicker2: false,
      dataTime: Number(new Date()),
      minDate: 0,
      maxDate: 0,
      opt: {},
      currentTab: 0,
      tabList: [{ name: '隐患整改单' }, { name: '审批信息' }],
      isFrom: '1', // 采集来源1日常检查2安全大检查;3随手拍
      formData: {
        // 基本信息
        pitfallCode: '', // 隐患问题编号
        recordCode: '', // 检查记录编号
        checkLevel: '', // 对应检查级别id
        checkLevelName: '', // 对应检查级别
        checkType: '', // 排查类型
        checkTypeName: '', // 排查类型
        createUserName: uni.getStorageSync('userInfo').nickName, // 创建人
        createTime: '', // 创建时间
        rectificationReceiveTime: '', // 整改接收时间
        rectificationFeedbackTime: '', // 整改反馈时间
        checkStatus: '', // 整改状态
        // 检查方填写
        checkUserId: '', // 检查人id
        checkUserName: '', // 检查人
        findTime: '', // 发现日期
        proId: '', // 隐患工程id
        proName: '', // 隐患工程
        subId: '', // 整改责任承包商id
        subName: '', // 整改责任承包商
        pitfallTypeId: '', // 隐患问题类别id
        pitfallTypeName: '', // 隐患问题类别
        pitfallLevelId: '', // 隐患问题级别id
        pitfallLevelName: '', // 隐患问题级别
        correctionTime: '', // 期限整改时间
        subPersonId: '', // 承包商责任人id
        subPersonName: '', // 承包商责任人
        supUuid: '', // uuid
        checkPhotoList: [], // 图片列表
        handlePhotoList: [], // 处理后图片
        pitfallDescription: '', // 隐患问题描述
        suggestion: '', // 整改措施建议
        dutyUserId: '', // 责任人id
        dutyUserName: '', // 责任人
        generateReason: '', // 产生原因
        correctionStatus: '', // 整改情况
        rectificationPhotoList: [], // 图片列表
        attachmentList: [], // 文件列表
        // 验收方
        deptId: undefined, // 验收部门id
        deptName: '', // 验收部门
        userId: '', // 验收人id
        userName: '', // 验收人
        isProcess: '', // 是否进行流程审批
        isProcessLabel: '', // 是否进行流程审批
        opinion: '', // 整改意见
        remarks: '', // 备注
        // 延期信息
        delayTime: '', // 延期整改时间
        delayReason: '' // 延期原因
      },
      approvalOpinion: '', // 审批意见
      approvalRecordList: [], // 审批记录
      // 排查类型-下拉
      checkTypeOpts: [],
      // 检查人-下拉
      checkUserOpts: [],
      // 隐患工程-下拉
      proOpts: [],
      // 整改责任承包商-下拉
      subOpts: [],
      // 隐患问题类别-下拉
      pitfallTypeOpts: [],
      // 隐患问题级别-下拉
      pitfallLevelOpts: [],
      // 整改验收部门-下拉
      deptOpts: [],
      // 整改验收人-下拉
      userOpts: [],
      // 是否进行流程审批-下拉
      isProcessOpts: [
        { label: '是', value: '1' },
        { label: '否', value: '0' }
      ],
      rules: [],
      // 校验基础信息,检查方填写,验收方
      rules1: {
        checkTypeName: [{ required: true, message: '请选择排查类型', trigger: 'blur' }],
        checkUserName: [{ required: true, message: '请选择检查人', trigger: 'blur' }],
        findTime: [{ required: true, message: '请选择发现日期', trigger: 'blur' }],
        proName: [{ required: true, message: '请选择隐患工程', trigger: 'blur' }],
        pitfallTypeName: [{ required: true, message: '请选择隐患问题类别', trigger: 'blur' }],
        pitfallLevelName: [{ required: true, message: '请选择隐患问题级别', trigger: 'blur' }],
        correctionTime: [{ required: true, message: '请选择期限整改时间', trigger: 'blur' }],
        pitfallDescription: [{ required: true, message: '请输入隐患问题描述', trigger: 'blur' }],
        deptName: [{ required: true, message: '请选择验收部门', trigger: 'blur' }],
        userName: [{ required: true, message: '请选择整改验收人', trigger: 'blur' }],
        isProcessLabel: [{ required: true, message: '请选择是否进行流程审批', trigger: 'blur' }],
        subName: [{ required: true, message: '请选择整改责任承包商', trigger: 'blur' }],
        subPersonName: [{ required: true, message: '请输入承包商责任人', trigger: 'blur' }]
      },
      // 验收
      rules2: {
        opinion: [{ required: true, message: '请输入整改意见', trigger: 'blur' }]
      }
    }
  },
  // 监听 this.formData.proId 的变化,获取整改责任承包商-下拉
  watch: {
    'formData.proId': {
      handler: function (val) {
        console.log('🚀 ~ 监听 val:', val)
        // 清除整改责任承包商与承包商责任人
        this.formData.subId = ''
        this.formData.subName = ''
        this.formData.subPersonName = ''
        this.getConsByProIdSelect(val)
      },
      immediate: false
    }
  },
  onLoad(opt) {
    this.token = uni.getStorageSync('App-Token')
    this.opt = JSON.parse(opt.params)
    this.currentTab = this.opt.isRecord ? 1 : 0
    this.formData.recordCode = this.opt.recordCode || ''
    this.formData.checkLevel = this.opt.inspectLevel || ''
    this.formData.checkLevelName = this.opt.inspectLevelName || ''
    this.formData.checkType = this.opt.checkType || ''
    this.formData.checkTypeName = this.opt.checkTypeName || ''
    this.formData.rectificationReceiveTime = this.opt.rectificationReceiveTime || this.getTodayDate()
    this.isFrom = this.opt.id ? '2' : '1'
    if (this.opt.isAdd) {
      this.rules = this.rules1
    } else if (this.opt.isReceive) {
      this.rules = this.rules2
    } else {
      this.rules = []
    }
    console.log('🚀 ~ onLoad ~ this.rules:', this.rules)
    console.log('🚀 ~ onLoad ~ this.opt', this.opt)
    this.getCheckLevelType()
    this.getOwnerSelect()
    this.getProSelect()
    this.getTroubleType()
    this.getTroubleLevel()
    this.getDeptTreeSelect()
    this.getApprovalHistory()
    if (!this.opt.isAdd) {
      this.getDetail()
    }
  },
  methods: {
    // 获取审批记录
    async getApprovalHistory() {
      try {
        const params = { taskId: this.opt.taskId, checkType: this.opt.isRecord ? 2 : 1 }
        console.log('🚀 ~ 审批记录 ~ params:', params)
        const res = await approvalHistory(params)
        console.log('🚀 ~ 审批记录 ~ res:', res)
        this.approvalRecordList = res.data
      } catch (error) {
        console.log('获取审批记录失败', error)
      }
    },
    // 查看详情
    async getDetail() {
      try {
        const params = { id: this.opt.id }
        const res = await getHiddenDangerRectificationForm(params)
        console.log('🚀 ~ getDetail ~ res:', res)
        this.formData = { ...res.data }
        this.formData.isProcessLabel = this.formData.isProcess == '1' ? '是' : '否'
        this.formData.checkPhotoList.forEach(item => {
          item.filePath = config.fileUrl + item.filePath
          item.url = item.filePath
        })
        this.formData.rectificationPhotoList.forEach(item => {
          item.url = item.filePath
        })
        this.formData.attachmentList.forEach(item => {
          item.url = item.filePath
        })
        this.$nextTick(() => {
          this.formData.subId = res.data.subId
          this.formData.subName = res.data.subName
          this.formData.subPersonId = res.data.subPersonId
          this.formData.subPersonName = res.data.subPersonName
        })
      } catch (error) {
        console.log('获取详情失败', error)
      }
    },
    getTodayDate() {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    // 检查人-下拉
    async getOwnerSelect() {
      try {
        const res = await getOwnerSelect()
        this.checkUserOpts = res.data
      } catch (error) {
        console.log('获取检查人-下拉失败', error)
      }
    },
    // 隐患工程-下拉
    async getProSelect() {
      try {
        const res = await getProSelect()
        console.log('🚀 ~ 工程下拉 ~ res:', res)
        this.proOpts = res.data
      } catch (error) {
        console.log('获取隐患工程-下拉失败', error)
      }
    },
    // 隐患问题类别-下拉
    async getTroubleType() {
      try {
        const res = await getTypeOfViolationSelect({ type: '1' })
        this.pitfallTypeOpts = res.data
      } catch (error) {
        console.log('获取隐患问题类别-下拉失败', error)
      }
    },
    // 隐患问题级别-yn_trouble_level
    async getTroubleLevel() {
      try {
        const params = {
          dictType: 'yn_trouble_level',
          dictValue: ''
        }
        const res = await dictTableOption(params)
        this.pitfallLevelOpts = res.data
      } catch (error) {
        console.log('获取隐患问题级别-下拉失败', error)
      }
    },
    // 获取整改责任承包商-下拉
    async getConsByProIdSelect(val) {
      try {
        // 清除 承包商责任人
        this.formData.subPersonName = ''
        const params = {
          proId: val
        }
        const res = await getConsByProIdSelect(params)
        console.log('🚀 ~ getConsByProIdSelect ~ res:', res)
        this.subOpts = res.data
      } catch (error) {
        console.log('获取整改责任承包商-下拉失败', error)
      }
    },
    // 整改验收部门-树形下拉
    async getDeptTreeSelect() {
      try {
        const res = await deptTreeSelect()
        this.deptOpts = res.data
        console.log('🚀 ~ 树 ~ deptOpts:', this.deptOpts)
      } catch (error) {
        console.log('获取整改验收部门-树形下拉失败', error)
      }
    },
    // 整改接收人-下拉
    async getDeptUserSelect(val) {
      try {
        this.formData.userId = ''
        this.formData.userName = ''
        this.userOpts = []
        const params = {
          deptId: val
        }
        const res = await getDeptUserSelect(params)
        this.userOpts = res.data
      } catch (error) {
        console.log('获取整改接收人-下拉失败', error)
      }
    },
    handleTab(item) {
      console.log('🚀 ~ handleTab ~ item', item)
      this.currentTab = item.index
    },
    // 过滤输入特殊字符
    filter() {
      this.approvalOpinion = filterInput(this.approvalOpinion)
    },
    async getCheckLevelType() {
      try {
        const params = {
          dictType: 'yh_inspect_level',
          dictValue: ''
        }
        const params2 = {
          dictType: 'yh_check_type',
          dictValue: ''
        }
        const res2 = await dictTableOption(params2)
        console.log('🚀 ~ 排查类型 ~ res2:', res2)
        this.checkTypeOpts = res2.data
      } catch (error) {
        console.log('获取检查级别-下拉失败', error)
      }
    },
    changeDept(ids, label) {
      console.log('🚀 ~ changeDept ~ 树:', ids, label)
      this.formData.deptId = ids[0]
      this.formData.deptName = label
      console.log('🚀 ~ changeDept ~ this.formData:', this.formData)
      this.getDeptUserSelect(ids[0])
    },
    handlePicker(type) {
      this.columns = []
      this.currentPicker = type
      if (type === 1) {
        this.columns = [this.checkUserOpts]
      } else if (type === 2) {
        this.columns = [this.proOpts]
      } else if (type === 3) {
        this.columns = [this.pitfallTypeOpts]
      } else if (type === 4) {
        this.columns = [this.pitfallLevelOpts]
      } else if (type === 5) {
        this.$refs.treePicker._show()
      } else if (type === 6) {
        this.columns = [this.userOpts]
      } else if (type === 7) {
        this.columns = [this.isProcessOpts]
      } else if (type === 8) {
        this.columns = [this.checkTypeOpts]
      } else if (type === 9) {
        this.columns = [this.subOpts]
      }
      setTimeout(() => {
        if (type === 5) return
        this.showPicker = true
      }, 200)
    },
    confirm(e) {
      console.log('🚀 ~ 当前下拉', this.currentPicker)
      console.log('🚀 ~ confirm ~ e', e)
      if (this.currentPicker === 1) {
        // 检查人
        this.formData.checkUserId = e.value[0].value
        this.formData.checkUserName = e.value[0].label
      } else if (this.currentPicker === 2) {
        // 隐患工程
        this.formData.proId = e.value[0].value
        this.formData.proName = e.value[0].label
      } else if (this.currentPicker === 3) {
        // 隐患问题类别
        this.formData.pitfallTypeId = e.value[0].value
        this.formData.pitfallTypeName = e.value[0].label
      } else if (this.currentPicker === 4) {
        // 隐患问题级别
        this.formData.pitfallLevelId = e.value[0].value
        this.formData.pitfallLevelName = e.value[0].label
      } else if (this.currentPicker === 6) {
        // 整改验收人
        this.formData.userId = e.value[0].value
        this.formData.userName = e.value[0].label
      } else if (this.currentPicker === 7) {
        // 是否进行流程审批
        this.formData.isProcess = e.value[0].value
        this.formData.isProcessLabel = e.value[0].label
      } else if (this.currentPicker === 8) {
        // 排查类型
        this.formData.checkType = e.value[0].value
        this.formData.checkTypeName = e.value[0].label
      } else if (this.currentPicker === 9) {
        // 整改责任承包商
        this.formData.subId = e.value[0].valueUuid
        this.formData.subName = e.value[0].label
        this.formData.subPersonId = e.value[0].userId
        this.formData.subPersonName = e.value[0].name
        this.formData.supUuid = e.value[0].supUuid
      }
      this.showPicker = false
    },
    handlePicker2(type) {
      this.currentTime = type
      // 获取今天的日期
      let today = new Date()
      if (this.currentTime === 1) {
        // minDate 今天往前10年, maxDate 为今天
        // 获取10年前的日期
        let tenYearsAgo = new Date()
        tenYearsAgo.setFullYear(today.getFullYear() - 10)
        // 获取今天和10年前日期的时间戳
        this.maxDate = today.getTime() // 当前时间戳
        this.minDate = tenYearsAgo.getTime() // 10年前的时间戳
      } else if (this.currentTime === 2) {
        // minDate 今天包括今天 maxDate 为今天往后10年
        // 获取10年后的日期
        let tenYearsLater = new Date()
        tenYearsLater.setFullYear(today.getFullYear() + 10)
        // 获取今天和10年后日期的时间戳
        this.maxDate = tenYearsLater.getTime() // 10年后的时间戳
        this.minDate = today.getTime() // 当前时间戳
      }
      this.showPicker2 = true
    },
    confirm2(e) {
      console.log('🚀 ~ confirm3 ~ e:', e)
      // this.formData.checkTime = this.formatTimestamp(e.value)
      if (this.currentTime === 1) {
        // minDate 今天往前10年, maxDate 为今天
        // 获取今天的日期
        let today = new Date()

        // 获取10年前的日期
        let tenYearsAgo = new Date()
        tenYearsAgo.setFullYear(today.getFullYear() - 10)

        // 获取今天和10年前日期的时间戳
        this.maxDate = today.getTime() // 当前时间戳
        this.minDate = tenYearsAgo.getTime() // 10年前的时间戳
        this.formData.findTime = this.formatTimestamp(e.value)
      } else if (this.currentTime === 2) {
        this.formData.correctionTime = this.formatTimestamp(e.value)
      }
      setTimeout(() => {
        this.showPicker2 = false
      }, 200)
    },
    // 将时间戳转换为日期格式 yyyy-MM-dd
    formatTimestamp(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    selectImg(e) {
      console.log('🚀 ~ selectImg ~ e:', e)
      e.tempFiles.forEach(item => {
        this.formData.checkPhotoList.push(item)
      })
    },
    upload(path) {
      uni.uploadFile({
        url: this.actionUrl,
        filePath: path,
        name: 'photoType',
        header: {
          Authorization: this.token,
          tokenType: 'APP'
        },
        success: res => {
          console.log('🚀 ~ selectImg ~ res:', res)
          console.log('🚀 ~ selectImg ~ res--data:', decryptCBC(JSON.parse(res.data).data))
          this.formData.handlePhotoList.push(JSON.parse(res.data).data[0])
          console.log('🚀 ~ upload ~ this.handlePhotoList:', this.formData.handlePhotoList)
        },
        fail: err => {
          console.log('🚀 ~ selectImg ~ err:', err)
        }
      })
    },
    deleteImg(e) {
      console.log('🚀 ~ deleteImg ~ e:', e)
      this.formData.checkPhotoList.splice(e.index, 1)
      console.log('🚀 ~ deleteImg ~ this.formData.checkPhotoList:', this.formData.checkPhotoList)
    },
    // 下发
    async submitForm() {
      console.log('🚀 ~ submitForm ~ 点击:')
      // 校验
      this.$refs.uForm
        .validate()
        .then(valid => {
          this.isLoading = true
          this.formData.handlePhotoList = []
          console.log('校验成功')
          const uploadPromises = this.formData.checkPhotoList.map(item => {
            console.log('🚀 ~ uploadPromises ~ item:', item)
            if (item.uuid) {
              return this.upload(item.path)
            }
            return Promise.resolve()
          })

          Promise.all(uploadPromises)
            .then(() => {
              // 所有上传操作完成后再提交
              setTimeout(async () => {
                try {
                  console.log('🚀 ~ submitForm ~ 提交:', this.formData)
                  this.formData.checkPhotoList = this.formData.handlePhotoList
                  const params = { ...this.formData, isFrom: this.isFrom }
                  console.log('🚀 ~ 提交 ~ this.params:', params)
                  const res = await addHiddenDangerRectification(params)
                  console.log('🚀 ~ setTimeout ~ res:', res)
                  uni.showToast({
                    title: '下发成功',
                    icon: 'success',
                    duration: 1500
                  })
                  setTimeout(() => {
                    this.isLoading = false
                    uni.navigateBack()
                  }, 1500)
                } catch (error) {
                  console.log('🚀 ~ submitForm ~ error:', error)
                  this.isLoading = false
                }
              }, 800)
            })
            .catch(error => {
              // 处理上传失败的情况
              console.error('上传失败', error)
              this.isLoading = false
            })
        })
        .catch(err => {
          console.log('校验失败')
          this.isLoading = false
        })
    },
    // 验收/驳回
    async submitForm2(type) {
      console.log('🚀 ~ submitForm ~ 点击:')
      // 校验
      this.$refs.uForm
        .validate()
        .then(async valid => {
          console.log('校验成功')
          try {
            const params = {
              ...this.formData,
              id: this.opt.id,
              isProcess: this.formData.isProcess,
              opinion: this.formData.opinion,
              remarks: this.formData.remarks
            }
            console.log('🚀 ~ 提交 ~ this.params:', params)
            let res = {}
            if (type === 1) {
              this.isLoading = true
              // 验收通过
              res = await updateHiddenDangerRectification(params)
              if (Number(this.formData.isProcess) == 1) {
                // 有流程审批
                this.submitApply(2)
              } else {
                uni.showToast({
                  title: '操作成功',
                  icon: 'success',
                  duration: 1500
                })
                setTimeout(() => {
                  this.isLoading = false
                  uni.navigateBack()
                }, 1500)
              }
            } else if (type === 2) {
              // 弹框确认
              uni.showModal({
                title: '提示',
                content: '是否确认驳回？',
                showCancel: true,
                success: async res => {
                  if (res.confirm) {
                    console.log('用户点击确定')
                    this.isLoading = true
                    // 驳回
                    res = await updateSuggestionsForRectification(params)
                    uni.showToast({
                      title: '操作成功',
                      icon: 'success',
                      duration: 1500
                    })
                    setTimeout(() => {
                      this.isLoading = false
                      uni.navigateBack()
                    }, 1500)
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })
            }
            console.log('🚀 ~ 提交结果 ~ res:', res)
          } catch (error) {
            console.log('🚀 ~ submitForm ~ error:', error)
            this.isLoading = false
          }
        })
        .catch(err => {
          console.log('校验失败')
        })
    },
    async submitFormDelay(type) {
      console.log('🚀 ~ submitFormDelay ~ type:', type)
      try {
        const params = {
          id: this.opt.id
        }
        console.log('🚀 ~ 提交 ~ this.params:', params)
        let res = {}
        if (type === 1) {
          this.isLoading = true
          // 验收通过
          res = await updateDeferredAcceptancePassed(params)
          if (Number(this.formData.isProcess) == 1) {
            // 有流程审批
            this.submitApply(1)
          } else {
            uni.showToast({
              title: '操作成功',
              icon: 'success',
              duration: 1500
            })
          }
          setTimeout(() => {
            this.isLoading = false
            uni.navigateBack()
          }, 1500)
        } else if (type === 2) {
          // 弹框输入驳回原因
          this.delayReason = true
          this.rejectionDelay = ''
        }
        console.log('🚀 ~ 提交结果 ~ res:', res)
      } catch (error) {
        console.log('🚀 ~ submitForm ~ error:', error)
        this.isLoading = false
      }
    },
    async submitDelayReason() {
      try {
        if (!this.rejectionDelay) {
          uni.showToast({
            title: '请输入驳回原因',
            icon: 'none',
            duration: 1500
          })
          return
        }
        this.isLoading = true
        const params = {
          id: this.opt.id,
          rejectionDelay: this.rejectionDelay
        }
        console.log('🚀 ~ 延期-驳回 ~ .params:', params)
        const res = await updateReasonForDelay(params)
        console.log('🚀 ~ 延期-驳回 ~ res:', res)
        uni.showToast({
          title: '操作成功',
          icon: 'success',
          duration: 1500
        })
        setTimeout(() => {
          this.isLoading = false
          uni.navigateBack()
        }, 1000)
      } catch (error) {
        console.log('🚀 ~ submitDelayReason ~ error:', error)
      }
    },
    submitApply(type) {
      let taskType
      let param
      let code = '验收通过'
      if (type === 2) {
        if (Number(this.formData.pitfallLevelId) === 1) {
          taskType = 14
        } else if (Number(this.formData.pitfallLevelId) === 2) {
          taskType = 15
        } else if (Number(this.formData.pitfallLevelId) === 3) {
          taskType = 16
        }
        param = {
          proId: this.opt.proId,
          taskType: taskType,
          userType: '01',
          taskId: this.opt.taskId,
          uuid: this.opt.id
        }
      } else {
        param = {
          proId: this.opt.proId,
          taskType: '17',
          userType: '01',
          taskId: this.opt.taskId,
          uuid: this.opt.id
        }
        code = '延期申请成功'
      }
      console.log('param=' + JSON.stringify(param))
      submitApproval(param).then(response => {
        if (response.code === 200) {
          if (response.msg === '此审核类型未配置相对应的审核流，请联系管理员配置后再次提交') {
            uni.showToast({
              title: response.msg,
              icon: 'none',
              duration: 1500
            })
          } else {
            uni.showToast({
              title: code + '，进入审核流程！',
              icon: 'none',
              duration: 1500
            })
          }
          setTimeout(() => {
            this.isLoading = false
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: (type === 1 ? '验收' : '延期申请') + '失败，请联系管理员查询具体情况，再次进行验收操作！',
            icon: 'none',
            duration: 1500
          })
          this.isLoading = false
        }
      })
    },
    // 审批驳回
    appReject(val) {
      // rejectReason-驳回原因
      console.log('审批驳回原因:', val)
      const params = {
        reason: this.approvalOpinion,
        rejectReason: val,
        agree: '2'
      }
      this.approval(params, '审批驳回')
    },
    // 审批通过 reason-审批意见
    handleAppPermit() {
      console.log('审批通过')
      const params = {
        reason: this.approvalOpinion,
        agree: '1'
      }
      this.approval(params, '审批通过')
    },
    // 终审
    handleAppEnd() {
      console.log('终审')
      const params = {
        reason: this.approvalOpinion,
        agree: '3'
      }
      this.approval(params, '审批通过')
    },
    async approval(param, text) {
      try {
        this.isLoading = true
        const params = {
          ...param,
          proId: this.opt.proId,
          taskId: this.opt.taskId,
          procInstId: this.opt.procInsId,
          taskType: this.opt.checkLevelId == '1' ? 14 : this.opt.checkLevelId == '2' ? 15 : 16,
          uuid: this.opt.id
        }
        console.log('🚀 ~ 审批 ~ params:', params)
        const res = await submitPersonApproval(params)
        console.log('🚀 ~ 审批 ~ res:', res)
        uni.showToast({
          title: text,
          icon: 'success',
          duration: 1500
        })
        setTimeout(() => {
          this.isLoading = false
          uni.navigateBack()
        }, 200)
      } catch (error) {
        this.isLoading = false
        console.log('🚀 ~ 审批 ~ error:', error)
      }
    }
  }
}
</script>

<style lang="scss">
.content {
  padding: 20px;
  .btns {
    display: flex;
    justify-content: space-between;
  }
}
</style>
