<template>
  <view class="content">
    <view class="card">
      <u-cell-group :border="false">
        <u-cell>
          <view slot="title" class="title required">检查题目：</view>
          <view slot="value">
            <u-radio-group v-model="form.INSPECTION_SUBJECT" placement="row" :disabled="disabled">
              <u-radio label="安全" name="安全"></u-radio>
              <u-radio label="环保" name="环保" class="ml-10"></u-radio>
              <u-radio label="综合" name="综合" class="ml-10"></u-radio>
            </u-radio-group>
          </view>
        </u-cell>
        <u-cell>
          <view slot="title" class="title required">被检查单位：</view>
          <view slot="value">
            <text @click="showTree('tkitree')">
              {{ disabled ? form.INSPECTED_CORPINFO_ID_NAME : form.INSPECTED_DEPARTMENT_NAME || '请选择' }}
            </text>
            <tki-tree ref="tkitree" :range="inspectedDepartmentTreeList" rangeKey="name" selectParent
                      @confirm="confirmTree($event,'inspectedSiteuserColumns')"/>
          </view>
        </u-cell>
        <u-cell v-show="form.INSPECTED_DEPARTMENT_NAME">
          <view slot="title" class="title required">被检查单位现场负责人：</view>
          <view slot="value">
            <text @click="disabled ? null : inspectedSiteuserShow = true">{{
                form.INSPECTED_SITEUSER_NAME || '请选择'
              }}
            </text>
            <u-picker :show="inspectedSiteuserShow" :columns="inspectedSiteuserColumns" keyName="NAME"
                      @cancel="inspectedSiteuserShow = false"
                      @confirm="inspectedSiteuserConfirmPicker"></u-picker>
          </view>
        </u-cell>
        <u-cell>
          <view slot="title" class="title required">检查场所：</view>
          <view slot="value">
            <u--input v-model="form.INSPECTION_PLACE" border="none" placeholder="请输入检查场所" inputAlign="right"
                      :disabled="disabled"></u--input>
          </view>
        </u-cell>
        <u-cell>
          <view slot="title" class="title required">检查类型：</view>
          <view slot="value">
            <text @click="showTree('tkitree1')">{{ form.INSPECTION_TYPE_NAME || '请选择' }}</text>
            <tki-tree ref="tkitree1" :range="inspectionTypeTreeList" rangeKey="name" selectParent children-name="nodes"
                      @confirm="confirmTree($event,'inspectionTypeTreeList')"/>
          </view>
        </u-cell>
        <u-cell>
          <view slot="title" class="title required">检查开始时间：</view>
          <view slot="value">
            <text @click="disabled ? null : inspectionTimeStartShow = true">{{
                form.INSPECTION_TIME_START || '请选择'
              }}
            </text>
            <u-datetime-picker :show="inspectionTimeStartShow" :value="form.INSPECTION_TIME_START"
                               @cancel="inspectionTimeStartShow = false"
                               @confirm="inspectionTimeStartConfirm"></u-datetime-picker>
          </view>
        </u-cell>
        <u-cell>
          <view slot="title" class="title required">检查结束时间：</view>
          <view slot="value">
            <text @click="disabled ? null : inspectionTimeEndShow = true">{{
                form.INSPECTION_TIME_END || '请选择'
              }}
            </text>
            <u-datetime-picker :show="inspectionTimeEndShow" :value="form.INSPECTION_TIME_END"
                               @cancel="inspectionTimeEndShow = false"
                               @confirm="inspectionTimeEndConfirm"></u-datetime-picker>
          </view>
        </u-cell>
        <u-cell v-if="disabled">
          <view slot="title" class="title required">记录填写时间：</view>
          <view slot="value">
            <text>{{ form.CREATTIME }}</text>
          </view>
        </u-cell>
        <u-cell>
          <view slot="title" class="title">检查情况：</view>
          <view slot="value">
            <u-button type="primary" text="添加" size="mini" @click="addSituation"
                      v-if="!disabled"></u-button>
          </view>
        </u-cell>
        <u-cell>
          <view slot="label">
            <view class="pr mt-10 textarea-box" v-for="(item,index) in form.situationList" :key="item.id">
              <u--textarea v-model="item.SITUATION" placeholder="请输入检查情况" :disabled="disabled"></u--textarea>
              <!-- 检查情况图片上传 -->
              <view class="mt-10">
                <view class="title mb-10">图片：</view>
                <u-upload
                    :fileList="item.IMAGE"
                    @afterRead="handleSituationImageUpload($event, index)"
                    @delete="handleSituationImageDelete($event, index)"
                    :disabled="disabled"
                    :deletable="!disabled"
                    multiple
                    :maxCount="1">
                </u-upload>
              </view>
              <u-badge value="X" type="error" :offset="[-9,-10]" absolute
                       @click.native="removeSituation(item,index)" v-if="!disabled"></u-badge>
            </view>
          </view>
        </u-cell>
        <u-cell>
          <view slot="title" class="title">检查人员：</view>
          <view slot="value">
            <u-button type="primary" text="添加" size="mini" @click="addInspector"
                      v-if="!disabled"></u-button>
          </view>
        </u-cell>
        <view class="title-none">
          <u-cell>
            <view slot="value" style="width: 100%">
              <view class="pr mt-10" v-for="(item,index) in form.inspectorList" :key="item.id">
                <u-cell-group :border="false" class="border">
                  <view class="title-show">
                    <u-cell>
                      <view slot="title">{{ index + 1 }}.检查人员单位</view>
                      <view slot="value">
                        <text @click="showTree('tkitreeInspector' + index,'arr')">
                          {{ item.INSPECTION_DEPARTMENT_NAME || '请选择' }}
                        </text>
                        <tki-tree :ref="'tkitreeInspector' + index" :range="inspectedDepartmentTreeList"
                                  rangeKey="name"
                                  selectParent @confirm="confirmTree($event,'inspectorList',index)"/>
                      </view>
                    </u-cell>
                  </view>
                  <view class="title-show">
                    <u-cell :border="false" v-show="item.INSPECTION_DEPARTMENT_NAME">
                      <view slot="title">{{ index + 1 }}.检查人员</view>
                      <view slot="value">
                        <text @click="inspectionUserShowPicker(index)">{{
                            item.INSPECTION_USER_NAME || '请选择'
                          }}
                        </text>
                        <u-picker :show="item.inspectionUserShow" :columns="[inspectorList[0][index]]" keyName="NAME"
                                  @cancel="item.inspectionUserShow = false"
                                  @confirm="inspectionUserConfirmPicker($event,index)"></u-picker>
                      </view>
                    </u-cell>
                  </view>
                </u-cell-group>
                <u-badge value="X" type="error" :offset="[-9,-10]" absolute
                         @click.native="removeInspector(item,index)" v-if="!disabled"></u-badge>
              </view>
            </view>
          </u-cell>
        </view>
        <u-cell>
          <view slot="title" class="title">发现问题：</view>
          <view slot="value">
            <u-button type="primary" text="添加" size="mini" @click="addHidden"
                      v-if="!disabled"></u-button>
          </view>
        </u-cell>
        <view class="title-none">
          <u-cell>
            <view slot="value" style="flex: 1">
              <uni-table border stripe emptyText="暂无更多数据">
                <uni-tr>
                  <uni-th align="center">序号</uni-th>
                  <uni-th align="center">隐患部位</uni-th>
                  <uni-th align="center">隐患描述</uni-th>
                  <uni-th align="center">操作</uni-th>
                </uni-tr>
                <uni-tr v-for="(item,index) in form.hiddenList" :key="item.HIDDEN_ID == null ? index : item.HIDDEN_ID">
                  <uni-td>{{ index + 1 }}</uni-td>
                  <uni-td>{{ item.HIDDENPART_NAME ? item.HIDDENPART_NAME : item.HIDDENPART }}</uni-td>
                  <uni-td>{{ item.HIDDENDESCR }}</uni-td>
                  <uni-td>
                    <view class="flex-between">
                      <u-icon name="eye-fill" @tap="showHidden(item, index)"></u-icon>
                      <view class="ml-10">
                        <u-icon name="trash-fill" @tap="removeHidden(item, index)"
                                v-if="!disabled"/>
                      </view>
                    </view>
                  </uni-td>
                </uni-tr>
              </uni-table>
            </view>
          </u-cell>
        </view>
        <template v-for="item in form.inspectorVerifyList" v-if="!type||!(type==='add' || type==='edit')">
          <u-cell v-show="item.INSPECTION_USER_OPINION">
            <template #title>
              <view class="title">检查人意见：</view>
            </template>
            <template #label>
              <view class="mt-10 textarea-box">
                <u--textarea v-model="item.INSPECTION_USER_OPINION" disabled
                             placeholder="请输入检查人意见"></u--textarea>
              </view>
            </template>
          </u-cell>
          <u-cell v-show="item.INSPECTION_USER_SIGN_IMG">
            <view slot="title" class="title">签字：</view>
            <view slot="label" class="mt-10">
              <u--image :showLoading="true" :src="$store.state.filePath + item.INSPECTION_USER_SIGN_IMG"
                        width="100%" height="80px" mode="scaleToFill"
                        @click="previewImage($store.state.filePath + item.INSPECTION_USER_SIGN_IMG)"></u--image>
            </view>
          </u-cell>
        </template>
        <template v-if="!type||!(type==='add' || type==='edit')">
          <u-cell v-show="form.INSPECTED_SITEUSER_SIGN_IMG">
            <view slot="title" class="title">被检查人意见：</view>
          </u-cell>
          <u-cell v-show="form.INSPECTED_SITEUSER_SIGN_IMG">
            <view slot="title" class="title">签字：</view>
            <view slot="label" class="mt-10">
              <u--image :showLoading="true" :src="$store.state.filePath + form.INSPECTED_SITEUSER_SIGN_IMG"
                        width="100%" height="80px" mode="scaleToFill"
                        @click="previewImage($store.state.filePath + form.INSPECTED_SITEUSER_SIGN_IMG)"></u--image>
            </view>
          </u-cell>
        </template>
        <template v-if="type&&(type==='add' || type==='edit')">
          <u-cell>
            <view slot="title" class="title">检查人意见：</view>
            <view slot="label" class="mt-10 textarea-box">
              <u--textarea v-model="form.INSPECTION_USER_OPINION" placeholder="请输入检查人意见"></u--textarea>
            </view>
          </u-cell>
          <u-cell v-if="form.INSPECTION_USER_OPINION">
            <view slot="title" class="title flex-between">
              签字：
              <view>
                <u-button type="primary" text="手写添加" size="mini" @click="signShow = true"></u-button>
              </view>
            </view>
            <view slot="label" class="mt-10">
              <sign v-if="signShow" :signShow.sync="signShow" @confirm="signConfirm"></sign>
            </view>
          </u-cell>
          <u-cell v-if="form.INSPECTION_USER_SIGN_IMG">
            <view slot="value" class="mt-10 flex-1" v-show="form.INSPECTION_USER_SIGN_IMG">
              <u--image v-show="form.INSPECTION_USER_SIGN_IMG" :showLoading="true" :src="form.INSPECTION_USER_SIGN_IMG"
                        width="100%" height="80px" mode="scaleToFill"
                        @click="previewImage(form.INSPECTION_USER_SIGN_IMG)"></u--image>

            </view>
          </u-cell>
        </template>
        <u-cell :border="false">
          <view slot="label">
            <u-button type="primary" text="提交" @click="$u.debounce(fnSubmit, 1000,true)" v-if="!disabled"></u-button>
          </view>
        </u-cell>
      </u-cell-group>
    </view>
    <u-popup :key="popupShow" :show="popupShow" @close="popupShow = false" mode="right" :closeOnClickOverlay="false"
             :customStyle="{width:'85vw',overflowY:'auto'}">
      <view class="card">
        <u-cell-group :border="false">
          <u-cell>
            <view slot="title" class="title required">隐患照片：</view>
            <view slot="label" class="mt-10">
              <u-upload
                  :disabled="popupDisabled"
                  :deletable="!popupDisabled"
                  uploadIcon="plus"
                  :fileList="hiddenForm.hiddenImgs"
                  @afterRead="afterRead"
                  @delete="deletePic"
                  multiple
                  :maxCount="popupDisabled?hiddenForm.hiddenImgs.length:4"
              ></u-upload>
            </view>
          </u-cell>
          <u-cell v-if="!(popupDisabled && hiddenForm.hiddenVideos.length ===0)">
            <view slot="title" class="title flex-between">
              隐患视频：
              <u-icon v-if="hiddenForm.hiddenVideos.length !== 0 && hiddenForm.hiddenVideos[0].url"
                      name="play-circle-fill" size="30" @click="previewVideo(hiddenForm.hiddenVideos[0].url)"></u-icon>
            </view>
            <view slot="label" class="mt-10">
              <u-upload
                  :disabled="popupDisabled"
                  :deletable="!popupDisabled"
                  accept="video"
                  uploadIcon="plus"
                  :fileList="hiddenForm.hiddenVideos"
                  @afterRead="afterRead1"
                  @delete="deletePic1"
                  multiple
                  :maxCount="1"
              ></u-upload>
              <u-modal :show="modalShow" title="视频播放" confirmText="关闭" @confirm="modalShow = false">
                <view>
                  <video v-if="modalShow" :src="videoUrl" :autoplay="true"></video>
                </view>
              </u-modal>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title required">隐患描述：</view>
            <view slot="label" class="mt-10 textarea-box">
              <u--textarea v-model="hiddenForm.HIDDENDESCR" placeholder="请输入隐患描述"
                           :disabled="popupDisabled"></u--textarea>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title">隐患部位：</view>
            <view slot="value">
              <text @click="showTree('tkitree2')">
                {{ hiddenForm.HIDDENPART_NAME ? hiddenForm.HIDDENPART_NAME : hiddenForm.HIDDENPART || '请选择' }}
              </text>
              <tki-tree ref="tkitree2" :range="hiddenRegionTreeList" rangeKey="name" selectParent children-name="nodes"
                        @confirm="confirmTree($event,'hiddenRegionTreeList')"/>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title required">隐患级别：</view>
            <view slot="value">
              <text @click="showTree('tkitree3')">{{ hiddenForm.HIDDENLEVEL_NAME || '请选择' }}</text>
              <tki-tree ref="tkitree3" :range="hiddenLevelTreeList" rangeKey="name" selectParent children-name="nodes"
                        @confirm="confirmTree($event,'hiddenLevelTreeList')"/>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title required">隐患类型：</view>
            <view slot="value">
              <text @click="showTree('tkitree4')">{{ hiddenForm.HIDDENTYPE_NAME || '请选择' }}</text>
              <tki-tree ref="tkitree4" :range="hiddenTypeTreeList" rangeKey="name" children-name="nodes"
                        @confirm="confirmTree($event,'hiddenTypeTreeList')"/>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title required">是否是相关方：</view>
            <view slot="value">
              <u-radio-group v-model="hiddenForm.ISRELEVANT" placement="row" :disabled="disabled">
                <u-radio label="是" name="1" class="ml-10"></u-radio>
                <u-radio label="否" name="2" class="ml-10"></u-radio>
              </u-radio-group>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title required">隐患发现时间：</view>
            <view slot="value">
              <text @click="popupDisabled ? null : discoveryTimeShow = true">{{
                  hiddenForm.DISCOVERYTIME || '请选择'
                }}
              </text>
              <u-datetime-picker :show="discoveryTimeShow" :value="hiddenForm.DISCOVERYTIME" :minDate="Number(1970)"
                                 @cancel="discoveryTimeShow = false"
                                 @confirm="discoveryTimeConfirm"></u-datetime-picker>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title flex-between">
              隐患上报位置：
              <view>
                <u-button type="primary" text="定位" size="mini" @click="showMapModal"
                          v-if="!popupDisabled"></u-button>
              </view>
            </view>
            <view slot="label" class="mt-10" v-if="hiddenForm.LONGITUDE && hiddenForm.LATITUDE">
              <view>经度:{{ hiddenForm.LONGITUDE }}</view>
              <view>纬度:{{ hiddenForm.LATITUDE }}</view>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title">隐患位置描述：</view>
            <view slot="label" class="mt-10 textarea-box">
              <u--textarea v-model="hiddenForm.POSITIONDESC" placeholder="请输入隐患位置描述"
                           :disabled="popupDisabled"></u--textarea>
            </view>
          </u-cell>
          <u-cell>
            <view slot="title" class="title required">隐患发现人：</view>
            <view slot="value">
              <text @click="popupDisabled ? null : creatorShow = true">{{ hiddenForm.CREATOR_NAME || '请选择' }}</text>
              <u-picker :show="creatorShow" :columns="creatorList" keyName="NAME"
                        @cancel="creatorShow = false"
                        @confirm="creatorConfirmPicker"></u-picker>
            </view>
          </u-cell>
          <u-cell :border="false">
            <view slot="label" class="flex-between">
              <view class="flex1">
                <u-button type="info" text="取消" @click="popupClose"></u-button>
              </view>
              <view class="flex1 ml-10">
                <u-button type="primary" text="保存" @click="popupSave"
                          v-if="!popupDisabled"></u-button>
              </view>
            </view>
          </u-cell>
        </u-cell-group>
      </view>
    </u-popup>
  </view>
</template>

<script>
import {
  getDeptUser,
  getHiddenLevel,
  getHiddenRegion,
  getHiddenType,
  getInspectedDepartment,
  getInspectionDepartment,
  getInspectionType,
  getInspectors,
  getSafetyenvironmentalGoEdit,
  setImgFilesAdd,
  setSafetyenvironmentalAdd, setSafetyenvironmentalAdd_plus,
  setSafetyenvironmentalEdit, setSafetyenvironmentalEdit_plus,
  setVideoAdd, uploadSmd
} from "@/api";

export default {
  data() {
    return {
      form: {
        INSPECTION_SUBJECT: '',
        INSPECTED_DEPARTMENT_NAME: '',
        INSPECTED_CORPINFO_ID_NAME: '',
        INSPECTED_DEPARTMENT_ID: '',
        INSPECTED_SITEUSER_NAME: '',
        INSPECTED_SITEUSER_ID: '',
        INSPECTION_PLACE: '',
        INSPECTION_TYPE_NAME: '',
        INSPECTION_TYPE_OTHER: '',
        INSPECTION_TIME_START: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'),
        INSPECTION_TIME_END: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'),
        situationList: [{id: Math.random(), INSPECTION_SITUATION_ID: '', SITUATION: '', IMAGE: []}],
        inspectorList: [{
          id: Math.random(),
          inspectionUserShow: false,
          INSPECTION_INSPECTOR_ID: '',
          INSPECTION_DEPARTMENT_ID: '',
          INSPECTION_DEPARTMENT_NAME: '',
          INSPECTION_USER_ID: '',
          INSPECTION_USER_NAME: ''
        }],
        hiddenList: [],
        CREATTIME: '',
        INSPECTION_USER_OPINION: '',
        INSPECTION_USER_SIGN_IMG: ''
      },
      rules: {
        'INSPECTION_SUBJECT': {required: true, message: '请选择检查题目'},
        'INSPECTED_DEPARTMENT_NAME': {required: true, message: '请选择被检查单位'},
        'INSPECTED_SITEUSER_NAME': {required: true, message: '请选择被检查单位现场负责人'},
        'INSPECTION_PLACE': {required: true, message: '请输入检查场所'},
        'INSPECTION_TYPE_NAME': {required: true, message: '请选择检查类型'},
        'INSPECTION_TIME_START': {required: true, message: '请选择检查开始时间'},
        'INSPECTION_TIME_END': {required: true, message: '请选择检查结束时间'},
      },
      inspectedDepartmentTreeList: [],
      inspectionDepartmentTreeList: [],
      inspectionTypeTreeList: [],
      inspectedSiteuserShow: false,
      inspectionTimeStartShow: false,
      inspectionTimeEndShow: false,
      inspectedSiteuserColumns: [
        []
      ],
      inspectorList: [[]],
      INSPECTION_ID: '',
      vector: '',
      disabled: false,
      delSituations: [],
      delInspectors: [],
      popupShow: false,
      popupDisabled: false,
      hiddenForm: {
        id: Math.random(),
        ISRELEVANT: '2',//隐患类型
        hiddenImgs: [],
        hiddenVideos: [],
        HIDDENDESCR: '',
        HIDDENPART_NAME: '',
        HIDDENPART: '',
        HIDDENLEVEL_NAME: '',
        HIDDENLEVEL: '',
        HIDDENTYPE_NAME: '',
        HIDDENTYPE: '',
        DISCOVERYTIME: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'),
        LONGITUDE: '',
        LATITUDE: '',
        CREATOR_NAME: '',
        CREATOR: '',
        POSITIONDESC: '',
        SOURCE: '4',
        CORPINFO_ID: '',
        HIDDENFINDDEPT: ''
      },
      hiddenFormRules: {
        'hiddenImgs': {required: true, message: '请上传隐患照片'},
        'HIDDENDESCR': {required: true, message: '请输入隐患描述'},
        'HIDDENLEVEL_NAME': {required: true, message: '请选择隐患级别'},
        'HIDDENTYPE_NAME': {required: true, message: '请选择隐患类型'},
        'DISCOVERYTIME': {required: true, message: '请选择隐患发现时间'},
        'CREATOR_NAME': {required: true, message: '请选择隐患发现人'},
      },
      hiddenRegionTreeList: [],
      hiddenLevelTreeList: [
        {id: 'hiddenLevel1004', name: '轻微隐患'},
        {id: 'hiddenLevel1002', name: '一般隐患'},
      ],
      hiddenTypeTreeList: [],
      creatorList: [],
      delHiddens: [],
      delHiddenFiles: [],
      discoveryTimeShow: false,
      creatorShow: false,
      modalShow: false,
      videoUrl: '',

      signShow: false,
      type: ''
    }
  },
  async onLoad(event) {
    this.INSPECTION_ID = event.INSPECTION_ID
    this.vector = event.vector
    this.disabled = !(event.type === 'add' || event.type === 'edit');
    if (this.INSPECTION_ID) {
      await this.fnGetSafetyenvironmentalGoEdit()
    }
    this.type = event.type
    if (event.type === 'add' || event.type === 'edit') {
      await this.fnGetInspectedDepartment()
      await this.fnGetInspectionDepartment()
      await this.fnGetHiddenRegion()
      await this.fnGetHiddenType()
      // this.fnGetHiddenLevel()
      await this.fnGetInspectionType()
    }
  },
  computed: {
    userInfo() {
      return this.$store.getters.getUserInfo
    }
  },
  methods: {
    handleSituationImageUpload(event, index) {
      // 处理图片上传
      const { file } = event;
      this.form.situationList[index].IMAGE = [...(this.form.situationList[index].IMAGE || []), ...file];
    },
    handleSituationImageDelete(event, index) {
      // 处理图片删除
      const { index: imageIndex } = event;
      this.form.situationList[index].IMAGE.splice(imageIndex, 1);
    },
    async fnGetInspectedDepartment() {
      let resData = await getInspectedDepartment({'CORPINFO_ID': ''});
      this.inspectedDepartmentTreeList = JSON.parse(resData.zTreeNodes);
    },
    async fnGetInspectionDepartment() {
      let resData = await getInspectionDepartment();
      this.inspectionDepartmentTreeList = JSON.parse(resData.zTreeNodes);
    },
    async fnGetHiddenRegion(id) {
      if (!id) {
        id = {parentId: '0', DEPARTMENT_ID: this.form.INSPECTED_DEPARTMENT_ID}
      }
      let resData = await getHiddenRegion(id);
      this.hiddenRegionTreeList = JSON.parse(resData.zTreeNodes);
    },
    async fnGetHiddenType() {
      let resData = await getHiddenType();
      this.hiddenTypeTreeList = JSON.parse(resData.zTreeNodes);
    },
    async fnGetHiddenLevel() {
      let resData = await getHiddenLevel();
      this.hiddenLevelTreeList = JSON.parse(resData.zTreeNodes);
    },
    async fnGetInspectionType() {
      let resData = await getInspectionType();
      this.inspectionTypeTreeList = JSON.parse(resData.zTreeNodes);
    },
    async fnGetDeptUser(detpId) {
      let resData = await getDeptUser({'DEPARTMENT_ID': detpId});
      return resData.userList;
    },
    async fnGetInspectors(detpId) {
      let resData = await getInspectors({'DEPARTMENT_ID': detpId});
      return resData.userList;
    },
    async fnGetSafetyenvironmentalGoEdit() {
      let resData = await getSafetyenvironmentalGoEdit({INSPECTION_ID: this.INSPECTION_ID})
      for (let i = 0; i < resData.pd.hiddenList.length; i++) {
        for (let j = 0; j < resData.pd.hiddenList[i].hiddenImgs.length; j++) {
          resData.pd.hiddenList[i].hiddenImgs[j].url = this.$store.state.filePath + resData.pd.hiddenList[i].hiddenImgs[j].FILEPATH
        }
        for (let j = 0; j < resData.pd.hiddenList[i].hiddenVideos.length; j++) {
          resData.pd.hiddenList[i].hiddenVideos[j].url = this.$store.state.filePath + resData.pd.hiddenList[i].hiddenVideos[j].FILEPATH
        }
      }
      for (let i = 0; i < resData.pd.situationList.length; i++) {
        if (resData.pd.situationList[i].IMAGE_PATH) {
          resData.pd.situationList[i].IMAGE = [{ url: this.$store.state.filePath + resData.pd.situationList[i].IMAGE_PATH, imagePath: resData.pd.situationList[i].IMAGE_PATH}];
        }
      }
      console.log(resData.pd.inspectorVerifyList)
      this.form = resData.pd
    },
    showTree(ref, type) {
      if (this.popupDisabled) return;
      if (this.disabled) return;
      if (type === 'arr') this.$refs[ref][0]._show();
      else this.$refs[ref]._show()
    },
    confirmTree(e, list, index) {
      if (list === 'inspectedSiteuserColumns') {
        this.form.INSPECTED_DEPARTMENT_ID = e[0].id
        this.form.INSPECTED_DEPARTMENT_NAME = e[0].name
        this.form.INSPECTED_SITEUSER_NAME = ''
        this.form.INSPECTED_SITEUSER_ID = ''
        this.fnGetHiddenRegion({parentId: '0', DEPARTMENT_ID: e[0].id})
        this.fnGetDeptUser(e[0].id).then(res => {
          this.$set(this.inspectedSiteuserColumns, 0, res)
        })
      }
      if (list === 'inspectionTypeTreeList') {
        this.form.INSPECTION_TYPE = e[0].id
        this.form.INSPECTION_TYPE_NAME = e[0].name
      }
      if (list === 'inspectorList') {
        this.form.inspectorList[index].INSPECTION_DEPARTMENT_ID = e[0].id
        this.form.inspectorList[index].INSPECTION_DEPARTMENT_NAME = e[0].name
        this.form.inspectorList[index].INSPECTION_USER_NAME = ''
        this.form.inspectorList[index].INSPECTION_USER_ID = ''
        this.fnGetInspectors(e[0].id).then(res => {
          this.$set(this.inspectorList[0], index, res)
        })
      }
      if (list === 'hiddenRegionTreeList') {
        this.hiddenForm.HIDDENPART = e[0].id
        this.hiddenForm.HIDDENPART_NAME = e[0].name
      }
      if (list === 'hiddenLevelTreeList') {
        this.hiddenForm.HIDDENLEVEL = e[0].id
        this.hiddenForm.HIDDENLEVEL_NAME = e[0].name
      }
      if (list === 'hiddenTypeTreeList') {
        this.hiddenForm.HIDDENTYPE = e[0].id
        this.hiddenForm.HIDDENTYPE_NAME = e[0].name
      }
    },
    inspectedSiteuserConfirmPicker(e) {
      this.form.INSPECTED_SITEUSER_NAME = e.value[0].NAME
      this.form.INSPECTED_SITEUSER_ID = e.value[0].USER_ID
      this.inspectedSiteuserShow = false;
    },
    inspectionTimeStartConfirm(e) {
      this.form.INSPECTION_TIME_START = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
      this.inspectionTimeStartShow = false;
    },
    inspectionTimeEndConfirm(e) {
      this.form.INSPECTION_TIME_END = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
      this.inspectionTimeEndShow = false;
    },
    addSituation() {
      this.form.situationList.push({id: Math.random(), INSPECTION_SITUATION_ID: '', SITUATION: '',IMAGE: []})
    },
    removeSituation(item, index) {
      uni.showModal({
        title: '提示',
        cancelText: '确认',
        confirmText: '取消',
        content: '确定删除检查情况吗？',
        success: (res) => {
          if (res.cancel) {
            this.form.situationList.splice(index, 1)
            if (item.INSPECTION_SITUATION_ID) {
              this.delSituations.push(item.INSPECTION_SITUATION_ID)
            }
          }
        }
      });
    },
    addInspector() {
      this.form.inspectorList.push(
          {
            id: Math.random(),
            inspectionUserShow: false,
            INSPECTION_INSPECTOR_ID: '',
            INSPECTION_DEPARTMENT_ID: '',
            INSPECTION_DEPARTMENT_NAME: '',
            INSPECTION_USER_ID: '',
            INSPECTION_USER_INDEX: '',
            INSPECTION_USER_NAME: ''
          }
      )
      console.info(this.form.inspectorList)
    },
    removeInspector(item, index) {
      uni.showModal({
        title: '提示',
        cancelText: '确认',
        confirmText: '取消',
        content: '确定移除检查人员吗？',
        success: (res) => {
          if (res.cancel) {
            this.form.inspectorList.splice(index, 1);
            if (item.INSPECTION_INSPECTOR_ID) {
              this.delInspectors.push(item.INSPECTION_INSPECTOR_ID)
            }
          }
        }
      });
    },
    inspectionUserShowPicker(index) {
      if (this.disabled) return;
      this.form.inspectorList[index].inspectionUserShow = true
    },
    inspectionUserConfirmPicker(e, index) {
      this.form.inspectorList[index].INSPECTION_USER_ID = e.value[0].USER_ID
      this.form.inspectorList[index].INSPECTION_USER_NAME = e.value[0].NAME
      this.form.inspectorList[index].inspectionUserShow = false
      this.form.inspectorList[index].USER_SIDE = e.value[0].USER_SIDE
    },
    async fnSubmit() {
      for (const key in this.rules) {
        if (!this.form[key]) {
          uni.showToast({
            title: this.rules[key].message,
            icon: "none"
          })
          return;
        }
      }
      const situations  = [];
      for (let i = 0; i < this.form.situationList.length; i++) {
        if (!this.form.situationList[i].SITUATION) {
          uni.showToast({
            title: `请填写第${i + 1}项检查情况`,
            icon: 'none'
          })
          return
        }
        let imagePath = '';
        if (this.form.situationList[i].IMAGE[0]?.imagePath) {
          imagePath = this.form.situationList[i].IMAGE[0].imagePath
        } else if (this.form.situationList[i].IMAGE.length) {
          const { imgUrl } = await uploadSmd({
            filePath: this.form.situationList[i].IMAGE[0].url,
            name: "file",
          });
          imagePath = imgUrl;
        }
        situations.push({
          imagePath: imagePath,
          ...this.form.situationList[i],
          IMAGE: null
        })
      }
      for (let i = 0; i < this.form.inspectorList.length; i++) {
        if (!this.form.inspectorList[i].INSPECTION_USER_NAME) {
          uni.showToast({
            title: `请选择第${i + 1}项检查人员`,
            icon: 'none'
          })
          return
        }
      }
      if (this.form.INSPECTION_USER_OPINION) {
        if (!this.form.INSPECTION_USER_SIGN_IMG) {
          uni.showToast({
            title: `您还未签字`,
            icon: 'none'
          })
          return
        }
      }
      let vector = 0
      for (let x in this.form.inspectorList) {
        vector = 0
        for (let y in this.form.inspectorList) {
          if (this.form.inspectorList[y].INSPECTION_USER_ID === this.form.inspectorList[x].INSPECTION_USER_ID) vector++
        }
        if (vector > 1) {
          uni.showToast({
            title: '检查人重复！请检查数据',
            icon: "none"
          })
          return
        }
      }
      let index = this.form.inspectorList.findIndex(item => {
        return item.INSPECTION_USER_ID === this.userInfo.USER_ID
      })
      if (index < 0) {
        this.form.inspectorList.push(
            {
              INSPECTION_INSPECTOR_ID: '',	//检查人员主键
              INSPECTION_DEPARTMENT_ID: this.userInfo.DEPARTMENT_ID,	//检查人员部门ID
              INSPECTION_DEPARTMENT_NAME: this.userInfo.DEPARTMENT_NAME,
              INSPECTION_USER_ID: this.userInfo.USER_ID,		//检查人员ID
              INSPECTION_USER_INDEX: '',
              INSPECTION_USER_NAME: this.userInfo.NAME
            }
        )
      }
      let resData
      if (this.form.INSPECTION_USER_SIGN_IMG) {
        let params = {
          filePath: this.form.INSPECTION_USER_SIGN_IMG,
          name: 'FFILE',
          formData: {
            ...this.form,
            INSPECTION_ORIGINATOR_ID: this.userInfo.USER_ID,
            INSPECTION_STATUS: '1',
            delInspectors: this.delInspectors.join(','),
            delSituations: this.delSituations.join(','),
            delHiddens: this.delHiddens.join(','),
            delHiddenFiles: this.delHiddenFiles.join(','),
            INSPECTORJSON: JSON.stringify(this.form.inspectorList),
            SITUATIONJSON: JSON.stringify(situations),
            HIDDENJSON: JSON.stringify(this.form.hiddenList),
          }
        }
        resData = this.INSPECTION_ID ? await setSafetyenvironmentalEdit_plus(params) : await setSafetyenvironmentalAdd_plus(params)
      } else {
        let params = {
          ...this.form,
          INSPECTION_ORIGINATOR_ID: this.userInfo.USER_ID,
          INSPECTION_STATUS: '1',
          delInspectors: this.delInspectors.join(','),
          delSituations: this.delSituations.join(','),
          delHiddens: this.delHiddens.join(','),
          delHiddenFiles: this.delHiddenFiles.join(','),
          INSPECTORJSON: JSON.stringify(this.form.inspectorList),
          SITUATIONJSON: JSON.stringify(situations),
          HIDDENJSON: JSON.stringify(this.form.hiddenList),
        }
        resData = this.INSPECTION_ID ? await setSafetyenvironmentalEdit(params) : await setSafetyenvironmentalAdd(params)
      }

      let PromiseArr = []
      for (let i = 0; i < resData.pd.hiddenList.length; i++) {
        for (let j = 0; j < this.form.hiddenList[i].hiddenImgs.length; j++) {
          let imgFiles = []
          imgFiles.push({
            uri: this.form.hiddenList[i].hiddenImgs[j].url,
            FFILE: this.form.hiddenList[i].hiddenImgs[j].url,
          })
          PromiseArr.push(this.fnSetImgFilesAdd(imgFiles, resData.pd.hiddenList[i].HIDDEN_ID))
        }
        for (let j = 0; j < this.form.hiddenList[i].hiddenVideos.length; j++) {
          PromiseArr.push(this.fnSetVideoAdd(this.form.hiddenList[i].hiddenVideos[j].url, resData.pd.hiddenList[i].HIDDEN_ID))
        }
      }
      Promise.all(PromiseArr).then(() => {
        uni.showToast({
          title: this.INSPECTION_ID ? '修改成功' : '添加成功',
        })
        if (this.vector !== 'list') {
          uni.$u.route({
            type: 'navigateBack'
          })
        } else {
          uni.$u.route({
            type: 'navigateBack',
            delta: 2
          })
        }
      }).catch((e) => {
        uni.showToast({
          title: '添加失败！',
          icon: 'error',
          duration: 2000
        });
      })
    },
    async fnSetImgFilesAdd(imgFiles, FOREIGN_KEY) {
      if (imgFiles[0].uri.indexOf('qgqy.qhdsafety.com') > 0) {
        return await function () {
          console.log('ok')
        }
      }
      return await setImgFilesAdd({
        files: imgFiles,
        formData: {
          FOREIGN_KEY,
          TYPE: '3'
        },
        loading: false
      })
    },
    async fnSetVideoAdd(filePath, FOREIGN_KEY) {
      if (filePath && filePath.indexOf('qgqy.qhdsafety.com') > 0) {
        return await function () {
          console.log('ok')
        }
      }
      return await setVideoAdd({
        filePath,
        name: 'FFILE',
        formData: {
          FOREIGN_KEY,
          TYPE: 102,
          CORPINFO_ID: this.userInfo.CORPINFO_ID,
        },
        loading: false
      })
    },
    addHidden() {
      this.clearHiddenForm()
      this.creatorList = [[{NAME: this.userInfo.NAME, USER_ID: this.userInfo.USER_ID}]]
      this.form.inspectorList.forEach(item => {
        let index = this.creatorList[0].findIndex(items => items.USER_ID === item.INSPECTION_USER_ID)
        if (index < 0) {
          this.creatorList[0].push({
            USER_ID: item.INSPECTION_USER_ID,
            NAME: item.INSPECTION_USER_NAME,
            DEPARTMENT_ID: item.INSPECTION_DEPARTMENT_ID
          })
        }
      })
      this.popupShow = true
      this.popupDisabled = false
    },
    showHidden(item) {
      this.clearHiddenForm()
      this.creatorList = [[]]
      this.form.inspectorList.forEach(item => {
        this.creatorList[0].push({
          USER_ID: item.INSPECTION_USER_ID,
          NAME: item.INSPECTION_USER_NAME,
          DEPARTMENT_ID: item.INSPECTION_DEPARTMENT_ID
        })
      })
      this.hiddenForm = item
      this.popupShow = true
      this.popupDisabled = true
    },
    clearHiddenForm() {
      this.hiddenForm = {
        id: Math.random(),
        ISRELEVANT: '2',//隐患类型
        hiddenImgs: [],
        hiddenVideos: [],
        HIDDENDESCR: '',
        HIDDENPART_NAME: '',
        HIDDENPART: '',
        HIDDENLEVEL_NAME: '',
        HIDDENLEVEL: '',
        HIDDENTYPE_NAME: '',
        HIDDENTYPE: '',
        DISCOVERYTIME: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'),
        LONGITUDE: '',
        LATITUDE: '',
        CREATOR_NAME: '',
        CREATOR: '',
        POSITIONDESC: '',
        SOURCE: '4'
      }
    },
    removeHidden(item, index) {
      uni.showModal({
        title: '提示',
        cancelText: '确认',
        confirmText: '取消',
        content: '确定移除发现问题吗？',
        success: (res) => {
          if (res.cancel) {
            this.form.hiddenList.splice(index, 1);
            if (item.HIDDEN_ID) {
              this.delHiddens.push(item.HIDDEN_ID)
            }
          }
        }
      });
    },
    afterRead(event) {
      this.hiddenForm.hiddenImgs = [...this.hiddenForm.hiddenImgs, ...event.file]
    },
    deletePic(event) {
      if (this.hiddenForm.hiddenImgs[event.index].IMGFILES_ID) {
        this.delHiddenFiles.push(this.hiddenForm.hiddenImgs[event.index].FILEPATH)
      }
      this.hiddenForm.hiddenImgs = this.hiddenForm.hiddenImgs.filter(item => item.url !== event.file.url)
    },
    afterRead1(event) {
      this.hiddenForm.hiddenVideos = [...this.hiddenForm.hiddenVideos, ...event.file]
    },
    deletePic1(event) {
      this.hiddenForm.hiddenVideos = this.hiddenForm.hiddenVideos.filter(item => item.url !== event.file.url)
    },
    discoveryTimeConfirm(e) {
      this.hiddenForm.DISCOVERYTIME = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
      this.discoveryTimeShow = false;
    },
    showMapModal() {
      let _this = this
      uni.navigateTo({
        url: '/pages/map/map',
        events: {
          acceptDataFromOpenedPage: function (e) {
            _this.hiddenForm.LONGITUDE = e.data.longitue;
            _this.hiddenForm.LATITUDE = e.data.latitude;
          }
        },
        success: function (res) {
          res.eventChannel.emit('acceptDataFromOpenerPage', {data: {title: '安全环保检查发起'}})
        }
      })
    },
    creatorConfirmPicker(e) {
      this.hiddenForm.CREATOR = e.value[0].USER_ID
      this.hiddenForm.CREATOR_NAME = e.value[0].NAME
      this.hiddenForm.HIDDENFINDDEPT = e.value[0].DEPARTMENT_ID
      this.creatorShow = false;
    },
    popupClose() {
      this.popupShow = false
    },
    popupSave() {
      for (const key in this.hiddenFormRules) {
        if (!this.hiddenForm[key]) {
          uni.showToast({
            title: this.hiddenFormRules[key].message,
            icon: "none"
          })
          return;
        }
      }
      this.hiddenForm.SOURCE = 4
      this.form.hiddenList.push(this.hiddenForm)
      this.popupClose()
    },
    previewImage(current) {
      if (false) {
        uni.previewImage({
          urls: [current],
          current
        });
      }
    },
    previewVideo(videoUrl) {
      this.modalShow = true;
      this.videoUrl = videoUrl;
    },
    signConfirm({path}) {
      this.form.INSPECTION_USER_SIGN_IMG = path
    },
  },
}
</script>

<style scoped>
.flex-1 {
  flex: 1;
}

.title {
  min-width: 170rpx;
}

.textarea-box {
  width: 100%;
}
</style>
