<template>
  <div class="app-container">
    <el-form label-width="100px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="关键字搜索">
            <el-input v-model="KEYWORDS" placeholder="搜索摄像头名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="10px">
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getQuery">
              搜索
            </el-button>
            <el-button v-waves class="filter-item" type="success" icon="el-icon-refresh" @click="goKeyReset">
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table
      v-loading="listLoading"
      ref="multipleTable"
      :data="varList"
      :row-key="getRowKey"
      :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="name" label="视频名称" />
      <el-table-column prop="regionName" label="区域" />
      <el-table-column prop="POSITION" label="状态" width="100">
        <template slot-scope="{row}">
          <span v-if="row.LATITUDE && row.LONGITUDE">已定位</span>
          <span v-else>未定位</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="400">
        <template slot-scope="{row}">
          <el-button v-show="!row.PLATFORMVIDEOMANAGEMENT_ID" type="success" icon="el-icon-edit" size="mini" @click="handleIn(row)">加入</el-button>
          <el-button type="success" icon="el-icon-caret-right" size="mini" @click="showVideo(row)">播放</el-button>
          <el-button type="warning" size="mini" @click="getRTSP(row)">获取rtsp地址</el-button>
          <el-button type="info" icon="el-icon-location-information" size="mini" @click="handleMap(row)">定位</el-button>
          <el-button v-show="row.LATITUDE && row.LONGITUDE" type="danger" icon="el-icon-delete" size="mini" @click="handleDel(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 v-if="dialogVideoHLS" :visible.sync="dialogVideoHLS" :before-close="handleBack" 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 :visible.sync="dialogFormMap" title="定位" width="1050px" class="dy-dialog">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="所属企业" prop="CORPINFO_ID">
          <el-select v-model="form.CORPINFO_ID" placeholder="请选择申请状态" clearable >
            <el-option v-for="item in corpList" :key="item.CORPINFO_ID" :label="item.CORP_NAME" :value="item.CORPINFO_ID" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div id="map" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <span>经度：</span>
        <el-input v-model="form.LONGITUDE" style="width: 200px" placeholder="请输入内容" disabled />
        <span>纬度：</span>
        <el-input v-model="form.LATITUDE" style="width: 200px" placeholder="请输入内容" disabled />
        <el-button @click="dialogFormMap = false">取 消</el-button>
        <el-button type="primary" @click="setPosition">确 定</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'
export default {
  components: { Pagination, TiandiMap },
  directives: { waves },
  data() {
    // eslint-disable-next-line no-unused-vars
    return {
      map: null,
      marker: null,
      BMap: '',
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      total: 0,
      KEYWORDS: '',
      tempList: [],
      varList: [],
      dialogVideoHLS: false,
      player: {},
      dialogFormMap: false,
      corpList: [],
      form: {},
      rules: {
        CORPINFO_ID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ]
      }
    }
  },
  async created() {
    this.getCorpList()
    await this.getAllList()
    this.getList()
  },
  methods: {
    getRowKey(row) {
      return row.PERSONNELMANAGEMENT_ID
    },

    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.listQuery.page = 1
      this.getList()
    },
    goKeyReset() {
      this.KEYWORDS = ''
      this.getQuery()
    },

    getCorpList() {
      requestFN(
        '/corpinfo/listAll',
        {}
      ).then((data) => {
        this.corpList = data.varList
      }).catch((e) => {
      })
    },

    getAllList() {
      return new Promise(resolve => {
        requestFN(
          '/platformvideomanagement/listAll',
          { }
        ).then((data) => {
          this.tempList = data.varList
          resolve()
        }).catch((e) => {
        })
      })
    },

    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/platformvideomanagement/platformList',
        {
          'pageNo': this.listQuery.page,
          'pageSize': this.listQuery.limit,
          'name': this.KEYWORDS
        }
      ).then((res) => {
        this.listLoading = false
        const tempList = res.data.list
        tempList.forEach(item => {
          for (let i = 0; i < this.tempList.length; i++) {
            if (item.indexCode === this.tempList[i].INDEXCODE) {
              console.log(item.indexCode === this.tempList[i].INDEXCODE)
              item.PLATFORMVIDEOMANAGEMENT_ID = this.tempList[i].PLATFORMVIDEOMANAGEMENT_ID
              item.LONGITUDE = this.tempList[i].LONGITUDE
              item.LATITUDE = this.tempList[i].LATITUDE
              item.CORPINFO_ID = this.tempList[i].CORPINFO_ID
            }
          }
        })
        this.varList = tempList
        console.log(tempList)
        this.total = res.data.total
      }).catch((e) => {
        this.listLoading = false
      })
    },

    handleIn(row) {
      this.$confirm('确认将[' + row.name + ']加入系统吗', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/platformvideomanagement/add',
          {
            INDEXCODE: row.indexCode,
            REGIONINDEXCODE: row.regionIndexCode,
            EXTERNALINDEXCODE: row.externalIndexCode,
            NAME: row.name,
            CAMERATYPE: row.cameraType,
            CASCADECODE: row.cascadeCode,
            DECODETAG: row.decodeTag,
            RESOURCETYPE: row.resourceType,
            CREATETIME: row.createTime,
            UPDATETIME: row.updateTime,
            SORT: row.sort,
            DISORDER: row.disOrder,
            RECORDLOCATION: row.recordLocation,
            CASCADETYPE: row.cascadeType,
            REGIONNAME: row.regionName,
            REGIONPATH: row.regionPath,
            REGIONPATHNAM: row.regionPathName
          }
        ).then(() => {
          this.$message({
            message: '加入成功',
            type: 'success'
          })
          this.listLoading = false
          this.allCodes.push(row.indexCode)
          this.varList = []
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },

    setPosition() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.dialogFormMap = false
          this.listLoading = true
          requestFN(
            '/platformvideomanagement/savePosition',
            this.form
          ).then(async(data) => {
            await this.getAllList()
            this.getList()
          }).catch((e) => {
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },

    // 播放
    showVideo(row) {
      requestFN(
        '/platformvideomanagement/getHlsPath',
        {
          INDEXCODE: row.indexCode
        }
      ).then((res) => {
        this.dialogVideoHLS = true
        this.$nextTick(() => {
          // eslint-disable-next-line no-undef
          this.player = new Aliplayer({
            'id': 'aLiVideoPlayer',
            'source': res.data.url,
            'width': '100%',
            'height': '500px',
            'autoplay': true,
            'isLive': true,
            'rePlay': false,
            'playsinline': true,
            'preload': true,
            'controlBarVisibility': 'hover',
            'useH5Prism': true
          }, function(player) {
            console.log('The player is created')
          })
        })
      }).catch((e) => {
      })
    },
    getRTSP(row) {
      requestFN(
        '/platformvideomanagement/getRtspPath',
        {
          INDEXCODE: row.indexCode
        }
      ).then((res) => {
        this.notify(res.data.url)
      }).catch((e) => {
        this.listLoading = false
      })
    },
    handleDel(row) {
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/platformvideomanagement/delLocation',
          {
            PLATFORMVIDEOMANAGEMENT_ID: row.PLATFORMVIDEOMANAGEMENT_ID
          }
        ).then(async(res) => {
          // this.dialogVideoHLS = true
          this.getList()
          await this.getAllList()
        }).catch((e) => {
        })
      }).catch(() => {
      })
    },
    handleMap(row) {
      this.dialogFormMap = true
      this.form = {
        PLATFORMVIDEOMANAGEMENT_ID: row.PLATFORMVIDEOMANAGEMENT_ID,
        CORPINFO_ID: row.CORPINFO_ID,
        INDEXCODE: row.indexCode,
        REGIONINDEXCODE: row.regionIndexCode,
        EXTERNALINDEXCODE: row.externalIndexCode,
        NAME: row.name,
        LONGITUDE: row.LONGITUDE,
        LATITUDE: row.LATITUDE,
        CAMERATYPE: row.cameraType,
        CASCADECODE: row.cascadeCode,
        DECODETAG: row.decodeTag,
        RESOURCETYPE: row.resourceType,
        CREATETIME: row.createTime,
        UPDATETIME: row.updateTime,
        SORT: row.sort,
        DISORDER: row.disOrder,
        RECORDLOCATION: row.recordLocation,
        CASCADETYPE: row.cascadeType,
        REGIONNAME: row.regionName,
        REGIONPATH: row.regionPath,
        REGIONPATHNAM: row.regionPathName
      }
      this.$nextTick(() => {
        if (!this.map) this.initMap(this.form.LONGITUDE, this.form.LATITUDE, 16)
        else this.initCenter(this.form.LONGITUDE, this.form.LATITUDE, 16)
      })
    },

    /**
     * 初始化天地图对象
     */
    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.form.LONGITUDE && !this.form.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.form.LONGITUDE = lng
        this.form.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.form.LONGITUDE = event.lnglat.getLng()
      this.form.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)
    },

    back() {
      this.dialogVideoHLS = false
      this.player.dispose()
    },

    handleBack() {
      this.player.dispose()
      this.dialogVideoHLS = false
    }
  }
}
</script>
<style>
  #map{
    width: 1000px;
    height: 500px;
  }
</style>
