<template>
  <div class="app-container">
    <div>
      <el-button icon="el-icon-arrow-left" @click="goBack">返回</el-button>
    </div>
    <el-form label-width="100px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="关键词">
            <el-input v-model="KEYWORDS" placeholder="视频名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label-width="10px">
            <el-button v-waves type="primary" icon="el-icon-search" @click="getQuery">
              搜索
            </el-button>
            <el-button type="success" icon="el-icon-view" size="mini" @click="getReset">
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table
      v-loading="listLoading"
      ref="multipleTable"
      :row-key="getRowKey"
      :data="varList"
      :header-cell-style="{
        'font-weight': 'bold',
        'color': '#000'
      }"
      tooltip-effect="dark"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        :reserve-selection="true"
        type="selection"
        width="55"
        align="center"/>
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="SOURCE_NAME" label="报警源名称" align="center"/>
      <el-table-column prop="SOURCE_VALUE" label="报警值" align="center"/>
      <el-table-column prop="ALARM_PEOPLE_NAME" label="报警处理人" align="center"/>
      <el-table-column prop="ALARM_AREA" label="报警区域" align="center"/>
      <el-table-column prop="ALARM_TIME" label="报警时间" align="center"/>
      <el-table-column prop="IS_ALARM" label="是否报警信息" align="center">
        <template slot-scope="{row}">
          {{ row.IS_ALARM === '0' || row.IS_ALARM == null ? '未核定' : row.IS_ALARM === '1'? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column prop="VIDEO_COUNT" label="视频数" align="center"/>
      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="{row}">
          <el-button type="success" icon="el-icon-search" size="mini" @click="viewNearbyCameras(row)">查看附近摄像头</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <div/>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>

    <el-dialog :visible.sync="dialogFormMap" title="定位" width="1050px" class="dy-dialog">
      <div id="map" />
      <div slot="footer" class="dialog-footer">
        <span>经度:</span>
        <el-input v-model="addForm.info.LONGITUDE" style="width: 200px" placeholder="请输入内容" disabled />
        <span>纬度:</span>
        <el-input v-model="addForm.info.LATITUDE" style="width: 200px" placeholder="请输入内容" disabled />
        <el-button @click="dialogFormMap = false">取 消</el-button>
        <el-button type="primary" @click="setPosition()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="addForm.dialogVisible" :title="addForm.dialogType==='add'?'新增':'编辑'" width="500px">
      <el-form ref="addForm" :model="addForm.info" :rules="addForm.rules" label-width="110px">
        <el-form-item label="是否报警信息:" prop="IS_ALARM">
          <el-select v-model="addForm.info.IS_ALARM" placeholder="请选择">
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.name"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <div v-if="addForm.info.IS_ALARM === '2'">
          <el-form-item label="原因:" prop="REASON">
            <el-input v-model="addForm.info.REASON" style="width:206px" placeholder="请输入原因"/>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="back">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-if="dialogVideo" :visible.sync="dialogVideo" :show-close="false" title="视频2" width="600px">
      <iframe :src="VIDEOURL" width="100%" height="380" allowfullscreen allow="autoplay; fullscreen;microphone" style="position: relative;border:none"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="back">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog v-if="dialogVideoHLS" :visible.sync="dialogVideoHLS" :before-close="handleBack" :show-close="false" title="视频" width="600px">
      <div id="aLiVideoPlayer" class="prism-player"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="back">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog v-if="dialogVideoAll" :visible.sync="dialogVideoAll" :before-close="handleBack" title="视频" width="1200px">
      <!--      <iframe src="http://192.168.192.121:10800/?menu=no/#/screen" width="100%" height="500px" allowfullscreen allow="autoplay; fullscreen" style="position: relative;border:none"/>-->
      <div style="display: flex;flex-wrap: wrap;justify-content: space-between">
        <div v-for="(video,index) in videoList" :key="index" style="margin-bottom: 10px;width: 45%">
          <div v-if="video.HLSVIDEOURL" :id="'aLiVideoPlayer'+index" class="prism-player"/>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="back">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
import TiandiMap from '../../../../components/TianMap/TiandiMap'
import SelectTree from '@/components/SelectTree'

export default {
  components: { Pagination, TiandiMap, SelectTree },
  directives: { waves },
  data() {
    return {
      map: null,
      marker: null,
      BMap: '',
      clientHeight: 500,
      inputLocation: '',
      msg: 'add',
      config: config,
      listLoading: true,
      dialogForm: false,
      dialogImageUrl: '',
      dialogVisible: false,
      dialogSelect: false,
      add: true,
      del: true,
      edit: true,
      dialogFormMap: false,
      listQuery: {
        page: 1,
        limit: 20
      },
      total: 0,
      typeList: [{ name: '是', value: '1' }, { name: '否', value: '2' }],
      KEYWORDS: '',
      dates: [],
      varList: [],
      LATITUDE: '',
      LONGITUDE: '',
      zoom: 10,
      rules: {
        VIDEONAME: [{ required: true, message: '视频名称不能为空', trigger: 'blur' }],
        CODE: [{ required: true, message: '摄像头编号不能为空', trigger: 'blur' }]
      },
      dialogVideo: false,
      dialogVideoHLS: false,
      dialogVideoBack: false,
      dialogVideoAll: false,
      treeDataInspectDept: [],
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      INSPECTOR_List: [],
      RESPONSIBLE_USER_List: [{ NAME: JSON.parse(sessionStorage.getItem('user')).NAME, USER_ID: JSON.parse(sessionStorage.getItem('user')).USER_ID }], // 隐患责任人
      addForm: {
        dialogType: 'add', // 增or改
        dialogVisible: false,
        rules: {
          LONGITUDE: [{ required: true, message: '不可为空', trigger: 'blur' }],
          LATITUDE: [{ required: true, message: '不可为空', trigger: 'blur' }],
          RECIPIENT: [{ required: true, message: '不可为空', trigger: 'blur' }],
          TYPE: [{ required: true, message: '不可为空', trigger: 'blur' }]
        },
        info: {
          ALARMINFORMATION_ID: '',
          ALARMDEVICEMAINTENANCE_ID: '',
          ALARM_TIME: '',
          ALARM_AREA: '',
          LONGITUDE: '',
          LATITUDE: '',
          IS_ALARM: '',
          REASON: ''
        }
      }
    }
  },
  created() {
    this.getList()
    this.getDict()
  },
  methods: {
    clearAddform() {
      console.log(66666)
      this.addForm.info.ALARM_TIME = ''
    },
    // 获取人员列表
    getInspectorList(DEPARTMENT_ID, i) {
      if (DEPARTMENT_ID) {
        requestFN(
          '/user/listAllManageAndCorp',
          {
            CURRENT_INSPECTED_DEPARTMENT_ID: this.CURRENT_INSPECTED_DEPARTMENT_ID,
            DEPARTMENT_ID: DEPARTMENT_ID,
            NOMAIN: '1'
          }
        ).then((data) => {
          this.INSPECTOR_List[i] = data.userList
          this.$forceUpdate()
        }).catch((e) => {
        })
      }
    },
    updateInspecteDept(id, i, item) {
      // 获取人员列表
      if (id) {
        requestFN(
          '/user/listAllManageAndCorp',
          {
            DEPARTMENT_ID: id
          }
        ).then((data) => {
          this.INSPECTOR_List[i] = data.userList
          this.$forceUpdate()
        }).catch((e) => {
        })
      }
      this.addForm.info.inspectorList[i].INSPECTION_USER_ID = ''
      this.addForm.info.inspectorList[i].USER_SIDE = ''
      this.getInspectorList(DEPARTMENT_ID, i)
    },
    // 删除接受报警人
    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.addForm.info.inspectorList.splice(index, 1)
          this.INSPECTOR_List.splice(index, 1)
        }).catch(() => {
        })
      } else {
        this.addForm.info.inspectorList.splice(index, 1)
        this.INSPECTOR_List.splice(index, 1)
      }
    },
    addInspector() {
      console.log(this.addForm.info.inspectorList)
      this.addForm.info.inspectorList.push({ INSPECTION_INSPECTOR_ID: '', INSPECTION_DEPARTMENT_ID: '', INSPECTION_USER_ID: '', USER_SIDE: '' })
      this.INSPECTOR_List.push([])
    },
    /* 改为从接受报警人中选取 */
    changeHiddenUserList(item, data) {
      item.USER_SIDE = data.USER_SIDE
      for (let i = 0; i < this.addForm.info.inspectorList.length; i++) {
        this.INSPECTOR_List[i].forEach(item => {
          if (this.addForm.info.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)
            }
          }
        })
      }
    },
    // 搜索
    getReset() {
      this.KEYWORDS = ''
      this.listQuery = {
        page: 1,
        limit: 20
      }
      this.total = 0
      this.getQuery()
    },
    /**
     * 初始化天地图对象
     */
    initTDT() {
      return new Promise((resolve, reject) => {
        if (window.T) {
          console.log('天地图初始化成功...')
          resolve(window.T)
          reject('error')
        }
      }).then(T => {
        window.T = T
      })
    },
    /**
     * 初始化地图
     * @param {*} lng 经度
     * @param {*} lat 纬度
     * @param {*} zoom 缩放比例(1~18)
     */
    initMap(lng, lat, zoom) {
      this.initTDT().then((T) => {
        const imageURL = 'http://t0.tianditu.gov.cn/img_w/wmts?' + 'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' + '&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=e8a16137fd226a62a23cc7ba5c9c78ce'
        // 创建自定义图层对象
        this.lay = new window.T.TileLayer(imageURL, { minZoom: 1, maxZoom: 18 })
        // 初始化地图对象
        this.map = new window.T.Map('map')
        this.initCenter(lng, lat, zoom)
      })
    },
    initCenter(lng, lat, zoom) {
      // 设置显示地图的中心点和级别
      if (!this.addForm.info.LONGITUDE && !this.addForm.info.LATITUDE) {
        this.map.centerAndZoom(new window.T.LngLat(119.58, 39.94), zoom)
        this.marker && this.map.removeOverLay(this.marker)
      } else {
        this.map.centerAndZoom(new window.T.LngLat(lng, lat), zoom)
        this.marker && this.map.removeOverLay(this.marker)
        this.addForm.info.LONGITUDE = lng
        this.addForm.info.LATITUDE = lat
        this.marker = new window.T.Marker(new window.T.LngLat(lng, lat))
        // 向地图上添加标注
        this.map.addOverLay(this.marker)
      }
      // 创建卫星和路网的混合视图
      this.map.setMapType(window.TMAP_HYBRID_MAP)
      // 允许鼠标滚轮缩放地图
      this.map.enableScrollWheelZoom()
      // 允许鼠标移动地图
      this.map.enableInertia()
      // 向地图上添加标注
      this.map.addEventListener('click', this.MapClick)
    },
    MapClick(event) {
      this.marker && this.map.removeOverLay(this.marker)
      this.addForm.info.LONGITUDE = event.lnglat.getLng()
      this.addForm.info.LATITUDE = event.lnglat.getLat()
      this.marker = new window.T.Marker(new window.T.LngLat(event.lnglat.getLng(), event.lnglat.getLat()))
      // 向地图上添加标注
      this.map.addOverLay(this.marker)
    },
    handleMap(row) {
      this.dialogFormMap = true
      this.$nextTick(() => {
        if (!this.map) this.initMap(this.addForm.info.LONGITUDE, this.addForm.info.LATITUDE, 16)
        else this.initCenter(this.addForm.info.LONGITUDE, this.addForm.info.LATITUDE, 16)
      })
    },
    getRowKey(row) {
      return row.ALARMINFORMATION_ID
    },
    goBack() {
      this.$parent.activeName = 'list'
    },
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    setPosition() {
      this.addForm.info.LONGTITUDEANDLATITUDE = this.addForm.info.LONGITUDE + '--' + this.addForm.info.LATITUDE
      this.dialogFormMap = false
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/alarmInformation/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          ALARMDEVICEMAINTENANCE_ID: this.$parent.ALARMDEVICEMAINTENANCE_ID
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
      }).catch((e) => {
        this.listLoading = false
      })
    },

    // 添加
    handleAdd() {
      this.resetAddForm()
      this.addForm.dialogType = 'add'
      this.addForm.dialogVisible = true
    },

    viewNearbyCameras(row) {
      this.$parent.activeName = 'videoList'
      this.$parent.ALARMINFORMATION_ID = row.ALARMINFORMATION_ID
      this.$parent.LONGITUDE = row.LONGITUDE
      this.$parent.LATITUDE = row.LATITUDE
    },

    resetAddForm() {
      this.ALARMDEVICEMAINTENANCE_ID = ''
      this.addForm.info = {
        ALARMDEVICEMAINTENANCE_ID: '',
        inspectorList: [{ INSPECTION_INSPECTOR_ID: '', INSPECTION_DEPARTMENT_ID: '', INSPECTION_USER_ID: '', USER_SIDE: '' }], // 接受报警人
        INDICATORSOURCE: '',
        ALARMTHRESHOLD: '',
        RECIPIENT: '',
        TYPE: '',
        LATITUDE: '',
        LONGITUDE: ''
      }
      this.addForm.dialogType = ''
    },
    confirm() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          requestFN(
            '/alarmInformation/' + this.addForm.dialogType,
            {
              ...this.addForm.info
            }
          ).then((data) => {
            this.$message.success('保存成功')
            this.getList()
            this.addForm.dialogVisible = false
          }).catch((e) => {
          })
        } else {
          return false
        }
      })
    },
    handleDelete(id) {
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/alarmInformation/delete',
          {
            ALARMINFORMATION_ID: id
          }
        ).then((data) => {
          if (data.result === 'success') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          } else {
            this.$message.error(data.msg)
          }
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    batchDel() {
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length == 0) {
        this.$message({
          message: '请选中要删除的项...',
          type: 'error'
        })
        return false
      }
      const ids = _selectData.map((item, index) => {
        return item.GATEVIDEO_ID
      }).join(',')

      this.$confirm('确定要删除选中的数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/gateVideo/deleteAll',
          {
            DATA_IDS: ids
          }
        ).then(() => {
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.$refs.multipleTable.clearSelection()
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    goKeyReset() {
      this.KEYWORDS = ''
      this.getList()
    },

    back() {
      if (this.addForm.dialogVisible) this.addForm.dialogVisible = false
      if (this.dialogVideo) this.dialogVideo = false
      if (this.dialogVideoBack) this.dialogVideoBack = false
      if (this.dialogVideoAll) {
        this.dialogVideoAll = false
        for (let i = 0; i < this.playerList.length; i++) {
          this.playerList[i].dispose()
        }
      }
      if (this.dialogForm) this.dialogForm = false
      if (this.dialogVideoHLS) {
        this.dialogVideoHLS = false
        this.player.dispose()
      }
    },
    // 获取数据字典数据
    getDict: function() {
      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) => {
      })
    }
  }
}

</script>
<style>
.ui-foot-xuan {
  width: 100%;
  margin-top: 10px;
  position: inherit;
  height: 60px;
  line-height: 60px;
  background-color: #f1f1f1;
  text-align: center;
}
#map{
  width: 1000px;
  height: 500px;
}
</style>