// pages/call/call.js

import { XYTCallEngine, HangupReason, CallState, EventType, CallType} from '../../js/XYTCallEngine.js';
import { pusherStatusToast, shareData} from '../../utils/util.js';

Page({
  player: null,
  pusher: null,
  eventCallBack: null,
  /**
   * 页面的初始数据
   */
  data: {
    type: '',
    callerName: '',
    callerNumber: '',
    playUrl: '',
    pushUrl: '',
    camera: 'front',
    windowWidth: wx.getSystemInfoSync().windowWidth,
    windowHeight: wx.getSystemInfoSync().windowHeight,
    openPlay: true,
    openPush: true,
    openDtmf: false,
    video: false,
    orientation: 'vertical',
    show: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let type = options.type;
    let video = options.video=="true";
    if (!type) return;
    if (type == 'incoming') {
      let callerNumber = options.callerNumber;
      let callerName = options.callerName;
      this.setData({
        type: type,
        callerName: callerName ? callerName : "",
        callerNumber: callerNumber ? callerNumber : "",
        video: video
      });
    } else if (type == 'outgoing') {
      let dstNumber = options.dstNumber;
      if (!dstNumber) {
        wx.navigateBack();
        return;
      };
      this.setData({
        type: type,
        video: video
      })
      this._startNewCall(dstNumber);
    }
    this.addEvent();
  },
  addEvent: function () {
    wx.setKeepScreenOn({
      keepScreenOn: true,
    });
    this.eventCallBack = (eventType, data) => {
      if (eventType == EventType.NetWorkError) {
        //网络错误 直接挂断
        console.log(data);
        XYTCallEngine.hangup(HangupReason.Normal);
        this.releasePusherAndPlayer();
        wx.navigateBack();
      } else if (eventType == EventType.Answer) {
        //对方应答
        console.log("event answer");
        let playUrl = data.playUrl;
        if (!(playUrl && playUrl.length > 0)) {
          console.error("plaUrl is empty!!!");
          return;
        }
        this.setData({
          playUrl: playUrl,
          type: "incall"
        })
        this.player = wx.createLivePlayerContext("player", this);
        
        this.pusher.start();
        this.player.play();
        console.log("event answer playUrl > " + this.data.playUrl);
      } else if (eventType == EventType.Hangup) {
        let reason = "呼叫失败";
        if (data == HangupReason.NoAnswer) {
          reason = "无人接听";
        } else if (data == HangupReason.Rejected) {
          reason = "对方拒接";
        } else if (data == HangupReason.UserBusy) {
          reason = "用户忙";
        } else if (data == HangupReason.NoLogin) {
          reason = "对方未在线";
        } else if (data == HangupReason.Normal) {
          reason = null;
        }
        //对方挂断
        console.log("event hangup");
        this.releasePusherAndPlayer();
        if (reason) {
          wx.showToast({
            title: reason,
            icon: 'none'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1000);
        } else {
          wx.navigateBack();
        }
      } else if (eventType == EventType.Ring) {
        //对方响铃
        console.log("event ring");
      } else if (eventType == EventType.DTMF) {
        //对方按键
        console.log("event dtmf > " + data);
      }
    };
    XYTCallEngine.addEventCallBack(this.eventCallBack);
  },
  _startNewCall: function (dstNumber) {
    var callType = CallType.Sip;
    if (dstNumber.charAt(0) == "*") {
      callType = CallType.WXApp;
      dstNumber = dstNumber.substr(1);
    }
    XYTCallEngine.newCall(dstNumber, this.data.video, "1111111", "1111111", callType, (success, data) => {
      if (!success) {
        console.log(data);
        wx.showToast({
          title: data,
          'icon': 'none'
        });
        this.bindHangupTap();
      } else {
        if (!data.pushUrl) {
          console.error("pushurl is empty!!!");
          return;
        }
        console.log("pushurl > "+data.pushUrl);
        this.setData({
          pushUrl: data.pushUrl
        });
        this.pusher = wx.createLivePusherContext("pusher", this);
        this.pusher.startPreview();
      }
    });
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (XYTCallEngine.callState != CallState.Idle) {
      XYTCallEngine.hangup(HangupReason.Normal);
      this.releasePusherAndPlayer();
    }
    wx.setKeepScreenOn({
      keepScreenOn: false,
    });
    XYTCallEngine.removeEventCallBack(this.eventCallBack);
  },

  bindAnswerTap: function () {
    XYTCallEngine.answer((success, data) => {
      if (!success) {
        console.log(data);
        wx.showToast({
          title: data,
          'icon': 'none'
        });
        this.bindHangupTap();
      } else {
        let pushUrl = data.pushUrl;
        let playUrl = data.playUrl;
        console.log("pushurl > " + data.pushUrl);
        console.log("playurl > " + data.playUrl);
        this.setData({
          pushUrl: pushUrl,
          playUrl: playUrl,
          type: "incall"
        });
        this.pusher = wx.createLivePusherContext("pusher", this);
        this.player = wx.createLivePlayerContext("player", this);
        this.player.play();
        this.pusher.start();
      }
    });
  },
  bindHangupTap: function () {
    let reason = HangupReason.Normal;
    if (XYTCallEngine.callState == CallState.Imcoming) {
      //呼入挂断 拒接
      reason = HangupReason.Rejected;
    }
    XYTCallEngine.hangup(reason);
    this.releasePusherAndPlayer();
    wx.navigateBack();
  },
  releasePusherAndPlayer: function () {
    if (this.player) this.player.stop();
    if (this.pusher) this.pusher.stop();
    this.player = null;
    this.pusher = null;
  },
  bindPlay: function () {
    if (this.data.type == "incall") {
      let openPlay = !this.data.openPlay;
      if (openPlay) {
        this.player && this.player.resume();
      } else {
        this.player && this.player.pause();
      }
      this.setData({
        openPlay: openPlay
      })
    }
  },
  bindPush: function () {
    if (this.data.type == "incall") {
      let openPush = !this.data.openPush;
      if (openPush) {
        this.pusher && this.pusher.resume();
      } else {
        this.pusher && this.pusher.pause();
      }
      this.setData({
        openPush: openPush
      })
    }
  },
  bindDtmf: function () {
    let openDtmf = !this.data.openDtmf;
    this.setData({
      openDtmf: openDtmf
    });
  },
  bindKeybordClick: function (e) {
    let key = e.currentTarget.dataset.item;
    if (!key) return;
    let keyValues = { '0_0': '1', '0_1': '2', '0_2': '3', '1_0': '4', '1_1': '5', '1_2': '6', '2_0': '7', '2_1': '8', '2_2': '9', '3_0': '*', '3_1': '0', '3_2': '#', };
    let value = keyValues[key];
    if (!value) return;
    XYTCallEngine.dtmf(value);
  },
  bindSwitchCamera: function () {
    let camera = this.data.camera;
    if (camera == "front") {
      camera = "back";
    } else {
      camera = "front";
    }
    this.setData({
      camera: camera
    });
    this.pusher && this.pusher.switchCamera();
  },
  //监听网络状态
  bindnetstatus: function(e) {
    console.log("netSpeed: " + e.detail.info.netSpeed + "  netJitter: " + e.detail.info.netJitter);
  },

  playerStatechange: function (e) {
    pusherStatusToast(e);
    console.log('live-player code:', e.detail.code)
    
    let code = e.detail.code;
    if (code == 2104 || code == 2105 || code == 2107) {
      //网络不稳定
      wx.showToast({
        title: '请检查您的网络，当前网络可能会影响您的通话质量',
        icon: 'none'
      });
    } else if (code == -2301) {
      //网络异常
      this.bindHangupTap();
    }
  },
  playerError: function (e) {
    pusherStatusToast(e);
    console.error('live-player error:', e.detail.errMsg)
  },
  pusherStatechange: function (e) {
    pusherStatusToast(e);
    console.log('live-pusher code:', e.detail.code)
    let code = e.detail.code;
    if (code == 1101) {
      //网络不稳定
      wx.showToast({
        title: '请检查您的网络，当前网络可能会影响您的通话质量',
        icon: 'none'
      });
    }else if (code == -1307) {
      //网络异常
      this.bindHangupTap();
    }
  },
  pusherError: function (e) {
    pusherStatusToast(e);
    console.error('live-pusher error:', e.detail.errMsg)
  },

  onResize(res) {
    let w = res.size.windowWidth;
    let h = res.size.windowHeight;
    let orientation = w > h ? "horizontal" : "vertical";
    this.setData({
      windowWidth:w,
      windowHeight:h,
      orientation:orientation
    })
  },
  bindShowTap: function () {
    this.setData({
      show: !this.data.show
    })
  },
  onShareAppMessage: function (res) {
    return shareData();
  }
  
})