import { createConnection, client, servicesTopic, destroyConnection } from './src/mqtt';
import { airport, uav, liveInfo, buildGUID, base64ByURL } from './src/config';
import { GetUavPageByDocksn } from '@/api/demo/projecthome';
import {
  getVerifyToken,
  getDroneDockflightInfos,
  getTaskPicList,
  getTaskVideoList,
} from '@/api/workmanagement/droneDock';
import TCPlayer from 'tcplayer.js';
import { useMessage } from '@/hooks/web/useMessage';
import { errorName } from '@/utils/debugging/remote';

const { createMessage } = useMessage();
const bid = buildGUID();
let video_id;
let sn;
let live_url;
let video_time;

class LiveStreamPlugin {
  constructor() {
    console.log('LiveStreamPlugin constructor');
  }
  initSDK(token: String) {
    /**
     * 初始化SDK。token：用国土调查云ak/sk生成的token，
     * 分中心进行校验通过才能使用直播插件
     */
    return getVerifyToken(token).then((res) => {
      return res;
    });
  }
  setLiveStreamControl(divContainor: HTMLElement, deviceType: number) {
    /**
     * 设置视频直播画面控件，用于展示视频直播。
     * divContainor：div元素
     * deviceType： 0无人机 1 机场监控
     */
    console.log('LiveStreamPlugin setLiveStreamControl', divContainor, deviceType);
    divContainor.innerHTML =
      '  <video id="player-container-id" preload="auto" playsinline webkit-playsinline > </video>';
    setTimeout(() => {
      const player = TCPlayer('player-container-id', {
        sources: [
          {
            src: live_url + '.flv', // 播放地址
          },
        ],
        licenseUrl: live_url + '.flv', // license 地址，必传。参考准备工作部分，在视立方控制台申请 license 后可获得 licenseUrl
        autoplay: true, // 是否自动播放
      });
    }, 1000);
  }
  async startLiveStreamCall(serialNum: String, deviceType: number) {
    /**
     * 开始视频直播
     * serialNum：无人机机场序列号
     * deviceType： 0无人机 1 机场监控
     */
    console.log('LiveStreamPlugin startLiveStreamCall', serialNum, deviceType);
    sn = serialNum;
    createConnection('mqtt_' + serialNum);

    // const liveUrl = liveInfo.rtmp + serialNum;
    let querys;
    if (deviceType == 1) {
      video_id = serialNum + '/' + airport.camera_index + '/' + airport.video_index;
      querys = {
        bid: bid,
        method: 'live_start_push',
        tid: buildGUID(),
        timestamp: new Date().getTime(),
        data: {
          url_type: 1,
          url: liveInfo.rtmp + '5',
          video_id: video_id,
          video_quality: 3,
        },
      };
      live_url = liveInfo.url + '5';
    } else {
      // 根据机场sn获取无人机sn
      const params = {
        sn: sn,
        page: 1,
        limit: 99,
      };
      await GetUavPageByDocksn(params).then((res) => {
        console.log('GetUavPageByDocksn', res);
        if (res.items.length > 0) {
          video_id = res.items[0].sn + '/' + uav.camera_index + '/' + uav.video_index;
          querys = {
            bid: bid,
            method: 'live_start_push',
            tid: buildGUID(),
            timestamp: new Date().getTime(),
            data: {
              url_type: 1,
              url: liveInfo.rtmp + '6',
              video_id: video_id,
              video_quality: 3,
            },
          };
        }
      });
      live_url = liveInfo.url + '5';
    }
    // 发送消息
    servicesTopic(serialNum, querys);
    // 订阅回执
    client.subscribe('thing/product/' + serialNum + '/services_reply', { qos: 0 }, () => {});
    // 接收消息
    client.on('message', (topic, message) => {
      const rs = JSON.parse(message);
      if (rs.bid == bid) {
        console.log('LiveStreamPlugin liveStartPush', rs);
        if (rs.method == 'camera_recording_start') {
          if (rs.data.result == 0) {
            createMessage.success('开始录像成功');
          } else {
            createMessage.error('开始录像失败，' + errorName(rs.data.result));
          }
        }
        if (rs.method == 'live_start_push') {
          if (rs.data.result == 0) {
            createMessage.success('发起视频直播成功');
          } else {
            createMessage.error('发起视频直播失败，' + errorName(rs.data.result));
          }
        }
        if (rs.method == 'live_stop_push') {
          if (rs.data.result == 0) {
            createMessage.success('结束视频直播成功');
          } else {
            createMessage.error('结束视频直播失败，' + errorName(rs.data.result));
          }
        }
      }
    });
  }
  endLiveStreamCall(deviceType: number) {
    /**
     * 结束视频直播
     * deviceType： 0无人机 1 机场监控
     */
    console.log('LiveStreamPlugin endLiveStreamCall', deviceType);
    const querys = {
      bid: bid,
      method: 'live_stop_push',
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      data: {
        video_id: video_id,
      },
    };
    servicesTopic(sn, querys);
  }
  takePicture(callback) {
    /**
     * 拍照
     * callback：拍照完成回调方法，
     * 参数如下： issuccess：状态
     *           true/false；
     *           imgBlob：照片文件Blob；
     *           zpkzxx：照片扩展信息
     */
    console.log('LiveStreamPlugin takePicture', callback);
    servicesTopic(sn, {
      bid: bid,
      method: 'camera_mode_switch',
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      data: {
        camera_mode: 0,
        payload_index: uav.camera_index,
      },
    });
    const time = new Date().getTime();
    setTimeout(() => {
      const querys = {
        bid: bid,
        method: 'camera_photo_take',
        tid: buildGUID(),
        timestamp: time,
        data: {
          payload_index: uav.camera_index,
        },
      };
      console.log(querys);
      servicesTopic(sn, querys);
      client.subscribe('thing/product/' + sn + '/events', { qos: 2 }, () => {});
    }, 1000);
    // 接收消息
    let id = '';
    return new Promise((resolve, reject) => {
      client.on('message', async (topic, message) => {
        const rs = JSON.parse(message);
        if (rs.method == 'camera_photo_take') {
          if (rs.data.result == 0) {
            createMessage.success('拍照成功');
          } else {
            createMessage.error('拍照失败，' + errorName(rs.data.result));
          }
        }
        if (
          rs.method == 'flighttask_progress' &&
          rs.data.output.status == 'in_progress' &&
          id == ''
        ) {
          id = rs.data.output.ext.flight_id;
          createMessage.info('正在获取数据，预计需要一分钟，请稍后');
          setTimeout(() => {
            getTaskPicList({
              flightId: id,
              timestamp: time,
            }).then(async (res) => {
              if (res) {
                await base64ByURL(res.pictureLink).then((urlres) => {
                  let { blob } = urlres;
                  res.imgBlob = blob;
                });
                createMessage.success('获取数据成功');
              } else {
                createMessage.error('获取数据失败，请稍后重试');
              }
              resolve(callback(res));
            });
          }, 50000);
        }
      });
    });
  }
  startVideoRecording() {
    /**
     * 开始录像
     */
    console.log('LiveStreamPlugin startVideoRecording');
    servicesTopic(sn, {
      bid: bid,
      method: 'payload_authority_grab',
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      data: {
        payload_index: uav.camera_index,
      },
    });
    servicesTopic(sn, {
      bid: bid,
      method: 'camera_mode_switch',
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      data: {
        camera_mode: 1,
        payload_index: uav.camera_index,
      },
    });
    setTimeout(() => {
      video_time = new Date().getTime();
      servicesTopic(sn, {
        bid: bid,
        method: 'camera_recording_start',
        tid: buildGUID(),
        timestamp: video_time,
        data: {
          payload_index: uav.camera_index,
        },
      });
    }, 1000);
  }
  endVideoRecording(callback: Function) {
    /**
     * 结束录像
     * callback：录像完成回调方法，
     * 参数如下： issuccess：状态
     *           true/false；
     */
    console.log('LiveStreamPlugin endVideoRecording', callback);
    const time = new Date().getTime();

    servicesTopic(sn, {
      bid: bid,
      method: 'camera_recording_stop',
      tid: buildGUID(),
      timestamp: time,
      data: {
        payload_index: uav.camera_index,
      },
    });
    client.subscribe('thing/product/' + sn + '/events', { qos: 2 }, () => {});
    // 接收消息
    let id = '';
    return new Promise((resolve, reject) => {
      client.on('message', async (topic, message) => {
        const rs = JSON.parse(message);
        if (rs.method == 'camera_recording_stop') {
          if (rs.data.result == 0) {
            createMessage.success('结束录像成功');
          } else {
            createMessage.error('结束录像失败，' + errorName(rs.data.result));
          }
        }
        if (
          rs.method == 'flighttask_progress' &&
          rs.data.output.status == 'in_progress' &&
          id == ''
        ) {
          id = rs.data.output.ext.flight_id;
          createMessage.info('正在获取数据,预计需要五分钟，请稍后');
          setTimeout(() => {
            getTaskVideoList({
              flightId: id,
              timestamp: video_time,
            }).then(async (res) => {
              if (res) {
                await base64ByURL(res.videoLink).then((urlres) => {
                  let { blob } = urlres;
                  console.log(blob);
                  res.videoBlob = blob;
                  console.log(res);
                });
                createMessage.success('获取数据成功');
              } else {
                createMessage.error('获取数据失败，请稍后重试');
              }
              resolve(callback(res));
            });
          }, 300000);
        }
      });
    });
  }
  disposeSDK() {
    /**
     * 销毁SDK
     */
    console.log('LiveStreamPlugin disposeSDK');
    destroyConnection();
  }
  async getFlightTaskInfo(serialNum: String) {
    /**
     * 获取无人机任务信息
     * 参数：serialNum无人机机场序列号
     * 返回结果：FlightTaskInfo
     */
    console.log('LiveStreamPlugin getFlightTaskInfo', serialNum);

    client.subscribe('thing/product/' + serialNum + '/events', { qos: 2 }, () => {});
    // 接收消息
    let id = '';
    return new Promise((resolve, reject) => {
      client.on('message', async (topic, message) => {
        const rs = JSON.parse(message);
        if (
          rs.method == 'flighttask_progress' &&
          rs.data.output.status == 'in_progress' &&
          id == ''
        ) {
          id = rs.data.output.ext.flight_id;
          getDroneDockflightInfos(id).then((res) => {
            resolve(res);
          });
        }
      });
    });
  }
}

export default LiveStreamPlugin;
