<template>
  <v-scale-screen width="2200" height="1080">
    <div  class="main_screen_cotainer">
      <div class="task_header">当前态势</div>
      <div class="tag" @click="jumpToHistory">
        历史态势
      </div>


      <div class="content_cotainer">
        <div class="center_chart_cotainer_task" id="taskItem">
          <div class="task_detail_cotainer_task" style="width:100%;">


<!--            <div v-if="false" class="header_line_style">-->
<!--              <div class="headerTitle"></div>-->
<!--            </div>-->

<!--            <div v-if="false" class="task_name_header">「{{ currentTaskName }}」任务态势大屏</div>-->
<!--             任务屏幕-->

<!--            <div class="task_item_header">-->
<!--              <el-select-->
<!--                  v-model="wholeOutTaskId"-->
<!--                  placeholder="「切换任务」"-->
<!--                  style="width:270px;"-->
<!--                  @change="changeTask"-->
<!--                  filterable-->
<!--              >-->
<!--                <el-option-->
<!--                    v-for="item in taskOPtion"-->
<!--                    :key="item.value"-->
<!--                    :label="item.label"-->
<!--                    :value="item.value"-->
<!--                >-->
<!--                </el-option>-->
<!--              </el-select>-->
<!--            </div>-->

            <div class="task_item_body" >
                <el-row class="task_item_body1" >
                  <el-col :span="24"  >

                    <el-table ref="teacher" :data="pagedData" size="mini"
                              @sort-change="pagedData.onSortChange"
                              header-cell-class-name="table-header-gray" class="task_item_body_bak" >
<!--                    <el-table ref="teacher" :data="renwuliebiao.data" size="mini"-->
<!--                              @sort-change="renwuliebiao.onSortChange"-->
<!--                              header-cell-class-name="table-header-gray">-->


<!--                      <el-table-column label="序号" header-align="center" align="center" type="index" width="55px" :index="renwuliebiao.getTableIndex" />-->
                      <el-table-column label="序号" header-align="center" align="center" type="index" width="55px" :index="getTableIndex" />
                      <el-table-column label="任务实际开始时间" prop="0" />
                      <el-table-column label="任务关联ID" prop="1" />
                      <el-table-column label="任务描述" prop="2" />
                      <el-table-column label="任务状态" prop="3" />
                      <el-table-column label="任务代码" prop="4" />
                      <el-table-column label="任务ID" prop="5" />
                      <el-table-column label="任务名称" prop="6" />
                      <el-table-column label="任务阶段" prop="7" />
                      <el-table-column label="操作" align="center">
                        <template slot-scope="scope">
                          <el-button class="table-btn primary" size="mini" type="text" @click="onTiaozhuan(scope.row)">跳转</el-button>
                        </template>
                      </el-table-column>
                    </el-table>

                    <el-row type="flex" justify="end" style="margin-top: 10px;">
                      <el-pagination
                          :total="renwuliebiao.data.length"
                          :current-page="renwuliebiao.currentPage"
                          :page-size="renwuliebiao.pageSize"
                          :page-sizes="[5,10, 20, 50, 100]"
                          layout="total, prev, pager, next, sizes"
                          @current-change="onCurrentPageChange"
                          @size-change="onPageSizeChange">
                      </el-pagination>

                    </el-row>
                  </el-col>
                </el-row>

                <operation-space v-if="showOperationSpace" :flow-instance="currentFlowInstance" @close="onOperationSpaceClose"></operation-space>

            </div>

          </div>
        </div>


      </div>
    </div>
  </v-scale-screen>
</template>
<script>

import myFlylineChartEnhanced from '../components/my-flyline-chart-enhanced/index'

import myscrollBoard from '../components/myscroll-board/src/main'
import sacleBox from '../components/sacle-box/index'
import { request } from '../utils/request';
var uploadedDataURL = require('../../public/json/taiyuan.json')
import './mainScreen.css'
import Videojs from "video.js"; // 引入Videojs
import FormTaskProcessViewer from '../components/workflow/formTaskProcessViewer.vue';
import hkv from '../components/hk/hkv.vue'
import hkCamara from '../components/hk/hkCamara.vue'
import {Message} from "element-ui";



export default {
  components:{
    myFlylineChartEnhanced,
    sacleBox,
    myscrollBoard,
    hkv,
    hkCamara,
    FormTaskProcessViewer,
  },
  data() {
    return {
      showOperationSpace: false,
      currentFlowInstance: undefined,
      // formAllInstanceWidget: new TableWidget(this.loadAllTaskData, this.loadAllTaskVerify, true, false),
      isInit: false,

      HKCardShow: false,
      HKCamaraShow: false,
      systemFinshedValue:'',
      unitFinshedValue:'',
      wholeOutTaskId:'',
      systemSubjectId:'',
      unitSubjectValue:'',
      subjectItem:{},
      processDefinitionId: "",
      processInstanceId:"",
      moreFlag:true,
      dialogVisible:false,
      taskList:[],
      websocket: null, //建立的连接
      websocketOrder: null, //建立的连接
      websocketBpmn: null, //建立的连接
      updatekey:'1',

      renwuliebiao:{
        header: ['1', '2', '3','4', '5', '6','7', '8'],
        waitTime:1500,
        data: [],
        columnWidth: [80],
        oddRowBGC:'#072347',
        evenRowBGC:'#021736',


        actualStartTime:'',
        bk:'',
        description:'',
        status: '',
        taskCode:'',
        taskId: '',
        taskName: '',
        taskStage:'',

        currentPage:1,
        pageSize:10,

        paged:true,
      },


      scrollTableConfig:{
        header: ['课目名称', '指令名称', '特情注入', '指令内容', '模训系统', '时间'],
        waitTime:1500,
        data: [],
        columnWidth: [80],
        oddRowBGC:'#072347',
        evenRowBGC:'#021736'
      },
      dialogType:1,
      subjectDatas:[],
      subjectMap:{
        '待执行':require('../assets/img/waite.png'),
        '执行中':require('../assets/img/doing.png'),
        '已完成':require('../assets/img/finshed.png') ,
      },
      instructList: [],
      renwuList: [],
      unitOption: [],
      systemOption: [],
      taskOPtion: [],
      isReady: false,
      currentTaskName: "",
      currentTaskGrade: "",
      unitSubGradeValue: "",
      gridData: [],
      camaraSrc: ["", "", "", "", ""],
      completionRate: false,
      playerList: [],
      camaraName: ["监控名称", "监控名称", "监控名称", "监控名称", "监控名称"],
      videoList: [
        "videoPlayerTask",
        "videoPlayer_first",
        "videoPlayer_second",
        "videoPlayer_third",
        "videoPlayer_fourth"
      ],
      mainVideoData: {},
      currentSubject: '',
      camaraData:[],
      cardData:[],
      cardName:[],
      cardSrc:[]
    };
  },
  computed:{
    pagedData() { // 动态计算当前页的数据
      const start = (this.renwuliebiao.currentPage - 1) * this.renwuliebiao.pageSize
      const end = start + this.renwuliebiao.pageSize
      // console.log("hhhh1:  ",start+"---"+end )
      // console.log("hhhh2:  ",this.renwuliebiao.data.slice(start, end) )
      return this.renwuliebiao.data.slice(start, end)
    }
  },
  methods:{
    /**
     * 表格分页变化
     * @param {Integer} newCurrentPage 变化后的显示页面
     */
    onCurrentPageChange (newCurrentPage) {

      console.log("1:  ",newCurrentPage )
      console.log("2:  ",this.renwuliebiao.pageSize )
      console.log("3:  ",this.oldPage)


      this.loadTableDataImpl(newCurrentPage, this.renwuliebiao.pageSize).then(() => {//数据加载成功


        this.renwuliebiao.currentPage = newCurrentPage;
        this.oldPage = this.renwuliebiao.currentPage-1
        console.log("4:  ",newCurrentPage)
        console.log("5:  ",this.renwuliebiao.currentPage)
        console.log("6:  ",this.oldPage)


        if(this.renwuliebiao.data.length <= newCurrentPage*this.renwuliebiao.pageSize   ){
          this.renwuliebiao.paged=true
        }else{
          this.renwuliebiao.paged=false
        }



      }).catch(() => {//数据加载失败
        this.renwuliebiao.currentPage = this.oldPage;


        console.log("7:  ",this.oldPage)
        console.log("8:  ",this.renwuliebiao.currentPage)

      });
    },
    /**
     * 表格分页每页显示数量变化
     * @param {Integer} newPageSize 变化后的每页显示数量
     */
    onPageSizeChange (newPageSize) {

      console.log("hhhh2:  ",newPageSize )

      this.renwuliebiao.pageSize = newPageSize;
      this.renwuliebiao.currentPage = 1
      this.loadTableDataImpl(1, newPageSize).then(() => {
        this.oldPage = this.renwuliebiao.currentPage;
        this.oldPageSize = this.renwuliebiao.pageSize;
      }).catch(e => {
        this.renwuliebiao.currentPage = this.oldPage;
        this.renwuliebiao.pageSize = this.oldPageSize;
      });
    },
    /**
     * 表格排序字段变化
     * @param {String} prop 排序字段的字段名
     * @param {String} order 正序还是倒序
     */
    onSortChange ({ prop, order }) {
      this.orderInfo.fieldName = prop;
      this.orderInfo.asc = (order === 'ascending');
      this.refreshTable();
    },
    /**
     * 获取表格数据
     * @param {Integer} pageNum 当前分页
     * @param {Integer} pageSize 每页数量
     * @param {Boolean} reload 是否重新获取数据
     */
    loadTableDataImpl (pageNum, pageSize, reload = false) {
      console.log("11:  ",pageNum+"---"+pageSize+"---"+reload)

      // const start = (pageNum - 1) * this.renwuliebiao.pageSize
      // const end = start + this.renwuliebiao.pageSize
      // // console.log("hhhh1:  ",start+"---"+end )
      // // console.log("hhhh2:  ",this.renwuliebiao.data.slice(start, end) )
      // return this.renwuliebiao.data.slice(start, end)


// 判断是否需要重新加载数据
      if (reload || !this.renwuliebiao.data || this.renwuliebiao.data.length === 0) {
        // 调用后端接口或其他数据来源获取数据
        // 这里省略具体实现

        // 模拟一个返回结果的 Promise 对象
        const mockData = new Promise(resolve => {
          const data = [];

          for (let i = 1; i <= pageSize; i++) {
            data.push({
              id: pageNum * pageSize + i,
              name: `任务${pageNum * pageSize + i}`,
              status: Math.floor(Math.random() * 4)
            });
          }

          resolve(data);
        });

        // 返回 Promise 对象，以便分页组件可以在数据加载完成后进行下一步处理。
        return mockData.then(data => {
          // 更新任务列表数据
          this.renwuliebiao.data = data;
          // 返回新的任务列表数据
          return this.renwuliebiao.data.slice((pageNum - 1) * pageSize, pageNum * pageSize);
        });
      } else {
        // 直接返回已有的任务列表数据
        return Promise.resolve(this.renwuliebiao.data.slice((pageNum - 1) * pageSize, pageNum * pageSize));
      }


      // return new Promise((resolve, reject) => {
      //   console.log("12:  ",this.loadTableData)
      //
      //   if (typeof this.loadTableData !== 'function') {
      //     reject();
      //   } else {// 如果pageSize和pageNum没有变化，并且不强制刷新
      //     console.log("13:  ",pageNum+"---"+pageSize+"---"+reload)
      //     if (this.paged && !reload && this.oldPage === pageNum && this.oldPageSize === pageSize) {
      //       resolve();
      //     } else {
      //       let params = {};
      //       if (this.orderInfo.fieldName != null) params.orderParam = [this.orderInfo];
      //       if (this.paged) {
      //         params.pageParam = {
      //           pageNum,
      //           pageSize
      //         }
      //       }
      //       this.loading = true;
      //       this.loadTableData(params).then(tableData => {
      //         this.dataList = tableData.dataList;
      //         this.totalCount = tableData.totalCount;
      //         this.loading = false;
      //         resolve();
      //       }).catch(e => {
      //         this.loading = false;
      //         reject(e);
      //       });
      //     }
      //   }
      // });
    },

    /**
     * 刷新表格数据
     * @param {Boolean} research 是否按照新的查询条件重新查询（调用verify函数）
     * @param {Integer} pageNum 当前页面
     */
    refreshTable (research = false, pageNum = undefined, showMsg = false) {
      let reload = false;
      if (research) {
        if (typeof this.searchVerify === 'function' && !this.searchVerify()) return;
        reload = true;
      }

      if (Number.isInteger(pageNum) && pageNum !== this.renwuliebiao.currentPage) {
        this.loadTableDataImpl(pageNum, this.renwuliebiaopageSize, reload).then(res => {
          this.oldPage = this.renwuliebiao.currentPage = pageNum;
          if (research && showMsg) Message.success('查询成功');
        }).catch(e => {
          this.renwuliebiao.currentPage = this.oldPage;
        });
      } else {
        this.loadTableDataImpl(this.renwuliebiao.currentPage, this.renwuliebiao.pageSize, true).catch(e => {});
      }
    },




    /**
     * 获取每一行的index信息
     * @param {Integer} index 表格在本页位置
     */
    getTableIndex (index) {

      // console.log("页码1：  "+index)
      // console.log(".....1  "+index)
      // console.log("页码2：  "+this.renwuliebiao.paged ? ((this.renwuliebiao.currentPage - 1) * this.renwuliebiao.pageSize + (index + 1)) : (index + 1))
      // console.log(".....2  "+this.renwuliebiao.paged)
      let a
      // let a=this.renwuliebiao.paged ? ((this.renwuliebiao.currentPage - 1) * this.renwuliebiao.pageSize + (index + 1)) : (index + 1);
      // console.log(".....a  "+a)
      // return this.renwuliebiao.paged ? ((this.renwuliebiao.currentPage - 1) * this.renwuliebiao.pageSize + (index + 1)) : (index + 1);





      console.log("参数：  "+this.renwuliebiao.paged+" "+this.renwuliebiao.pageSize+" "+index)
      // if(this.renwuliebiao.paged){
      //   console.log("a1")
      //   a=((this.renwuliebiao.currentPage - 1) * this.renwuliebiao.pageSize + (index + 1))
      // }else{
      //   console.log("a2")
      //   a=(index + 1)
      // }
      a=((this.renwuliebiao.currentPage - 1) * this.renwuliebiao.pageSize + (index + 1))
      console.log(".....a  "+a)
      return a;








    },



    onTiaozhuan (a) {


      console.log("111",a[5])
      // this.$router.push({name: 'testParams',params: {testParams:'testParams'}});
      // location.reload()
      this.$router.push({
        path:"/taskScreen",
        query:{
          key1:a[5],
          key2:a[6],
        }
      });
      // location.reload()
    },
    refreshFormAllInstance (reloadData = false) {
      if (reloadData) {
        this.renwuliebiao.refreshTable(true, 1);
      } else {
        this.renwuliebiao.refreshTable();
      }
      if (!this.isInit) {
        // 初始化下拉数据
      }
      this.isInit = true;
    },

    onOperationSpaceClose () {
      this.showOperationSpace = false;
      this.currentFlowInstance = null;
      this.refreshFormAllInstance()
    },

    HKCardInit(){
      this.HKCardShow = true;
    },
    jumpToHistory() {
      // this.$refs.hk.$destroy();
      //     this.HKshow = false;

      this.$router.push("/situationScreen")


    },
    // 表格样式修改
    changeHeaderCellStyle(row,column, rowIndex, columnIndex){
      if(row.columnIndex === 0){
        return 'background: #004279 ; color:#fff;'; // 修改的样式
      }else {
        return 'background: #004279 ;color:#fff; ';
      }
    },
    changeCellStyle(row,column, rowIndex, columnIndex){
      if(row.columnIndex === 0){
        return 'background: #0A427C  ; color:#fff;'; // 修改的样式
      }else {
        return 'background: #0A427C ; color:#fff;';
      }
    },



    // 获取全部系统
    async getAllSystems(){
      let params={}
      const res = await request('/dt_screen/rest/v1/screen/listSystem/', 'get', params, false)
      const { errorCode, errorMessage, success,data } = res.data;
      if (success) {
        console.log('获取全部系统', data);
        this.systemOption = data.map((item)=>{
          return {
            label:item.systemName,
            value: item.systemId
          }
        })
        this.systemFinshedValue=this.systemOption[0].value
      } else {
        this.$message.error(errorMessage)
      }
    },



    // 获取全部单位
    async getAllUnits (){
      let params={}
      const res = await request('/dt_screen/rest/v1/screen/listUnit/', 'get', params, false)
      const { errorCode, errorMessage, success,data } = res.data;
      if (success) {
        console.log('获取全部单位', data);
        // 获取任务数据
        this.getTaskList()
        this.unitOption = data.map((item)=>{
          return {
            label:item.unitName,
            value: item.unitId
          }
        })
        this.unitFinshedValue=this.unitOption[0].value
        this.unitSubGradeValue=this.unitOption[0].value
      } else {
        this.$message.error(errorMessage)
      }
    },


    /**
     * 获取所有任务实例
     */
    loadAllTaskData (params) {
      if (params == null) params = {};
      params = {
        ...params,
        processDefinitionName: this.formFilterCopy.processDefinitionName,
        startUser: this.formFilterCopy.startUser,
        processName: this.formFilterCopy.processName,
        processStatus: this.formFilterCopy.processStatus,
        taskCode: this.formFilterCopy.taskCode,
        taskStage: this.formFilterCopy.taskStage,
        beginDate: this.formFilterCopy.createDate[0],
        endDate: this.formFilterCopy.createDate[1]
      }

      return new Promise((resolve, reject) => {
        FlowOperationController.listAllHistoricProcessInstanceWithTask(this, params).then(res => {
          console.log('res :>> ', res);
          resolve({
            dataList: res.data.dataList,
            totalCount: res.data.totalCount
          });
        }).catch(e => {
          reject(e);
        });
      });
    },


    // 获取任务列表
    async getTaskList() {
      let params = {};
      // const res = await request("/dt_screen/rest/v2/task/listCurrentTask/", "post", params, false);
      const res = await request("/dt_screen/rest/v2/task/listRunningTasks/", "post", params, false);
      const { errorCode, errorMessage, success, data } = res.data;
      if (success) {
        console.log("获取任务列表", data);

        this.renwuList=data
        let tempData=[]
        data.forEach((item)=>{
          console.log("1:  ", item);


          tempData.push([item.actualStartTime, item.bk, item.description,item.status,item.taskCode,item.taskId ,item.taskName, item.taskStage])
        })
        this.renwuliebiao.data=tempData

          //
          // this.instructList=data
          // let tempData=[]
          // data.forEach((item)=>{
          //   tempData.push([item.subjectName, item.name, item.situation, item.content, item.system,item.time])
          // })
          // this.scrollTableConfig.data=tempData
          // console.log("🚀 data >> ", this.scrollTableConfig.data);
          // this.updatekey=new Date().getTime()










        this.taskList = data;
        this.wholeOutTaskId = data[0].taskId;
        this.processInstanceId = this.wholeOutTaskId;
        this.taskOPtion = data.map((item) => {
          return {
            label: item.taskName,
            value: item.taskId
          };
        });


        let param = {taskId: this.processInstanceId};
        const res1 = await request("/dt_screen/rest/v2/task/getDefId/", "post", param, false);
        this.processDefinitionId = res1.data;
        this.initWebsoketBpmn();
        this.isReady = true;
        this.currentTaskName = data[0].taskName;
        this.currentTaskGrade = data[0].syntheticTaskScore;
        // 获取地图的信息
        if (data.length) {
          // 获取任务的课目信息
          this.getSubjectList(data[0].taskId);
          // 获取任务的指令信息
          this.getinstructList(data[0].taskId);
          // 建立指令websocket 链接
          this.initInstructWebsoket();
        }
      } else {
        this.$message.error(errorMessage);
      }

    },




    // 切换任务
    async changeTask() {
      this.camaraData = []
      this.cardData = []
      this.systemSubjectId = "";
      this.unitSubjectValue = "";
      this.isReady = false;
      this.currentTaskName = this.taskOPtion.find((item) => item.value == this.wholeOutTaskId).label;
      this.currentTaskGrade = this.taskList.find((item) => item.taskId == this.wholeOutTaskId).syntheticTaskScore;
      // 获取任务的课目信息
      this.processInstanceId = this.wholeOutTaskId;

      let param = {taskId: this.processInstanceId};
      const res2 = await request("/dt_screen/rest/v2/task/getDefId/", "post", param, false);
      console.log('res2 :>> ', res2.data);
      this.processDefinitionId = res2.data;
      this.isReady = true;
      this.getSubjectList(this.wholeOutTaskId);
      // 获取任务的指令信息
      this.getinstructList(this.wholeOutTaskId);
      // 建立指令websocket 链接
      this.initInstructWebsoket();
      this.initWebsoketBpmn();
    },
    changeTaskAndUnit() {
      this.systemSubjectId=''
      if(this.unitSubjectValue){
        this.getUnitSubjectList(this.wholeOutTaskId, this.unitSubjectValue)
      }else {
        this.getSubjectList(this.wholeOutTaskId)
      }
    },
    changeTaskAndSystem() {
      this.unitSubjectValue=''
      if(this.systemSubjectId){
        this.getSystemSubjectList(this.wholeOutTaskId, this.systemSubjectId)
      }else {
        this.getSubjectList(this.wholeOutTaskId)
      }
    },
    // 获取任务的课目信息
    async getSubjectList(taskId){
      let params={}
      const res = await request(`/dt_screen/rest/v2/subject/list/${taskId}`, 'get', params, false)
      const { errorCode, errorMessage, success,data } = res.data;
      if (success) {
        console.log('获取任务的课目信息', data);
        this.subjectDatas=data
        this.initUrl(this.subjectDatas[0].subjectName)
      } else {
        this.$message.error(errorMessage)
      }
    },
    // 获取任务的指令
    async getinstructList (taskId) {
      let params={}
      const res = await request(`/dt_screen/rest/v2/order/list/${taskId}`, 'get', params, false)
      const { errorCode, errorMessage, success,data } = res.data;
      if (success) {
        console.log('获取任务的指令', data);
        this.instructList=data
        let tempData=[]
        data.forEach((item)=>{
          tempData.push([item.subjectName, item.name, item.situation, item.content, item.system,item.time])
        })
        this.scrollTableConfig.data=tempData
        console.log("🚀 data >> ", this.scrollTableConfig.data);
        this.updatekey=new Date().getTime()

      } else {
        this.$message.error(errorMessage)
      }
    },
    // 切换单位再结合任务id 获取课目课目列表
    async getUnitSubjectList(taskId,unitId){
      let params={}
      params["taskId"] = taskId
      params["unitId"] = unitId
      // const res = await request(`/dt_screen/rest/v1/subject/list/task/${taskId}/unit/${unitId}`, 'get', params, false)
      const res = await request(`/dt_screen/rest/v2/subject/listByCondition`, 'post', params, false)
      const { errorCode, errorMessage, success,data } = res.data;
      if (success) {
        this.subjectDatas=data
      } else {
        this.$message.error(errorMessage)
      }
    },
    // 切换系统再结合任务id 获取课目课目列表
    async getSystemSubjectList(taskId,systemId){
      let params={}
      params["taskId"] = taskId
      params["systemId"] = systemId
      // const res = await request(`/dt_screen/rest/v1/subject/list/task/${taskId}/system/${systemId}`, 'get', params, false)
      const res = await request(`/dt_screen/rest/v2/subject/listByCondition`, 'post', params, false)
      const { errorCode, errorMessage, success,data } = res.data;
      if (success) {
        this.subjectDatas=data
      } else {
        this.$message.error(errorMessage)
      }
    },
    // 建立websocket 链接 任务
    initWebsoket(){
      this.websocket = new WebSocket(`ws://${this.$store.state.webSocketIp}:${this.$store.state.webSocketPort}/websocket/task`);//这里将http替换成ws
      switch (this.websocket.readyState) {
        case 0:
          console.log("正在连接");
          break;
        case 1:
          console.log("已经链接并且可以通讯");
          break;
        case 2:
          console.log("连接正在关闭");
          break;
        case 3:
          console.log("连接已关闭或者没有链接成功");
          break;
      };
      this.websocket.onopen = this.websocketsend;//websoket连接成功
      this.websocket.onmessage =this. websocketonmessage;//websoket收到信息
      this.websocket.onclose = this.websocketclose;//websoket连接关闭
    },
    websocketsend(){
      console.log('ws 连接成功');
    },
    websocketonmessage(msg){
      // 获取全部单位
      this.getAllUnits()
      // 获取全部系统
      this.getAllSystems()
      console.log('收到任务信息',msg);
    },
    websocketclose(){
      console.log('ws 连接关闭');
      this.initWebsoket();//重新建立连接
    },
    // 建立websocket 链接 任务
    initWebsoketBpmn(){
      this.websocketBpmn = new WebSocket(`ws://${this.$store.state.webSocketIp}:${this.$store.state.webSocketPort}/websocket/bpmn`);//这里将http替换成ws
      switch (this.websocketBpmn.readyState) {
        case 0:
          console.log("正在连接");
          break;
        case 1:
          console.log("已经链接并且可以通讯");
          break;
        case 2:
          console.log("连接正在关闭");
          break;
        case 3:
          console.log("连接已关闭或者没有链接成功");
          break;
      };
      this.websocketBpmn.onopen = this.bpmnWebsocketsend;//websoket连接成功
      this.websocketBpmn.onmessage =this.bpmnWebsocketonmessage;//websoket收到信息
      this.websocketBpmn.onclose = this.bpmnWebsocketclose;//websoket连接关闭
    },
    bpmnWebsocketsend(){
      console.log('ws 连接成功');
    },
    bpmnWebsocketonmessage(msg){
      // 更新流程图
      this.$refs.FormTaskProcessViewer.getTaskHighlightData();
      this.$refs.FormTaskProcessViewer.getTaskProcessXml();
      console.log('收到指令信息',msg);
    },
    bpmnWebsocketclose(){
      console.log('ws 连接关闭');
      this.initWebsoketBpmn();//重新建立连接
    },
    initInstructWebsoket(){
      // 指令的ws
      this.websocketOrder = new WebSocket(`ws://${this.$store.state.webSocketIp}:${this.$store.state.webSocketPort}/websocket/order/${this.wholeOutTaskId}`);//这里将http替换成ws
      switch (this.websocketOrder.readyState) {
        case 0:
          console.log("正在连接");
          break;
        case 1:
          console.log("已经链接并且可以通讯");
          break;
        case 2:
          console.log("连接正在关闭");
          break;
        case 3:
          console.log("连接已关闭或者没有链接成功");
          break;
      };
      this.websocketOrder.onopen = this.orderWebsocketsend;//websoket连接成功
      this.websocketOrder.onmessage =this. orderWebsocketonmessage;//websoket收到信息
      this.websocketOrder.onclose = this.orderWebsocketclose;//websoket连接关闭
    },
    orderWebsocketsend(){
      console.log('ws 连接成功');
    },
    orderWebsocketonmessage(msg){
      // 获取任务的指令信息
      this.getinstructList(this.wholeOutTaskId)
      console.log('收到指令信息',msg);
    },
    orderWebsocketclose(){
      console.log('ws 连接关闭');
      this.initInstructWebsoket();//重新建立连接
    },
    // 查看成绩表格
    viewManData(item){
      this.dialogType=2
      this.dialogVisible=true
      console.log('item',item);
      const { subjectScore } = item
      this.gridData=subjectScore
    },
    // 全屏事件
    showFull(id){
      console.log('this.camaraData :>> ', this.camaraData);
      console.log('ckx debug  监控大屏' )
      this.$router.push(
          {
            path: './monitorScreen',
            query: {
              camaraData: JSON.stringify(this.camaraData)
            }
          }
      )
    },
    showFull1(id){
      console.log('this.camaraData :>> ', this.cardData);
      console.log('ckx debug  监控大屏' )
      this.$router.push(
          {
            path: './monitorScreen',
            query: {
              camaraData: JSON.stringify(this.cardData)
            }
          }
      )
    },
    // 退出全屏
    exitFull(){
      let exitFullScreen =
          document.exitFullScreen ||
          document.mozCancelFullScreen ||
          document.webkitExitFullscreen ||
          document.msExitFullscreen;
      if (exitFullScreen) {
        exitFullScreen.call(document);
      }
      this.updatekey=new Date().getTime()
    },
    // 展开全屏
    requestFullScreen(elem){
      console.log('ckx debug ',  )
      // #兼容不同的浏览器
      var requestMethod =
          elem.requestFullScreen ||
          elem.webkitRequestFullScreen ||
          elem.mozRequestFullScreen ||
          elem.msRequestFullScreen;
      if (requestMethod) {
        requestMethod.call(elem);
      } else if (typeof window.ActiveXObject !== "undefined") {
        // #模拟F11 实现全屏
        var wscript = new ActiveXObject("WScript.Shell");
        if (wscript !== null) {
          wscript.SendKeys("{F11}");
        }
      }
      let that =this
      window.addEventListener('resize',function () {//执行
        let isFull = document.mozFullScreen ||
            document.fullScreen ||
            //谷歌浏览器及Webkit内核浏览器
            document.webkitIsFullScreen ||
            document.webkitRequestFullScreen ||
            document.mozRequestFullScreen ||
            document.msFullscreenEnabled
        if (isFull === undefined) {
          that.exitFull()
        }else {

        }
      })
    },
    checkFull() {
      //判断浏览器是否处于全屏状态 （需要考虑兼容问题）
      //火狐浏览器
      let isFull = document.mozFullScreen ||
          document.fullScreen ||
          //谷歌浏览器及Webkit内核浏览器
          document.webkitIsFullScreen ||
          document.webkitRequestFullScreen ||
          document.mozRequestFullScreen ||
          document.msFullscreenEnabled
      if (isFull === undefined) {
        isFull = false
      }
      return isFull;
    },
    showMoreInfo(type){
      if(type=='more'){
        this.$router.push('/situationScreen')
      }else {
        this.$router.push('/taskScreen')
      }
    },

    // 初始化视频
    initVideo(nowPlayVideoUrl,id) {
      let that =this

      // 这些options属性也可直接设置在video标签上，见 muted
      let options = {
        autoplay: true, // 设置自动播放
        controls: true, // 显示播放的控件
        sources: [
          // 注意，如果是以option方式设置的src,是不能实现 换台的 (即使监听了nowPlayVideoUrl也没实现)
          {
            src: nowPlayVideoUrl,
            type: "application/x-mpegURL" // 告诉videojs,这是一个hls流
          }
        ]
      };
      // videojs的第一个参数表示的是，文档中video的id
      const myPlyer= Videojs(id, options, function onPlayerReady() {
        console.log("onPlayerReady 中的this指的是：", this); // 这里的this是指Player,是由Videojs创建出来的实例
        console.log(myPlyer === this); // 这里返回的是true
      });
      this.playerList.push(myPlyer)

    },

    async initUrl(subjectName) {
      if (subjectName == '')
        return;

      let params = {
        subjectName: subjectName,
        taskId: this.wholeOutTaskId
      };
      this.currentSubject = subjectName;
      this.camaraData = [];
      this.cardData = [];
      const res = await request("/dt_screen/rest/v2/video/videos/getSubjectUrls", "post", params, false);
      let index = 0;
      this.camaraSrc = ["", "", "", "", ""];
      this.camaraName = ["监控名称", "监控名称", "监控名称", "监控名称", "监控名称"];

      for (let item in res.data.data) {
        // this.camaraSrc[index] = res.data.data[item].url;
        // this.camaraName[index++] = res.data.data[item].name;
        let data = {
          ip: res.data.data[item].ip,
          Port: res.data.data[item].port,
          Username: res.data.data[item].username,
          Password: res.data.data[item].password,
          channelName: res.data.data[item].channelName
        };
        this.camaraData.push(data);
      }

      setTimeout(() => {
        this.HKCamaraShow = true;
      }, 800);

      let params1 = {
        subjectName: subjectName,
        taskId: this.wholeOutTaskId
      };
      this.currentSubject = subjectName;
      const res1 = await request("/dt_screen/rest/v2/video/videos/getSubjectCardUrls", "post", params1, false);
      console.log('res1 :>> ', res1);
      let index1 = 0;
      this.cardSrc = ["", "", "", "", ""];
      this.cardName = ["监控名称", "监控名称", "监控名称", "监控名称", "监控名称"];
      for (let item in res1.data.data) {
        // this.cardSrc[index1] = res1.data.data[item].url;
        // this.cardName[index1++] = res1.data.data[item].name;
        let data = {
          ip: res1.data.data[item].ip,
          Port: res1.data.data[item].port,
          Username: res1.data.data[item].username,
          Password: res1.data.data[item].password,
          channelName: res1.data.data[item].channelName
        };
        this.cardData.push(data);
      }
      console.log('cardData :>> ', this.cardData);
      // setTimeout(() => {

      //   for(let index = 0; index < this.cardSrc.length;index++)
      //   {
      //     this.cardData.push(this.resolveUrl(this.cardSrc[index]))
      //   }
      // }, 1000);

    },
    resolveUrl(url){
      if(url ==''){
        return;
      }
      let data = {};
      url = url.split("/");
      url = url[2];
      url = url.split(":");
      data.Username = url[0];
      data.Port = 80;
      url = url[1];
      url = url.split("@");
      data.ip = url[1];
      data.Password = url[0];
      data.channelName = "test1";
      return data;
    },
    changeVideo(subjectName) {
      if (subjectName == '')
        return;
      if(subjectName != this.currentSubject) {
        this.currentSubject = subjectName;
        // this.$refs.hkv.stopAll();
        // this.$refs.hkCard.stopAll();
        this.camaraData = []
        this.cardData = []
        this.initUrl(subjectName);
      }
    }
  },
  mounted() {



    // 获取全部单位
    this.getAllUnits();
    // 获取全部系统
    this.getAllSystems();
    // 建立任务的weksocket链接
    this.initWebsoket();
    // setTimeout(() => {
    // this.initUrl('步坦协同课目');
    //   }, 1000);
    //   setTimeout(() => {

    //  console.log('this.camaraSrc :>> ', this.camaraSrc);
    // for(let index = 0; index < this.camaraSrc.length;index++)
    // {
    //   this.camaraData.push(this.resolveUrl(this.camaraSrc[index]))
    // }

    // console.log('this.camaraData :>> ', this.camaraData);

    // }, 1000);

    //  setTimeout(() => {

    //   this.HKshow = true;

    // }, 800);

    // this.currentSubject = "步坦协同课目";
    //
    // //     // 过14秒调用
    // setTimeout(() => {
    //   for (let index = 0; index < this.camaraSrc.length; index++) {
    //     console.log('object :>> ',this.camaraSrc[index]);
    //     this.initVideo(this.camaraSrc[index], this.videoList[index]);
    //   }
    // }, 5000);
  },
  beforeDestroy() {
    this.HKshow = false;

    if (this.playerList.length) {
      this.playerList.forEach((item) => {
        item.dispose();
      });
    }
    let params ={}
    const res = request("/dt_screen/video/videos/videoClose", "get", params, false);
  }
};
</script>
<style scoped>
#videoPlayerTask {
  width: 906px;
  height: 350px;
}

#videoPlayer_first {
  width: 278px;
  height: 164px;
  margin-right: 10px;
  margin-bottom: 10px;
}

#videoPlayer_second {
  width: 278px;
  height: 164px;
  margin-bottom: 10px;
}

#videoPlayer_third {
  width: 278px;
  height: 164px;
  margin-right: 10px;
}

#videoPlayer_fourth {
  width: 278px;
  height: 164px;
}
.video_flex_style {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 10px 0;
  box-sizing: border-box;
}
</style>
