<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_Inspected"
                :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">
          <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="检查类型">
              <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-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" 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">
                  <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">
                  <el-select v-model="item.INSPECTION_USER_ID" clearable placeholder="请选择检查人员" @change="changeHiddenUserList">
                    <el-option v-for="data in INSPECTOR_List[index]" :key="data.USER_ID" :label="data.NAME" :value="data.USER_ID" />
                  </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>
    </div>

    <!--  添加隐患  -->
    <el-dialog :visible.sync="dialogFormVisible" title="添加隐患" top="1vh">
      <el-form v-if="dialogFormVisible" 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="24">
            <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 :gutter="12" type="flex" justify="space-between">
              <el-col :span="10">
                <el-input
                  id="LONGITUDE"
                  ref="LONGITUDE"
                  v-model="hiddenForm.LONGITUDE"
                  :readonly="true"
                  maxlength="255"
                  placeholder="这里选择隐患经度..."
                  title="隐患位置经度"
                  @focus="chooseMap" />
              </el-col>
              <el-col :span="10">
                <el-input
                  id="LATITUDE"
                  ref="LATITUDE"
                  v-model="hiddenForm.LATITUDE"
                  :readonly="true"
                  maxlength="255"
                  placeholder="这里选择隐患位置纬度..."
                  title="隐患位置经度"
                  @focus="chooseMap" />
              </el-col>
              <el-col :span="4" style="text-align: right">
                <el-button type="primary" icon="el-icon-add-location" plain @click="chooseMap">位置定位</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="隐患位置描述：" prop="POSITIONDESC" >
            <el-row>
              <el-input
                id="POSITIONDESC"
                ref="POSITIONDESC"
                v-model="hiddenForm.POSITIONDESC"
                type="textarea"
                maxlength="255"
                placeholder="请输入隐患位置描述..."
                title="隐患位置描述"/>
            </el-row>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <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">
                <div v-for="(item, index) in hiddenForm.hiddenImgs" :key="index" class="img-div">
                  <img :src="config.fileUrl + item.FILEPATH" alt="">
                  <div class="disContent-hide">
                    <el-tooltip class="item" effect="dark" content="预览" placement="top">
                      <span class="el-icon-zoom-in yuLan">
                        <viewer :images="hiddenForm.hiddenImgs">
                          <img :src="config.fileUrl + item.FILEPATH" alt="" class="yuLanImg">
                        </viewer>
                      </span>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="删除" placement="top">
                      <span class="Delete" @click="delHiddenImg(index)"><i class="el-icon-delete" /></span>
                    </el-tooltip>
                  </div>
                </div>
                <el-upload
                  ref="hiddenUpload"
                  :on-preview="handlePictureCardPreview"
                  :before-upload="hiddenBeforeUpload"
                  :on-change="handleChangeIMG"
                  :on-remove="hiddenRemove"
                  :auto-upload="false"
                  :limit="4"
                  :file-list="imgList"
                  :class="{hide:hiddenPicture}"
                  class="avatar-uploader"
                  action="#"
                  multiple
                  accept=".jpg,.jpeg,.png"
                  list-type="picture-card">
                  <i class="el-icon-plus" />
                </el-upload>
              </div>
              <span class="red-tip">* 最多只能上传四张图片</span>
              <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">
            <div v-if="hiddenForm.hiddenVideos.length > 0">
              <el-form-item label="隐患视频：">
                <div v-for="(data, indexImg) in hiddenForm.hiddenVideos" :key="'hdVideo'+indexImg" class="demo-image__preview" style="float: left; margin-right: 5px">
                  <img
                    src="../../../../assets/images/hidden_video.png"
                    style="width: 100px; height: 100px; cursor: pointer;"
                    @click="goViewVideo(data)"
                  >
                  <i class="el-icon-close" @click="delFujian(indexImg)" />
                </div>
              </el-form-item>
            </div>
            <el-form-item v-else 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="请选择隐患发现人" style="width: 100%;" @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">取 消</el-button>
        <el-button type="primary" @click="saveInspectionHidden">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogMap" :title="'隐患位置'" width="80%" top="8vh">
      <div>
        <iframe :src="iframeSrc" frameborder="0" allowtransparency="true" width="100%" height="600"/>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogViewVideo" title="视频" width="800px" @close="closePlay">
      <div>
        <video-player
          ref="hdVideoPlayer"
          :playsinline="true"
          :options="playerOptions"
          class="video-player vjs-custom-skin"/>
      </div>
    </el-dialog>

    <video id="videoPlayer" controls="controls" crossOrigin="anonymous" style="display: none">
      <source id="videoSource" src="" type="video/mp4">
    </video>
    <canvas id="canvasVideo" style="display: none"/>
    <confirm ref="confirm" @getProposal="getProposal"/>

    <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 { videoPlayer } from 'vue-video-player'
import 'video.js/dist/video-js.css'
import confirm from './confirm'

export default {
  components: { SelectTree, videoPlayer, confirm },
  directives: { waves },
  data() {
    return {
      listLoading: true,
      config: config,
      loginUserId: '',
      loginUserName: '',
      INSPECTED_SITEUSER_List: [],
      inspectionTypeTree: [],
      INSPECTOR_List: [],
      treeData: [],
      treeDataInspectDept: [],
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      pd: [],
      switchInspectionType: 'select',
      form: {
        INSPECTION_SUBJECT: '', // 检查标题
        INSPECTION_SOURCE: '5', // 检查来源（4-监管端 5-企业端）
        inspectorList: [{ INSPECTION_INSPECTOR_ID: '', INSPECTION_DEPARTMENT_ID: '', INSPECTION_USER_ID: '' }], // 检查人员
        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_ORIGINATOR_ID: [{ required: true, message: '检查发起人不能为空', trigger: 'blur' }],
        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: '状态不能为空', trigger: 'blur' }]
      },
      dialogFormVisible: false,
      hiddenDialogType: 'add',
      hiddenForm: {
        ISRELEVANT: '', // 是否相关方
        HIDDEN_ID: '', // 隐患ID
        HIDDENDESCR: '', // 隐患描述
        HIDDENPART: '', // 隐患部位
        HIDDENLEVEL: '', // 隐患级别
        HIDDENTYPE: '', // 隐患类型1
        HIDDENTYPE2: '', // 隐患类型2
        LONGITUDE: '', // 隐患位置经度
        LATITUDE: '', // 隐患位置纬度
        DISCOVERYTIME: '', // 隐患发现时间
        HIDDENFINDDEPT: '', // 隐患发现部门（隐患责任人部门）
        CREATOR: '', // 发现人（隐患责任人）
        SOURCE: '5', // 隐患描述,
        POSITIONDESC: '', // 隐患位置描述
        hiddenImgs: [],
        hiddenVideos: []
      },
      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: '',
      hiddenPicture: false,
      dialogImageUrl: '',
      dialogVisible: false,
      imgList: [{ name: '', url: '' }],
      imgListTemp: [{ name: '', url: '' }],
      fileHdImgList: [], // 隐患图片
      fileVideoList: [], // 隐患视频
      hiddenRules: {
        ISRELEVANT: [{ required: true, message: '是否相关方不能为空', trigger: 'blur' }],
        HIDDENDESCR: [{ required: true, message: '隐患描述不能为空', trigger: 'blur' }],
        HIDDENLEVEL: [{ required: true, message: '隐患级别不能为空', trigger: 'blur' }],
        HIDDENTYPE: [{ required: true, message: '隐患类型不能为空', trigger: 'blur' }],
        HIDDENTYPE2: [{ required: true, message: '隐患类型2不能为空', trigger: 'blur' }],
        DISCOVERYTIME: [{ required: true, message: '隐患发现时间不能为空', trigger: 'blur' }],
        HIDDENFINDDEPT: [{ required: true, message: '隐患发现人部门不能为空', trigger: 'blur' }],
        CREATOR: [{ required: true, message: '隐患发现人不能为空', trigger: 'blur' }]
      },
      dialogViewVideo: false,
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: false, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: 'video/mp4', // 类型
          src: '' // url地址
        }],
        poster: '', // 封面地址
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: true, // 是否显示剩余时间功能
          fullscreenToggle: true // 是否显示全屏按钮
        }
      }
    }
  },
  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

    }
  },
  created() {
    const loading = this.$loading({
      lock: true,
      text: '数据加载中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    this.init(loading)
  },
  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: {
    async init(loading) {
      await this.handleAdd()
      await this.getDict()
      await this.resetForm()
      await this.getDictTreeData()
      await this.getHiddenReginTreeList()
      // await this.getEditMyInfo()
      await this.closeLoading(loading)
    },

    closeLoading(loading) {
      return new Promise((resolve) => {
        loading.close()
        resolve('ok')
      })
    },

    // 添加
    handleAdd() {
      return new Promise((resolve, reject) => {
        this.dialogType = 'add'
        resolve('ok')
      })
    },
    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: '' })
      this.INSPECTOR_List.push([])
    },
    updateInspecteDept(DEPARTMENT_ID, i) {
      this.form.inspectorList[i].INSPECTION_USER_ID = ''
      this.getInspectorList(DEPARTMENT_ID, i)
    },
    // 获取人员列表
    getInspectorList(DEPARTMENT_ID, i) {
      if (DEPARTMENT_ID) {
        requestFN(
          '/user/listAll',
          {
            DEPARTMENT_ID: DEPARTMENT_ID,
            NOMAIN: '1'
          }
        ).then((data) => {
          this.INSPECTOR_List[i] = data.userList
          this.$forceUpdate()
        }).catch((e) => {
        })
      }
    },
    /* 隐患责任人改为充检查人员中选取 */
    changeHiddenUserList(val) {
      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) {
            if (JSON.parse(sessionStorage.getItem('user')).USER_ID !== item.USER_ID) {
              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)
      }
    },

    hiddenPartTypeBtn() {
      this.hiddenForm.HIDDENPART = ''
      this.hiddenPartType = (this.hiddenPartType == 'select') ? 'value' : 'select'
    },

    // 添加检查问题
    addHidden() {
      this.resetHd()
      this.hiddenPicture = false
      this.dialogFormVisible = true
    },

    // 添加/编辑其他隐患
    editInspectionHidden(item, index) {
      this.hiddenCurIndex = index
      this.hiddenForm = JSON.parse(JSON.stringify(this.form.hiddenList[index]))
      // this.fileHdImgList = this.hdFile[index].fileHdImgList
      this.fileVideoList = this.hdFile[index].fileVideoList
      this.dialogFormVisible = true
      console.info(this.imgList)
    },
    // 删除
    removeInspectionHidden(item, index) {
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.hiddenList.splice(index, 1)
        this.hdFile.splice(index, 1)
      }).catch(() => {
      })
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    getEditMyInfo() { // 获取登录人信息
      return new Promise((resolve) => {
        requestFN(
          '/user/goEditMyInfo',
          {}
        ).then((data) => {
          this.loginUserId = data.pd.USER_ID
          this.loginUserName = data.pd.NAME
          resolve('ok')
        }).catch((e) => {

        })
      })
    },
    // 隐患上传
    hiddenBeforeUpload(file) {
      if (this.fileHdImgList.length >= 4) {
        this.$message.error('最多上传4张隐患图片')
      } else {
        this.fileHdImgList.push(file)
      }
    },
    handleChangeIMG(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)
      }
      if (this.$refs.hiddenUpload) {
        this.hiddenPicture = this.$refs.hiddenUpload.uploadFiles.length >= 4
      }
    },
    hiddenRemove() {
      this.hiddenPicture = this.$refs.hiddenUpload.uploadFiles.length >= 4
    },
    // 删除隐患照片
    delHiddenImg(index) {
      this.$confirm('确定要移除该隐患图片吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.hiddenForm.hiddenImgs.splice(index, 1)
      }).catch(() => {
      })
    },
    goViewVideo(row) {
      const type = row.FILEPATH.slice(row.FILEPATH.lastIndexOf('.') + 1)
      this.playerOptions.sources[0].src = this.config.fileUrl + row.FILEPATH
      this.playerOptions.poster = this.config.fileUrl + row.IMGFILEPATH
      this.playerOptions.sources[0].type = 'video/' + type
      this.dialogViewVideo = true
    },
    closePlay() {
      this.$refs.hdVideoPlayer.player.pause()
    },
    delFujian(index) {
      this.$confirm('确定要移除该隐患视频吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delHiddenFiles.push(this.hiddenForm.hiddenVideos[index].FILEPATH)
        this.hiddenForm.hiddenVideos.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
      }
    },
    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
        } 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('检查人重复！请检查相关数据')
              return
            }
          }
          const index = this.form.inspectorList.findIndex(item => item.INSPECTION_USER_ID === JSON.parse(sessionStorage.getItem('user')).USER_ID)
          if (index < 0) {
            this.form.inspectorList.push({ INSPECTION_INSPECTOR_ID: '', INSPECTION_DEPARTMENT_ID: JSON.parse(sessionStorage.getItem('user')).DEPARTMENT_ID, INSPECTION_USER_ID: JSON.parse(sessionStorage.getItem('user')).USER_ID })
          }
          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)
      upload(
        '/imgfiles/addVideo',
        formData
      ).then((data) => {
      }).catch((e) => {
        this.listLoading = 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) => {
      }).catch((e) => {
        this.listLoading = false
      })
    },

    goBack() {
      this.$parent.INSPECTION_ID = ''
      this.$parent.activeName = 'List'
    },
    // 获取整改人列表
    getUserList(DEPARTMENT_ID) {
      if (DEPARTMENT_ID) {
        requestFN(
          '/user/listAll',
          { DEPARTMENT_ID: DEPARTMENT_ID }
        ).then((data) => {
          this.INSPECTED_SITEUSER_List = data.userList
        }).catch((e) => {
        })
      }
    },

    // 获取数据字典数据
    getDict: function() {
      return new Promise((resolve, reject) => {
        // 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)
        //     }
        //   })

        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/listSelectTree',
              {
                DICTIONARIES_ID: '60e6481d96e44a5390ff5c347c4d1ffe' // 检查类型
              }
            ).then((data) => {
              this.inspectionTypeTree = JSON.parse(data.zTreeNodes)
              resolve('ok')
            }).catch((e) => {
            })
          })
        })
      })
      // })
    },
    getDictTreeData() {
      return new Promise((resolve) => {
        requestFN(
          '/department/listzTree',
          {}
        ).then((data) => {
          this.treeData = this.listTransTree(JSON.parse(data.zTreeNodes), 'id', 'pId', 'nodes')
          this.treeDataInspectDept = this.listTransTree(JSON.parse(data.zTreeNodes), 'id', 'pId', 'nodes')
          resolve('ok')
        }).catch((e) => {
        })
      })
    },
    // 获取隐患部位 下拉树
    getHiddenReginTreeList() {
      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
        })
      })
    },
    resetForm() {
      return new Promise((resolve) => {
        this.form = {
          INSPECTION_SUBJECT: '安全', // 检查标题
          INSPECTION_SOURCE: '5', // 检查来源（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_DEPARTMENT_ID: '', INSPECTION_USER_ID: '' })
        this.INSPECTOR_List.push([])
        resolve('ok')
      })
    },
    resetHd() {
      this.hiddenForm = {
        ISRELEVANT: '2', // 是否相关方
        HIDDEN_ID: '', // 隐患ID
        HIDDENDESCR: '', // 隐患描述
        HIDDENPART: '', // 隐患部位
        HIDDENLEVEL: '', // 隐患级别
        HIDDENTYPE: '', // 隐患类型1
        HIDDENTYPE2: '', // 隐患类型2
        LONGITUDE: '', // 隐患位置经度
        LATITUDE: '', // 隐患位置纬度
        DISCOVERYTIME: '', // 隐患发现时间
        HIDDENFINDDEPT: '', // 隐患发现部门（隐患责任人部门）
        CREATOR: '', // 发现人（隐患责任人）
        SOURCE: '5', // 隐患描述
        hiddenImgs: [],
        hiddenVideos: []
      }
      this.imgList = []
      this.fileHdImgList = [] // 隐患图片
      this.fileVideoList = [] // 隐患视频
    },
    chooseMap() { // 弹出地图
      this.dialogMap = true
      this.iframeSrc = this.config.weburl + 'static/maplocation.html?t=' + Math.random()
    },
    openConfirm() {
      this.$refs.confirm.init()
    },
    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;
  }
</style>
