<template>
  <div>
    <div class="app-container">
      <el-form ref="form" :rules="rules" :model="form" label-width="170px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检查题目" prop="INSPECTION_SUBJECT">
              <el-radio-group id="INSPECTION_SUBJECT" ref="INSPECTION_SUBJECT" v-model="form.INSPECTION_SUBJECT">
                <el-radio :label="'安全'">安全</el-radio>
                <el-radio :label="'环保'">环保</el-radio>
                <el-radio :label="'综合'">综合</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="被检查单位" prop="INSPECTED_DEPARTMENT_ID">
              <SelectTree
                ref="deptTree"
                :clearable="false"
                :options="treeData"
                :props="defaultProps"
                v-model="form.INSPECTED_DEPARTMENT_ID"
                placeholder="请选择被检查单位"
                style="width: 300px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="被检查单位现场负责人" prop="INSPECTED_SITEUSER_ID">
              <el-select v-model="form.INSPECTED_SITEUSER_ID" clearable placeholder="请选择被检查单位现场负责人">
                <el-option v-for="item in INSPECTED_SITEUSER_List" :key="item.USER_ID" :label="item.NAME" :value="item.USER_ID" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="检查场所" prop="INSPECTION_PLACE">
          <el-input id="INSPECTION_PLACE" ref="INSPECTION_PLACE" v-model="form.INSPECTION_PLACE" maxlength="255" placeholder="这里输入检查场所..." title="检查场所"/>
        </el-form-item>
        <el-form-item label="检查人确认" prop="CONFIRM_MESSAGE">
          <el-input id="Confirm" ref="openConfirm" v-model="form.CONFIRM_MESSAGE" maxlength="255" readonly placeholder="点击签字" title="检查人确认" @click.native="openConfirm"/>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :prop="switchInspectionType === 'select'?'INSPECTION_TYPE':'INSPECTION_TYPE_OTHER'" label="检查类型">
              <el-input v-if="switchInspectionType ==='value'" v-model="form.INSPECTION_TYPE_OTHER" placeholder="请输入内容" style="width: 60%;display: inline-block" />
              <SelectTree
                v-if="switchInspectionType === 'select'"
                ref="tree_InspectionType"
                :clearable="false"
                :options="inspectionTypeTree"
                :props="defaultProps"
                v-model="form.INSPECTION_TYPE"
                :canparent="false"
                placeholder="这里选择检查类型..."
                children-name="nodes" />
              <el-button class="ml5" @click="changeSwitch('InspectionType')">{{ switchInspectionType === 'select' ? '输入' : '选择' }}</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检查开始时间" prop="INSPECTION_TIME_START">
              <el-date-picker v-model="form.INSPECTION_TIME_START" format="yyyy-MM-dd HH:mm" v-on:blur="checkTime(form.INSPECTION_TIME_START)" value-format="yyyy-MM-dd HH:mm" type="datetime" placeholder="选择检查开始时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检查结束时间" prop="INSPECTION_TIME_END">
              <el-date-picker v-model="form.INSPECTION_TIME_END" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm" type="datetime" placeholder="选择检查结束时间"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">检查人员 <el-button type="primary" size="mini" @click="addInspector">添加</el-button></el-divider>
        <el-form-item v-for="(item,index) in form.inspectorList" :key="index + (Math.random() + '').replace('.', '')" :label="(index+1)+'.'">
          <div class="uo-flex">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="检查人员部门" prop="INSPECTION_DEPARTMENT_ID" label-width="100px">
                  <SelectTree
                    ref="'deptTree_INSPECTION'+index"
                    :clearable="false"
                    :options="treeDataInspectDept"
                    :props="defaultProps"
                    v-model="item.INSPECTION_DEPARTMENT_ID"
                    placeholder="请选择检查人员部门"
                    style="width: 300px"
                    @change="updateInspecteDept(item.INSPECTION_DEPARTMENT_ID,index)"/>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="检查人员" prop="INSPECTION_USER_ID" label-width="100px">
                  <el-select v-model="item.INSPECTION_USER_ID" clearable placeholder="请选择检查人员">
                    <el-option v-for="data in INSPECTOR_List[index]" :key="data.USER_ID" :label="data.NAME" :value="data.USER_ID" @click.native="changeHiddenUserList(item, data)" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="1">
                <el-button plain size="mini" type="danger" icon="el-icon-delete" title="移除" @click="delInspectorRow(item,index)"/>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
        <el-divider content-position="left">检查情况 <el-button type="primary" size="mini" @click="addSituation">添加</el-button></el-divider>
        <el-form-item v-for="(item,index) in form.situationList" :key="'SITUATION'+index" :label="(index+1)+'.'" :prop="item.SITUATION">
          <div class="uo-flex">
            <el-input v-model="item.SITUATION" :autosize="{ minRows: 1}" maxlength="255" type="textarea" placeholder="这里输入检查情况..." style="margin-right: 5px" />
            <el-button plain size="mini" type="danger" icon="el-icon-delete" title="删除" @click="delSituationRow(item,index)"/>
          </div>
        </el-form-item>
        <div style="margin-top: 50px;"/>
        <el-divider content-position="left">发现问题 <el-button type="primary" size="mini" @click="addHidden">添加</el-button></el-divider>

        <div class="mb-20">
          <table class="table-ui">
            <tr>
              <th width="55" style="text-align:center">序号</th>
              <th>问题描述</th>
              <th width="200">操作</th>
            </tr>
            <template v-if="form.hiddenList.length !== 0">
              <tr v-for="(item,index) in form.hiddenList" :key="'HIDDEN'+index">
                <td align="center">{{ index+1 }}</td>
                <td>{{ item.HIDDENDESCR }}</td>
                <td>
                  <el-button v-if="false" type="primary" icon="el-icon-edit" size="mini" @click="editInspectionHidden(item,index)">修改</el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeInspectionHidden(item,index)">删除</el-button>
                </td>
              </tr>
            </template>
            <template v-else>
              <tr>
                <td colspan="3" style="text-align: center">暂无数据</td>
              </tr>
            </template>
          </table>
        </div>
      </el-form>
      <Confirm ref="confirm" @getProposal="getProposal"/>
    </div>

    <!--  添加隐患  -->
    <el-dialog v-if="dialogFormVisible" :visible.sync="dialogFormVisible" title="添加隐患">
      <el-form ref="hiddenForm" :rules="hiddenRules" :model="hiddenForm" label-width="140px" style="padding:0 20px">
        <el-form-item label="隐患描述:" prop="HIDDENDESCR">
          <el-input v-model="hiddenForm.HIDDENDESCR" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="隐患发现时间:" prop="DISCOVERYTIME">
          <el-date-picker
            v-model="hiddenForm.DISCOVERYTIME"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
            placeholder="选择日期"/>
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-form-item label="隐患部位:" prop="HIDDENPART">
              <el-input v-if="hiddenPartType =='value'" v-model="hiddenForm.HIDDENPART" style="width: 90%;" placeholder="请输入内容" />
              <SelectTree
                v-if="hiddenPartType =='select'"
                ref="deptTree_Select1"
                :clearable="false"
                :options="hiddenPartList"
                :props="defaultProps"
                v-model="hiddenForm.HIDDENPART"
                style="width: 90%;"
                allow-create
                placeholder="请选择" />
              <el-button class="ml5" @click="hiddenPartTypeBtn">{{ hiddenPartType === 'select' ? '输入' : '选择' }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="隐患级别:" prop="HIDDENLEVEL">
              <el-select v-model="hiddenForm.HIDDENLEVEL" style="width: 100%;">
                <el-option
                  v-for="item in hiddenlevelList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="隐患类型:" prop="HIDDENTYPE">
              <SelectTree
                ref="deptTree_Select3"
                :clearable="false"
                :options="hiddenTypeList"
                :props="defaultProps"
                v-model="hiddenForm.HIDDENTYPE"
                :canparent="false"
                children-name="nodes"
                style="width: 100%;"
                placeholder="请选择" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="隐患位置:" prop="LONGITUDE" >
            <el-row>
              <el-col :span="5" style="padding-right: 2px">
                <el-input
                  id="LONGITUDE"
                  ref="LONGITUDE"
                  v-model="hiddenForm.LONGITUDE"
                  :readonly="true"
                  maxlength="255"
                  placeholder="这里选择隐患经度..."
                  title="隐患位置经度"
                  @focus="chooseMap" />
              </el-col>
              <el-col :span="5" style="padding-left: 2px">
                <el-input
                  id="LATITUDE"
                  ref="LATITUDE"
                  v-model="hiddenForm.LATITUDE"
                  :readonly="true"
                  maxlength="255"
                  placeholder="这里选择隐患位置纬度..."
                  title="隐患位置经度"
                  @focus="chooseMap" />
              </el-col>
              <el-col :span="4">
                <el-button type="primary" icon="el-icon-add-location" style="margin-left:10px; " plain @click="chooseMap">位置定位</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-row>
        <el-form-item label="隐患部位描述:" prop="POSITIONDESC">
          <el-input v-model="hiddenForm.POSITIONDESC" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-form-item label="是否相关方:" prop="ISRELEVANT">
              <el-radio v-model="hiddenForm.ISRELEVANT" label="1">是</el-radio>
              <el-radio v-model="hiddenForm.ISRELEVANT" label="2">否</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="隐患图片:" class="is-required">
              <div class="disContent">
                <el-upload
                  ref="hiddenUpload"
                  :file-list="hiddenForm.hiddenImgs"
                  :on-preview="handlePictureCardPreview"
                  :before-upload="hiddenBeforeUpload"
                  :on-change="hiddenChange"
                  :on-remove="handleRemove"
                  :auto-upload="false"
                  :limit="4"
                  :class="{hide:hideUpload}"
                  multiple
                  class="avatar-uploader"
                  action="#"
                  accept=".jpg,.jpeg,.png"
                  list-type="picture-card">
                  <i class="el-icon-plus" />
                </el-upload>
              </div>
              <el-dialog :visible.sync="dialogVisible" append-to-body>
                <img :src="dialogImageUrl" width="100%" alt="">
              </el-dialog>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="隐患视频:">
              <el-upload
                ref="videoUpload"
                :on-remove="handleRemoveVideo"
                :on-error="handleUploadVideoError"
                :on-exceed="handleUploadVideoExceed"
                :before-upload="beforeVideoFileUpload"
                :file-list="fileVideoList"
                :limit="1"
                accept=".mp4"
                class="upload-demo"
                action="#"
                multiple>
                <div>
                  <el-button size="small" type="primary" style="width:110px">点击上传</el-button>
                  <span class="red-tip">* 只能上传mp4文件.最大上传50M</span>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="form-group input-group-sm">
          <el-form-item label="隐患发现人:" prop="CREATOR">
            <el-select v-model="hiddenForm.CREATOR" clearable placeholder="请选择隐患发现人" @change="changeHiddenFindDept">
              <el-option v-for="item in RESPONSIBLE_USER_List" :key="item.USER_ID" :label="item.NAME" :value="item.USER_ID" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img :src="dialogImageUrl" width="100%" alt="">
        </el-dialog>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false;hideUpload = false">取 消</el-button>
        <el-button type="primary" @click="saveInspectionHidden">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogMap" :title="'隐患位置'" width="80%">
      <div>
        <iframe :src="iframeSrc" frameborder="0" allowtransparency="true" width="100%" height="600"/>
      </div>
    </el-dialog>

    <div class="ui-height" />
    <div class="ui-foot">
      <el-button type="primary" @click="confirm">确 定</el-button>
      <el-button @click="goBack">取 消</el-button>
    </div>
  </div>
</template>
<script>

import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
import SelectTree from '@/components/SelectTree'
import { upload } from '@/utils/upload'
import Confirm from './confirm'

export default {
  components: { SelectTree, Confirm },
  directives: { waves },
  data() {
    return {
      listLoading: true,
      config: config,
      loginUserId: '',
      loginUserName: '',
      INSPECTED_SITEUSER_List: [],
      INSPECTION_TYPE_List: [],
      INSPECTOR_List: [],
      treeData: [],
      treeDataInspectDept: [],
      inspectionTypeTree: [],
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      pd: [],
      switchInspectionType: 'select',
      form: {
        INSPECTION_SUBJECT: '', // 检查标题
        INSPECTION_SOURCE: '4', // 检查来源(4-监管端 5-企业端)
        inspectorList: [{ INSPECTION_INSPECTOR_ID: '', INSPECTION_DEPARTMENT_ID: '', INSPECTION_USER_ID: '', USER_SIDE: '' }], // 检查人员
        INSPECTION_ORIGINATOR_ID: '', // 检查发起人
        INSPECTED_DEPARTMENT_ID: '', // 被检查单位
        INSPECTED_SITEUSER_ID: '', // 被检查单位现场负责人
        INSPECTED_EXPLAIN: '', // 申辩内容
        INSPECTED_SITEUSER_SIGN_IMG: '', // 被检查单位现场负责人签字
        INSPECTED_SITEUSER_SIGN_TIME: '', // 被检查单位现场负责人签字时间
        INSPECTION_TYPE: '', // 检查类型
        INSPECTION_TYPE_OTHER: '', // 检查类型(其他)
        INSPECTION_PLACE: '', // 检查场所
        INSPECTION_TIME_START: '', // 检查开始时间
        INSPECTION_TIME_END: '', // 检查结束时间
        INSPECTION_STATUS: '0', // 状态(0.暂存 1.检查人待确认、2.被检查人待确认、3.归档 -1.检查人异议打回 -2被检查人申辩)
        CONFIRM_MESSAGE: '',
        CONFIRM_MESSAGE_SIGN: '',
        CONFIRM_MESSAGE_TIME: '',
        situationList: [{ INSPECTION_SITUATION_ID: '', SITUATION: '' }], // 检查情况
        hiddenList: [{ ...this.hiddenForm }] // 隐患信息集合
      },
      hiddenCurIndex: -1,
      hdFile: [], // 隐患附件
      dialogType: 'add',
      rules: {
        INSPECTION_SUBJECT: [{ required: true, message: '检查标题不能为空', trigger: 'blur' }],
        INSPECTED_DEPARTMENT_ID: [{ required: true, message: '被检查单位不能为空', trigger: 'blur' }],
        INSPECTED_SITEUSER_ID: [{ required: true, message: '被检查单位现场负责人不能为空', trigger: 'blur' }],
        INSPECTED_EXPLAIN: [{ required: true, message: '申辩内容不能为空', trigger: 'blur' }],
        INSPECTED_SITEUSER_SIGN_IMG: [{ required: true, message: '被检查单位现场负责人签字不能为空', trigger: 'blur' }],
        INSPECTED_SITEUSER_SIGN_TIME: [{ required: true, message: '请选择被检查单位现场负责人签字时间', trigger: 'blur' }],
        INSPECTION_TYPE: [{ required: true, message: '检查类型不能为空', trigger: 'blur' }],
        INSPECTION_TYPE_OTHER: [{ required: true, message: '检查类型不能为空', trigger: 'blur' }],
        INSPECTION_PLACE: [{ required: true, message: '检查场所不能为空', trigger: 'blur' }],
        INSPECTION_TIME_START: [{ required: true, message: '请选择检查开始时间', trigger: 'blur' }],
        INSPECTION_TIME_END: [{ required: true, message: '请选择检查结束时间', trigger: 'blur' }],
        INSPECTION_STATUS: [{ required: true, message: '状态(0.暂存 1.检查人待确认、2.被检查人待确认、3.归档 -1.检查人异议打回 -2被检查人申辩)不能为空', trigger: 'blur' }]
      },
      dialogFormVisible: false,
      hiddenDialogType: 'add',
      hiddenForm: {
        ISRELEVANT: '', // 是否相关方
        HIDDEN_ID: '', // 隐患ID
        HIDDENDESCR: '', // 隐患描述
        HIDDENPART: '', // 隐患部位
        HIDDENLEVEL: '', // 隐患级别
        HIDDENTYPE: '', // 隐患类型1
        HIDDENTYPE2: '', // 隐患类型2
        LONGITUDE: '', // 隐患位置经度
        LATITUDE: '', // 隐患位置纬度
        DISCOVERYTIME: '', // 隐患发现时间
        HIDDENFINDDEPT: '', // 隐患发现部门(隐患责任人部门)
        CREATOR: '', // 发现人(隐患责任人)
        SOURCE: '4', // 隐患描述
        POSITIONDESC: ''
      },
      hiddenPartList: [], // 隐患部位
      hiddenPartType: 'select',
      hiddenlevelList: [{ value: 'hiddenLevel1002', label: '一般隐患' }, { value: 'hiddenLevel1004', label: '轻微隐患' }], // 隐患级别
      hiddenTypeList: [], // 隐患类型1
      hiddenType2List: [], // 隐患类型2
      RESPONSIBLE_USER_List: [{ NAME: JSON.parse(sessionStorage.getItem('user')).NAME, USER_ID: JSON.parse(sessionStorage.getItem('user')).USER_ID }], // 隐患责任人
      dialogMap: false,
      iframeSrc: '',
      hiddenImgs: [], // 隐患图片
      hideUpload: false,
      dialogImageUrl: '',
      dialogVisible: false,
      imgList: [{ name: '', url: '' }],
      imgListTemp: [{ name: '', url: '' }],
      fileHdImgList: [], // 隐患图片
      fileVideoList: [], // 隐患视频
      hiddenRules: {
        HIDDENDESCR: [{ required: true, message: '隐患描述不能为空', trigger: 'blur' }],
        HIDDENLEVEL: [{ required: true, message: '隐患级别不能为空', trigger: 'blur' }],
        HIDDENTYPE: [{ required: true, message: '隐患类型不能为空', trigger: 'blur' }],
        LATITUDE: [{ required: true, message: '隐患位置不能为空', trigger: 'blur' }],
        DISCOVERYTIME: [{ required: true, message: '隐患发现时间不能为空', trigger: 'blur' }],
        HIDDENFINDDEPT: [{ required: true, message: '隐患发现人部门不能为空', trigger: 'blur' }],
        CREATOR: [{ required: true, message: '隐患发现人不能为空', trigger: 'blur' }]
      }
    }
  },
  watch: {
    'form.INSPECTED_DEPARTMENT_ID': {
      handler(newVal, oldVal) {
        if (this.dialogType == 'add' || (oldVal != null && oldVal != '')) { // 编辑初始化时,不监听
          this.form.INSPECTED_SITEUSER_ID = ''
          this.INSPECTED_SITEUSER_List = []
        }
        if (newVal != null && newVal != '') {
          this.getUserList(newVal)
        }
      },
      immediate: false

    }
  },
  async created() {
    const loading = this.$loading({
      lock: true,
      text: '数据加载中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    this.resetForm()
    await this.getDict()
    await this.handleAdd()
    await this.getEditMyInfo()
    await this.getHiddenReginTreeListData()
    loading.close()
  },
  mounted() {
    const that = this
    window.addEventListener('message', function(e) {
      that.hiddenForm.LONGITUDE = e.data.LONGITUDE
      that.hiddenForm.LATITUDE = e.data.LATITUDE
      that.dialogMap = false
    })
  },
  methods: {
    checkTime(data){
      if (Date.parse(data)>new Date().getTime()){
        this.$message.error("检查开始时间需小于当前时间")
        this.$refs['form'].resetFields()
      }
    },
    // 添加
    handleAdd() {
      this.dialogType = 'add'
    },
    changeSwitch(type) {
      if (type === 'InspectionType') {
        this.form.INSPECTION_TYPE = ''
        this.form.INSPECTION_TYPE_OTHER = ''
        this.switchInspectionType = (this.switchInspectionType === 'select') ? 'value' : 'select'
        if (this.switchInspectionType === 'select') {
          this.rules.INSPECTION_TYPE = [{ required: true, message: '检查类型不能为空', trigger: 'blur' }]
          this.rules.INSPECTION_TYPE_OTHER = [{ required: false, message: '检查类型不能为空', trigger: 'blur' }]
        } else {
          this.rules.INSPECTION_TYPE = [{ required: false, message: '检查类型不能为空', trigger: 'blur' }]
          this.rules.INSPECTION_TYPE_OTHER = [{ required: true, message: '检查类型不能为空', trigger: 'blur' }]
        }
      }
    },
    addInspector() {
      this.form.inspectorList.push({ INSPECTION_INSPECTOR_ID: '', INSPECTION_DEPARTMENT_ID: '', INSPECTION_USER_ID: '', USER_SIDE: '' })
      this.INSPECTOR_List.push([])
    },
    updateInspecteDept(DEPARTMENT_ID, i) {
      this.form.inspectorList[i].INSPECTION_USER_ID = ''
      this.form.inspectorList[i].USER_SIDE = ''
      this.getInspectorList(DEPARTMENT_ID, i)
    },
    // 获取人员列表
    getInspectorList(DEPARTMENT_ID, i) {
      if (DEPARTMENT_ID) {
        requestFN(
          '/user/listAllManageAndCorp',
          {
            DEPARTMENT_ID: DEPARTMENT_ID,
            NOMAIN: '1'
          }
        ).then((data) => {
          this.INSPECTOR_List[i] = data.userList
          this.$forceUpdate()
        }).catch((e) => {
        })
      }
    },
    /* 隐患责任人改为充检查人员中选取 */
    changeHiddenUserList(item, data) {
      item.USER_SIDE = data.USER_SIDE
      for (let i = 0; i < this.form.inspectorList.length; i++) {
        this.INSPECTOR_List[i].forEach(item => {
          if (this.form.inspectorList[i].INSPECTION_USER_ID === item.USER_ID) {
            const index = this.RESPONSIBLE_USER_List.findIndex(vector => vector.USER_ID === item.USER_ID)
            if (index < 0) {
              this.RESPONSIBLE_USER_List.push(item)
            }
          }
        })
      }
    },
    // 删除检查人员
    delInspectorRow(row, index) {
      if (this.validStr(row.INSPECTION_DEPARTMENT_ID) || this.validStr(row.INSPECTION_USER_ID)) {
        this.$confirm('确定要移除第' + (index + 1) + '个检查人员吗?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.inspectorList.splice(index, 1)
          this.INSPECTOR_List.splice(index, 1)
        }).catch(() => {
        })
      } else {
        this.form.inspectorList.splice(index, 1)
        this.INSPECTOR_List.splice(index, 1)
      }
    },
    // 添加检查情况
    addSituation() {
      this.form.situationList.push({ INSPECTION_SITUATION_ID: '', SITUATION: '' })
    },
    // 删除检查情况
    delSituationRow(row, index) {
      if (this.form.situationList[index]) {
        this.$confirm('确定要移除第' + (index + 1) + '条检查情况吗?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.situationList.splice(index, 1)
        }).catch(() => {
        })
      } else {
        this.form.situationList.splice(index, 1)
      }
    },

    // 添加检查问题
    addHidden() {
      this.getHiddenReginTreeList()
      this.resetHd()
      this.RESPONSIBLE_USER_List = [{ NAME: JSON.parse(sessionStorage.getItem('user')).NAME, USER_ID: JSON.parse(sessionStorage.getItem('user')).USER_ID }]
      for (let i = 0; i < this.form.inspectorList.length; i++) {
        this.INSPECTOR_List[i].forEach(item => {
          if (this.form.inspectorList[i].INSPECTION_USER_ID === item.USER_ID) {
            const index = this.RESPONSIBLE_USER_List.findIndex(vector => vector.USER_ID === item.USER_ID)
            if (index < 0) {
              this.RESPONSIBLE_USER_List.push(item)
            }
          }
        })
      }
      this.dialogFormVisible = true
      this.hideUpload = false
    },
    hiddenPartTypeBtn() {
      this.hiddenForm.HIDDENPART = ''
      this.hiddenPartType = (this.hiddenPartType == 'select') ? 'value' : 'select'
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    // 隐患上传
    hiddenBeforeUpload(file) {
      const types = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = types.includes(file.type)
      if (!isImage) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!')
      } else if (this.fileHdImgList.length >= 4) {
        this.$message.error('最多上传4张隐患图片')
      } else {
        this.fileHdImgList.push(file)
      }
    },
    hiddenChange(file, fileList) {
      const types = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = types.includes(file.raw.type)
      if (!isImage) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!')
        fileList.pop()
      }
      if (this.dialogFormVisible) {
        console.info(fileList)
        for (let i = 0; i < fileList.length; i++) {
          this.imgListTemp[i] = { name: 'hdImg' + i, url: URL.createObjectURL(fileList[i].raw) }
        }
        console.info(this.imgListTemp)
      }
      this.hideUpload = fileList.length >= 4
    },
    handleRemove(file, fileList) {
      this.hideUpload = fileList.length >= 4
    },
    // 删除隐患照片
    delHiddenImg(index) {
      this.$confirm('确定要移除该隐患图片吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.hiddenImgs.splice(index, 1)
      }).catch(() => {
      })
    },

    handleRemoveVideo(file, fileVideoList) { // 文件列表移除文件时的钩子
      this.fileVideoList = []
    },
    // eslint-disable-next-line handle-callback-err
    handleUploadVideoError(err, file, fileVideoList) {
      this.fileVideoList = fileVideoList
      file.status = 'success'
      this.fileVideoList.push(file)
    },
    handleUploadVideoExceed(file, fileVideoList) { // 文件超出个数限制时的钩子
      this.$message.warning('最多上传1个视频哦!')
    },
    beforeVideoFileUpload(file) {
      const types = ['video/mp4']
      const isImage = types.includes(file.type)
      const isLt500M = file.size / 1024 / 1024 < 50
      if (this.fileVideoList.length > 0) {
        this.$message.error('文件超出个数限制!')
        return false
      }
      if (!isImage) {
        this.$message.error('上传视频只能是 MP4 格式!')
        return false
      } else if (!isLt500M) {
        this.$message.error('上传视频大小不能超过 50MB!')
        return false
      } else {
        this.fileVideoList.push(file)
        this.$forceUpdate()
        return true
      }
    },
    // 添加/编辑其他隐患
    editInspectionHidden(item, index) {
      this.hiddenCurIndex = index
      this.hiddenForm = JSON.parse(JSON.stringify(this.form.hiddenList[index]))
      console.log(this.hiddenForm)
      this.$set(this.hiddenForm, 'hiddenImgs', this.imgList)
      // this.fileHdImgList = this.hdFile[index].fileHdImgList
      this.fileVideoList = this.hdFile[index].fileVideoList
      this.dialogFormVisible = true
      this.hideUpload = false
    },
    // 删除
    removeInspectionHidden(item, index) {
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.hiddenList.splice(index, 1)
        this.hdFile.splice(index, 1)
      }).catch(() => {
      })
    },
    changeHiddenFindDept(val) {
      this.form.inspectorList.forEach(item => {
        if (val === item.INSPECTION_USER_ID) {
          this.hiddenForm.HIDDENFINDDEPT = item.INSPECTION_DEPARTMENT_ID
        }
      })
    },
    // 隐患提交
    saveInspectionHidden() {
      if (this.$refs.hiddenUpload.uploadFiles.length < 1) {
        this.$message({
          message: '请上传隐患图片',
          type: 'error'
        })
        return false
      }
      this.$refs.hiddenForm.validate(valid => {
        if (valid) {
          this.$refs.hiddenUpload.submit()
          const formData = { fileHdImgList: this.fileHdImgList, fileVideoList: this.fileVideoList }
          if (this.hiddenCurIndex !== -1) {
            this.form.hiddenList[this.hiddenCurIndex] = this.hiddenForm
            this.hdFile[this.hiddenCurIndex] = formData
            this.hiddenCurIndex = -1
          } else {
            this.hdFile.push(formData)
            this.form.hiddenList.push(this.hiddenForm)
          }
          if (this.imgListTemp.length > 0) {
            this.imgList = JSON.parse(JSON.stringify(this.imgListTemp))
          }
          this.imgListTemp = []
          this.fileHdImgList = []
          this.fileVideoList = []
          this.dialogFormVisible = false
          this.hideUpload = false
        } else {
          return false
        }
      })
    },

    // 保存
    confirm() {
      let flag = false
      this.form.situationList.forEach(item => {
        if (!this.validStr(item.SITUATION)) {
          flag = true
          return
        }
      })
      if (flag) {
        this.$message({
          message: '检查情况不能为空',
          type: 'warning'
        })
        return false
      }
      flag = false
      this.form.inspectorList.forEach(item => {
        if (!this.validStr(item.INSPECTION_USER_ID)) {
          flag = true
          return
        }
      })
      if (flag) {
        this.$message({
          message: '检查人员不能为空',
          type: 'warning'
        })
        return false
      }

      this.$refs.form.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '数据保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          for (var x in this.form.inspectorList) {
            var vector = 0
            for (var y in this.form.inspectorList) {
              if (this.form.inspectorList[y].INSPECTION_USER_ID === this.form.inspectorList[x].INSPECTION_USER_ID) vector++
            }
            if (vector > 1) {
              this.$message.error('检查人重复!请检查相关数据')
              loading.close()
              return
            }
          }
          var index = this.form.inspectorList.findIndex(item => { return item.INSPECTION_USER_ID === this.loginUserId })
          if (index < 0) {
            this.form.inspectorList.push(
              {
                INSPECTION_INSPECTOR_ID: '',	// 检查人员主键
                INSPECTION_DEPARTMENT_ID: JSON.parse(sessionStorage.getItem('user')).DEPARTMENT_ID,	// 检查人员部门ID
                INSPECTION_DEPARTMENT_NAME: JSON.parse(sessionStorage.getItem('user')).DEPARTMENT_NAME,
                INSPECTION_USER_ID: JSON.parse(sessionStorage.getItem('user')).USER_ID,		// 检查人员ID
                INSPECTION_USER_INDEX: '',
                INSPECTION_USER_NAME: JSON.parse(sessionStorage.getItem('user')).NAME
              }
            )
          }
          this.$set(this.form, 'INSPECTORJSON', JSON.stringify(this.form.inspectorList))
          this.$set(this.form, 'SITUATIONJSON', JSON.stringify(this.form.situationList))
          this.$set(this.form, 'HIDDENJSON', JSON.stringify(this.form.hiddenList))
          this.listLoading = true
          requestFN(
            '/safetyenvironmental/' + this.dialogType,
            { ...this.form }
          ).then((data) => {
            for (let i = 0; i < data.pd.hiddenList.length; i++) {
              this.uploadImg(this.hdFile[i]['fileHdImgList'], data.pd.hiddenList[i].HIDDEN_ID)
              this.uploadVideo(this.hdFile[i]['fileVideoList'], data.pd.hiddenList[i].HIDDEN_ID)
            }
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.listLoading = false
            loading.close()
            this.goBack()
          }).catch((e) => {
            this.listLoading = false
            loading.close()
          })
        } else {
          return false
        }
      })
    },
    // 上传隐患视频
    uploadVideo(list, HIDDEN_ID) {
      const formData = new FormData()
      for (var i = 0; i < list.length; i++) {
        formData.append('FFILE', list[i])
      }
      formData.append('FOREIGN_KEY', HIDDEN_ID)
      formData.append('TYPE', 102)
      return new Promise((resolve, rejected) => {
        upload(
          '/imgfiles/addVideo',
          formData
        ).then((data) => {
          resolve(true)
        }).catch((e) => {
          this.listLoading = false
          rejected(false)
        })
      })
    },
    // 上传隐患照片
    uploadImg(list, HIDDEN_ID) {
      const formData = new FormData()
      for (var i = 0; i < list.length; i++) {
        formData.append('FFILE', list[i])
      }
      formData.append('FOREIGN_KEY', HIDDEN_ID)
      formData.append('TYPE', 3)
      upload(
        '/imgfiles/add',
        formData
      ).then((data) => {
        if (this.hiddenForm.RECTIFICATIONTYPE == 2) {
          this.saveSuccess()
        } else if (this.hiddenForm.RECTIFICATIONTYPE == 1) {
          // this.$refs.rectifyUpload.submit()
          this.uploadRectifyImg()
        }
      }).catch((e) => {
        this.listLoading = false
      })
    },

    goBack() {
      this.$parent.INSPECTION_ID = ''
      this.$parent.activeName = 'List'
    },
    // 获取整改人列表
    getUserList(DEPARTMENT_ID) {
      if (DEPARTMENT_ID) {
        requestFN(
          '/corpUser/listAll',
          { DEPARTMENT_ID: DEPARTMENT_ID }
        ).then((data) => {
          this.INSPECTED_SITEUSER_List = data.userList
        }).catch((e) => {
        })
      }
    },
    // 获取整改人列表
    getResponsibleUserList(DEPARTMENT_ID) {
    },
    // 获取隐患部位 下拉树
    getHiddenReginTreeList() {
      this.treeLoading = true
      requestFN(
        '/hiddenRegion/gerRegionList',
        {
          parentId: '0',
          DEPARTMENT_ID: this.form.INSPECTED_DEPARTMENT_ID
        }
      ).then((data) => {
        this.treeLoading = false
        this.hiddenPartList = JSON.parse(data.zTreeNodes)
      }).catch((e) => {
        this.treeLoading = false
      })
    },

    // 获取数据字典数据
    getDict: function() {
      requestFN(
        '/dictionaries/listSelectTree',
        {
          DICTIONARIES_ID: '60e6481d96e44a5390ff5c347c4d1ffe' // 检查类型
        }
      ).then((data) => {
        this.inspectionTypeTree = JSON.parse(data.zTreeNodes)
      }).catch((e) => {

      })
      // requestFN(
      //   '/dictionaries/listSelectTree',
      //   {
      //     DICTIONARIES_ID: '5e7cf8620ba54ad89719d0be62133c7a' // 隐患级别
      //   }
      // ).then((data) => {
      //   this.hiddenlevelList = JSON.parse(data.zTreeNodes)
      //   // 屏蔽较大重大隐患
      //   this.hiddenlevelList.forEach((itemFirst, i) => {
      //     itemFirst.nodes.forEach((itemSecond, j) => {
      //       if (itemSecond.DICTIONARIES_ID === 'a9d916b5a17848c1b15e8b821c24bf6e' ||
      //         itemSecond.DICTIONARIES_ID === '39a8c8e95da448868cb8a67118726f09' ||
      //         itemSecond.DICTIONARIES_ID === 'a8e356e008de442c8785c876374d8da7') { // 忽略隐患、较大隐患、重大隐患 第二级
      //         itemFirst.nodes.splice(j, 1)
      //       }
      //     })
      //     if (itemFirst.DICTIONARIES_ID === '5ff9daf78e9a4fb1b40d77980656799d') { // 重大隐患 第一级
      //       this.hiddenlevelList.splice(i, 1)
      //     }
      //   })
      //   console.info(this.hiddenlevelList)
      // })

      requestFN(
        '/dictionaries/listSelectTree',
        {
          DICTIONARIES_ID: '3babc15144444bdc8d763d0af2bdfff6' // 隐患类型1
        }
      ).then((data) => {
        this.hiddenTypeList = JSON.parse(data.zTreeNodes)
      })

      requestFN(
        '/dictionaries/listSelectTree',
        {
          DICTIONARIES_ID: '18c0a9aea6e54feab9f4ab3f46e0bc86' // 隐患类型2
        }
      ).then((data) => {
        this.hiddenType2List = JSON.parse(data.zTreeNodes)
      })

      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: '60e6481d96e44a5390ff5c347c4d1ffe' // 检查类型
        }
      ).then((data) => {
        this.INSPECTION_TYPE_List = data.list
      }).catch((e) => {

      })

      requestFN(
        '/corpDepartment/listTreeCorpDept',
        {}
      ).then((data) => {
        this.treeData = this.listTransTree(JSON.parse(data.zTreeNodes), 'id', 'pId', 'nodes')
      }).catch((e) => {
      })

      requestFN(
        '/corpDepartment/listTreeManageAndCorp',
        {}
      ).then((data) => {
        this.treeDataInspectDept = this.listTransTree(JSON.parse(data.zTreeNodes), 'id', 'pId', 'nodes')
      }).catch((e) => {
      })
    },
    resetForm() {
      this.form = {
        INSPECTION_SUBJECT: '安全', // 检查标题
        INSPECTION_SOURCE: '4', // 检查来源(4-监管端 5-企业端)
        inspectorList: [], // 检查人员
        INSPECTION_ORIGINATOR_ID: '', // 检查发起人
        INSPECTED_DEPARTMENT_ID: '', // 被检查单位
        INSPECTED_SITEUSER_ID: '', // 被检查单位现场负责人
        INSPECTED_EXPLAIN: '', // 申辩内容
        INSPECTED_SITEUSER_SIGN_IMG: '', // 被检查单位现场负责人签字
        INSPECTED_SITEUSER_SIGN_TIME: '', // 被检查单位现场负责人签字时间
        INSPECTION_TYPE: '', // 检查类型
        INSPECTION_TYPE_OTHER: '', // 检查类型(其他)
        INSPECTION_PLACE: '', // 检查场所
        INSPECTION_TIME_START: '', // 检查开始时间
        INSPECTION_TIME_END: '', // 检查结束时间
        INSPECTION_STATUS: '0', // 状态(0.暂存 1.检查人待确认、2.被检查人待确认、3.归档 -1.检查人异议打回 -2被检查人申辩)
        situationList: [], // 检查情况
        hiddenList: [] // 隐患
      }
      this.form.inspectorList.push({ INSPECTION_INSPECTOR_ID: '', INSPECTION_DEPARTMENT_ID: '', INSPECTION_USER_ID: '', USER_SIDE: '' })
      this.INSPECTOR_List.push([])
    },
    resetHd() {
      this.hiddenForm = {
        ISRELEVANT: '2', // 是否相关方
        HIDDEN_ID: '', // 隐患ID
        HIDDENDESCR: '', // 隐患描述
        HIDDENPART: '', // 隐患部位
        HIDDENLEVEL: '', // 隐患级别
        HIDDENTYPE: '', // 隐患类型1
        HIDDENTYPE2: '', // 隐患类型2
        LONGITUDE: '', // 隐患位置经度
        LATITUDE: '', // 隐患位置纬度
        DISCOVERYTIME: '', // 隐患发现时间
        HIDDENFINDDEPT: '', // 隐患发现部门(隐患责任人部门)
        CREATOR: '', // 发现人(隐患责任人)
        SOURCE: '4', // 隐患描述
        POSITIONDESC: ''
      }
      this.hiddenImgs = [] // 隐患照片
      this.fileHdImgList = [] // 隐患图片
      this.fileVideoList = [] // 隐患视频
    },
    chooseMap() { // 弹出地图
      this.dialogMap = true
      this.iframeSrc = config.weburl + 'static/maplocation.html?t=' + Math.random()
    },
    getEditMyInfo() { // 获取登录人信息
      requestFN(
        '/user/goEditMyInfo',
        {}
      ).then((data) => {
        this.loginUserId = data.pd.USER_ID
        this.loginUserName = data.pd.NAME
      }).catch((e) => {
        this.$message.error(e)
      })
    },
    openConfirm() {
      this.$refs.confirm.init()
    },

    // 获取隐患部位 下拉树
    getHiddenReginTreeListData() {
      return new Promise((resolve) => {
        this.treeLoading = true
        requestFN(
          '/hiddenRegion/listAll',
          {}
        ).then((data) => {
          this.treeLoading = false
          this.hiddenPartList = JSON.parse(data.zTreeNodes)
          resolve('ok')
        }).catch((e) => {
          this.treeLoading = false
        })
      })
    },
    getProposal(information) {
      this.form.CONFIRM_MESSAGE = information.INSPECTION_USER_OPINION
      this.form.CONFIRM_MESSAGE_SIGN = information.INSPECTION_USER_SIGN_IMG
      this.form.CONFIRM_MESSAGE_TIME = information.INSPECTION_USER_SIGN_TIME
      this.$forceUpdate()
    }
  }
}

</script>

<style lang="scss" scoped>
  .uo-flex {
    display: flex;
    overflow: auto;
  }
  #infotabs .tabs-panels>.panel>.panel-body {
    overflow: hidden;
  }

  .hide .el-upload--picture-card {
    display: none;
  }

</style>