<template>
  <div>
    <div class="app-container">
      <div class="dialogContent mb-20">
        <div class="level-title">
          <h1>隐患信息</h1>
        </div>
        <div class="mb-20">
          <table class="table-ui">
            <tr>
              <td class="tbg">隐患描述</td>
              <td colspan="3">{{ form.HIDDENDESCR }}</td>
            </tr>
            <tr>
              <td class="tbg">隐患发现人</td>
              <td>{{ form.CREATORNAME }}</td>
              <td class="tbg">隐患级别</td>
              <td>{{ form.HIDDENLEVELNAME }}</td>
            </tr>
            <tr>
              <td class="tbg">隐患发现时间</td>
              <td>{{ form.DISCOVERYTIME }}</td>
              <td class="tbg">隐患部位</td>
              <td>{{ form.hregionName?form.hregionName:form.HIDDENPART }}</td>
            </tr>
            <tr>
              <td class="tbg">隐患位置描述</td>
              <td>{{ form.POSITIONDESC }}</td>
              <td class="tbg">是否是相关方</td>
              <td>{{ form.ISRELEVANT ==='1'?'是':'否' }}</td>
            </tr>
            <tr>
              <td class="tbg">隐患类型</td>
              <td>{{ form.HIDDENTYPENAME }}</td>
            </tr>
            <tr>
              <td class="tbg">隐患位置</td>
              <td colspan="3">
                <el-button icon="el-icon-place" circle @click="showMap(form)" />
                <span>
                  经度:{{ form.LONGITUDE }} , 纬度:{{ form.LATITUDE }}
                </span>
              </td>
            </tr>
            <tr>
              <td class="tbg">隐患图片</td>
              <td colspan="3">
                <div v-for="(data, index) in form.hiddenImgs" :key="'hdImg'+index" class="demo-image__preview" style="float: left; margin-right: 5px">
                  <el-image
                    :src="config.fileUrl + data.FILEPATH"
                    :preview-src-list="new Array(config.fileUrl + data.FILEPATH)"
                    style="width: 100px; height: 100px"/>
                </div>
              </td>
            </tr>
            <tr v-if="form.hiddenVideos">
              <td class="tbg">隐患视频</td>
              <td colspan="3">

                <div v-for="(data, index) in form.hiddenVideos" :key="'hdVideo'+index" class="demo-image__preview" style="float: left; margin-right: 5px">
                  <el-button icon="el-icon-video-camera" circle @click="goViewVideo(data)"/>
                </div>
              </td>
            </tr>
          </table>
        </div>

        <el-form ref="form" :rules="formRule" :model="form" label-width="0px">
          <div class="level-title">
            <h1>隐患确认</h1>
          </div>
          <div class="mb-20">
            <table class="table-ui">
              <tr v-if="state === '-2'">
                <td class="tbg">隐患确认人</td>
                <td>
                  <el-form-item prop="CONFIRM_USER" style="margin-top: 10px;margin-bottom: 10px">
                    <el-select v-model="form.CONFIRM_USER" placeholder="请选择">
                      <el-option v-for="item in confirmUserList" :key="item.USER_ID" :label="item.NAME" :value="item.USER_ID" />
                    </el-select>
                  </el-form-item>
                </td>
              </tr>
              <tr v-else>
                <td class="tbg">隐患确认人</td>
                <td colspan="3">{{ form.conUserName }}</td>
              </tr>
            </table>
          </div>
        </el-form>
      </div>

      <el-dialog :visible.sync="dialogMap" :title="'隐患位置'" width="80%">
        <div>
          <iframe id="iframe" ref="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"/>

      <div class="ui-height" />
      <div class="ui-foot">
        <el-button type="primary" @click="confirm">保 存</el-button>
        <el-button plain type="info" @click="goBack">返 回</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { requestFN } from '@/utils/request'
import dateformat from '@/utils/dateformat'
import SelectTree from '@/components/SelectTree'
import { videoPlayer } from 'vue-video-player'
import 'video.js/dist/video-js.css'

export default {
  components: { SelectTree, videoPlayer },
  data() {
    return {
      listLoading: true,
      config: config,
      iframeSrc: '',
      dialogMap: false,
      state: this.$parent.HIDDEN_STATUS,
      treeData: [],
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      confirmUserList: [], // 隐患确认人
      rectifyUserList: [], // 隐患整改人
      acceptUserList: [], // 验收人
      form: {
        HIDDENDESCR: '', // 隐患描述
        CREATORNAME: '', // 隐患责任人
        HIDDENLEVELNAME: '', // 隐患级别
        DISCOVERYTIME: '', // 隐患发现时间
        hregionName: '', // 隐患部位
        HIDDENPART: '',
        HIDDENTYPENAME: '', // 隐患类型1
        HIDDENTYPENAME2: '', // 隐患类型2
        LONGITUDE: '', // 隐患坐标经度
        LATITUDE: '', // 隐患坐标纬度
        hiddenImgs: [], // 隐患图片
        hiddenVideos: [], // 隐患视频

        CONFIRM_USER: '', // 隐患确认人
        conUserName: '',

        RECTIFICATIONTYPE: '2', // 隐患处置
        RECTIFICATIONDEADLINE: '', // 整改期限
        RECTIFICATIONDEPT: '', // 隐患整改人部门
        RECTIFICATIONDEPTNAME: '',
        RECTIFICATIONOR: '', // 隐患整改人
        RECTIFICATIONORNAME: '',
        CHECKDEPT: '', // 验收部门
        CHECKDEPTNAME: '',
        CHECKOR: '', // 验收人
        CHECKORNAME: '',
        HIDDEN_ID: '',
        POSITIONDESC: '',
        ISRELEVANT: ''
      },
      formRule: {
        CONFIRM_USER: [{ 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.RECTIFICATIONDEPT': {
      handler: function(newVal, oldVal) {
        this.form.RECTIFICATIONOR = ''
        this.getReUserList(newVal)
      }
    }

  },
  created() {
    this.iframeSrc = this.config.weburl + 'static/mapshow.html?t=' + Math.random()
  },
  async mounted() {
    this.getConfirmUserList()
    await this.getTreeList()
    await this.getData()
  },
  methods: {
    formatTime(date, column) {
      if (date) {
        return dateformat(date, 'YYYY年MM月DD日HH时mm分')
      } else {
        return ''
      }
    },
    getData() {
      return new Promise((resolve) => {
        requestFN(
          '/hidden/goEdit',
          {
            HIDDEN_ID: this.$parent.HIDDEN_ID
          }
        ).then((data) => {
          console.info(data.pd)
          this.form = Object.assign(this.form, data.pd) // copy obj
          this.form.hiddenImgs = data.hImgs
          this.form.hiddenVideos = data.hiddenVideo
          this.form.hiddenList.forEach(item => {
            if (item.hiddenVideos.length > 0) {
              this.$set(item.hiddenVideos[0], 'IMGFILEPATH', this.findvideocover(item.hiddenVideos[0]))
            }
          })
          this.listLoading = false
          console.info(this.form)
          resolve()
        }).catch((e) => {
          this.listLoading = false
        })
      })
    },
    findvideocover(item) {
      const source = document.getElementById('videoSource') // 获取视频对象
      source.src = this.config.fileUrl + item.FILEPATH
      const video = document.getElementById('videoPlayer')
      video.currentTime = 1 // 第一帧
      video.load()
      var canvas = document.getElementById('canvasVideo') // 获取 canvas 对象
      video.oncanplay = () => {
        // 利用canvas对象方法绘图
        canvas.getContext('2d').drawImage(video, 0, 0, video.clientWidth, video.clientHeight)
        // 转换成base64形式
        item.IMGFILEPATH = canvas.toDataURL('image/png') // 截取后的视频封面
      }
    },
    // 部门
    getTreeList() {
      return new Promise((resolve) => {
        requestFN(
          '/department/listTree',
          {}
        ).then((data) => {
          this.treeData = JSON.parse(data.zTreeNodes)

          resolve()
        }).catch((e) => {
        })
      })
    },
    getConfirmUserList() { // 根据选择的隐患确认部门显示隐患确认人
      this.listLoading = true
      requestFN(
        '/user/getHiddenConfirm',
        {
          tm: new Date().getTime(),
          IS_HAZARDCONFIRMER: '1'
        }
      ).then((data) => {
        this.confirmUserList = data.userList
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 获取整改人列表
    getReUserList(DEPARTMENT_ID) {
      if (DEPARTMENT_ID) {
        requestFN(
          '/user/listAll',
          { DEPARTMENT_ID: DEPARTMENT_ID }
        ).then((data) => {
          this.rectifyUserList = data.userList
        }).catch((e) => {
        })
      }
    },
    // 修改其他检查人部门
    updateOtherDep(DEPARTMENT_ID, i) {
      this.form.CHECKOR = ''
      this.getUserList(DEPARTMENT_ID, i)
    },
    getUserList(DEPARTMENT_ID, index) {
      this.listLoading = true
      requestFN(
        '/user/listAll',
        {
          DEPARTMENT_ID: DEPARTMENT_ID,
          tm: new Date().getTime()
        }
      ).then((data) => {
        this.acceptUserList = data.userList
      }).catch((e) => {
        this.listLoading = false
      })
    },

    // 保存
    confirm() {
      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)'
          })
          this.listLoading = true
          requestFN(
            '/safetyenvironmental/V2/assign',
            { ...this.form,
              HIDDEN_STATUS: this.$parent.HIDDEN_STATUS,
              INSPECTION_ID: this.$parent.INSPECTION_ID
            }
          ).then((data) => {
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.listLoading = false
            loading.close()
            this.goBack()
          }).catch((e) => {
            this.listLoading = false
            loading.close()
          })
        } else {
          return false
        }
      })
    },
    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()
    },
    showMap(obj) {
      this.dialogMap = true
      this.iframeSrc = this.config.weburl + 'static/mapshow.html?t=' + Math.random()
      this.$nextTick(() => {
        const iframe = document.querySelector('#iframe')
        // 处理兼容行问题
        if (iframe.attachEvent) {
          iframe.attachEvent('onload', function() {
            this.contentWindow.postMessage(
              {
                'name': obj.HIDDENDESCR,
                'longitude': Number(obj.LONGITUDE),
                'latitude': Number(obj.LATITUDE)
              }, '*')
          })
        } else {
          iframe.onload = function() {
            this.contentWindow.postMessage(
              {
                'name': obj.HIDDENDESCR,
                'longitude': Number(obj.LONGITUDE),
                'latitude': Number(obj.LATITUDE)
              }, '*')
          }
        }
      })
    },
    goBack() {
      this.$parent.HIDDEN_ID = ''
      this.$parent.HIDDEN_STATUS = ''
      this.$parent.activeName = 'HiddenList'
    }
  }
}
</script>

<style scoped>
</style>
