/**
 * 初始化华为云sdk
 * 正常会议与免费加入会议的功能都需要先初始化
 * 不同的是：
 * 1、正常会议需要先登录账号
 * 2、免费加入会议不需要登录账号
 */
import options from "./config";
import store1 from "../../../../src/index";
import { routerRedux } from "dva/router";
import { message, Modal } from "antd";
import {
  EC_EndConferenceReason,
  EC_ConfctrlOperationResult,
} from "./reasonCode";
const { confirm } = Modal;
export default function initial() {
  cloudEC.configure(options);
  var isNochairSharing = 0;
  var isPluginClickShare = 0;
  const _this = this;
  let listeners = {
    //1 This callback is used to handle kick out of login scenes(被踢出)
    onForceUnReg: function (ret) {
      if (ret.info.serviceAccountType == 0) {
        var confStatus = client.getConfHandler();
        if (confStatus) {
          client.leaveConf();
        }
        client.logout();
        _this.props.dispatch({
          type: `client/setLogin`,
          payload: {
            loginStatus: false,
          },
        });
        message.warning("您的会议账号已在其他地方登录");
        _this.props.dispatch({
          type: `client/setISKickOut`,
          payload: {
            isKickOut: true,
          },
        });
        const { dispatch } = store1;
        dispatch(routerRedux.push("/user/logOn"));
      }
    },

    //2 This callback is used to process text messages
    onChatRecvMsg: function (ret) {
      if (ret.result) {
        cloudecReceiveMsg(ret.info);
      }
    },

    //3 This callback is used to process the participant list refresh(刷新参与者列表)
    onUpdateAttendeeList: function (ret) {
      if (ret.result) {
        _this.getAttendeeList();
      }
    },

    //4 This callback is used to handle speaker notifications(处理扬声器通知)
    onSpeakerIdentify: function (ret) {
      if (ret.result) {
        // cloudecSpeaker(ret.info);
      }
    },
    //5 This callback is used to handle invitation sharing(处理邀请共享)
    onSharedInComing: function (ret) {
      if (isNochairSharing == 0) {
        confirm({
          title: "您有一个共享邀请，是否立即接受?",
          okText: "接受",
          cancelText: "取消",
          onOk() {
            client.answerScreenSharing(true);
          },
          onCancel() {
            client.answerScreenSharing(false);
          },
        });
      } else {
        client.answerScreenSharing(true);
      }
    },
    //6 This callback is used to handle meeting invitation(用于处理会议邀请)
    onConfIncoming: function (ret) {
      _this.getAttendeeList(); //更新会议列表
      var confIncomingInfo = ret.info;
      if (confIncomingInfo.subject != "") {
        confirm({
          title: confIncomingInfo.subject
            ? "您有一个名为“" +
              confIncomingInfo.subject +
              "”的会议邀请, 是否立即加入?"
            : "您有一个会议邀请，是否立即加入?",
          okText: "加入",
          cancelText: "取消",
          onOk() {
            client.answerConference(true);
            _this.props.dispatch({
              type: `client/setCurrentConferID`,
              payload: {
                currentConferID: confIncomingInfo.confId,
                currentConferTopic: confIncomingInfo.subject,
              },
            });
          },
          onCancel() {},
        });
      } else {
        client.answerConference(false);
      }
      _this.props.dispatch({
        type: `client/setISRefreshMeetingList`,
        payload: {
          updateISRefreshMeetingList: true,
        },
      });
    },
    //7 This callback is used to handle the conference connection（用于处理会议链接）
    onConfConnected: function (ret) {
      if (ret.result) {
        _this.props.dispatch({
          type: `client/setJoinMeetingStatus`,
          payload: {
            joinMeetingStatus: false,
            isSuccessJoinMeeting: true,
          },
        });
        message.info("加入会议成功");
      }
    },
    //8 This callback is used to handle exceptions（用于处理异常）
    onError: function (ret) {
      console.log(ret)
      if (390000003 == ret.info.errorCode) {
        console.warn(
          "Memory usage over 80%, please close the unrelated program."
        );
      } else {
        //  TODO
        if (ret.info === "Already in the meeting!") {
          _this.props.dispatch({
            type: `client/setJoinMeetingStatus`,
            payload: {
              joinMeetingStatus: false,
            },
          });
          if (_this.props.currentConferTopic) {
            message.warning(
              "您当前已在主题为“" + _this.props.currentConferTopic + "”的会议中"
            );
          } else {
            message.warning("您当前已在会议中");
          }
        } else {
          console.log(ret);
          alert(JSON.stringify(ret));
        }
      }
    },

    //9 离开会议事件
    onLeaveConference: function (ret) {
      if (ret.result) {
        if (_this.props.currentConferTopic) {
          message.info(
            "您已离开主题为“" + _this.props.currentConferTopic + "”的会议"
          );
        } else {
          message.info("您已离开会议");
        }
        _this.getAttendeeList();
        _this.props.dispatch({
          type: `client/setCurrentConferID`,
          payload: {
            currentConferID: null,
          },
        });
        if (_this.props.history.location.pathname === "/meeting/control") {
          _this.props.history.go(-1);
        }
      }
    },

    //10 其他用户收到结束会议通知
    onEndConference: function (ret) {
      console.log(ret);
      if (ret.result) {
        message.info(EC_EndConferenceReason[ret.info.reasonCode]);
        endConference(_this);
      } else {
      }
    },

    //11 This callback is used to apply for remote control（应用远程控制）
    onAsOnPrivilege: function (ret) {
      if (ret.info.sharePrivilegeType == 0) {
        switch (ret.info.shareAction) {
          case 0: //共享权限释放
            alert("share permissions are released ");
            break;
          case 1: //共享权限添加
            alert("share permissions are added ");
            break;
          case 2: //共享权限修改
            alert("share permissions are modified  ");
            break;
          case 3: //共享权限申请
            confirm({
              title:
                "The other person requests control of your computer,reject or accept?",
              okText: "确定",
              cancelText: "取消",
              onOk() {
                client.answerRemoteCtrl(ret.info.attendee, true);
              },
              onCancel() {
                client.answerRemoteCtrl(ret.info.attendee, false);
              },
            });
            break;
          case 4: //拒绝共享权限申请
            message.warning("拒绝共享权限申请");
            // alert("share permission request is denied ");
            break;
          default:
        }
      }
    },

    //11 此回调用于处理屏幕共享
    onAsOnSharingState: function (ret) {
      if (ret.info.state == 0) {
        isNochairSharing = 0;
      }
    },

    //12 This callback is used to handle call incoming
    onCallIncomming: function (ret) {
      if (ret.result) {
        confirm({
          title: "您有一个呼叫，是否加入?",
          okText: "确定",
          cancelText: "取消",
          onOk() {
            client.answerCall(true, ret.info.isVideo === 1);
          },
          onCancel() {
            client.answerCall(false, ret.info.isVideo === 1);
          },
        });
      }
    },

    //13 This callback is used to handle call ringing
    onCallRingBack: function (ret) {
      message.info("正在呼叫...");
    },

    //14 This callback is used to handle
    onEvtCallRtpCreated: function (ret) {
      console.info("call timeout");
    },

    //15 This callback is used to handle call connection
    onCallConnected: function (ret) {
      console.info("the call is connected");
      //call.
    },

    //16 此回调用于处理呼叫挂断
    onCallEnded: function (ret) {
      if (ret.param.callInfo.reasonCode === 50331781) {
        _this.props.dispatch({
          type: `client/setJoinMeetingStatus`,
          payload: {
            joinMeetingStatus: false,
            isSuccessJoinMeeting: false,
          },
        });
        message.warning("加入会议失败");
      }

      //呼叫未响应
      if (ret.param.callInfo.reasonCode == "50331762") {
        message.warning("呼叫方未来电提醒");
      }
    },

    //17 This callback is used to add a video
    onAddVideoRequest: function (ret) {
      if (ret.result) {
        alert("onAddVideoRequest");
      }
    },

    //18 This callback is used to delete a video
    onDelVideoRequest: function (ret) {
      if (ret.result) {
        alert("onDelVideoRequest");
      }
    },

    //19 音视频转换结果
    onCallModifyVideoResult: function (ret) {
      if (ret.result) {
        alert("onCallModifyVideoResult:" + JSON.stringify(ret));
      }
    },

    onNewServiceRight: function (ret) {
      if (ret.result) {
      }
    },

    onSetIptServiceResult: function (ret) {
      alert("onSetIptServiceResult:" + JSON.stringify(ret));
    },

    onCallBldTransferRecvSucRsp: function (ret) {
      alert("onCallBldTransferRecvSucRsp:" + JSON.stringify(ret));
    },

    onCallBldTransferResult: function (ret) {
      alert("onCallBldTransferResult:" + JSON.stringify(ret));
    },

    onPluginEvtClickHangupCall: function (ret) {
      var call = client.getCallHandler();
      if (call == null) {
        return;
      }
      client.hangup();
    },

    onEvtGetDataconfParamResult: function (ret) {
      if (ret.result) {
        client.joinDataConference();
      } else {
      }
    },

    onPluginEvtClickMuteMic: function (ret) {
      console.log("onPluginEvtClickMuteMic:" + JSON.stringify(ret));
    },

    onPluginEvtClickMuteSpeaker: function (ret) {
      console.log("onPluginEvtClickMuteSpeaker:" + JSON.stringify(ret));
    },

    onPluginEvtClickMuteCamera: function (ret) {
      console.log("onPluginEvtClickMuteCamera:" + JSON.stringify(ret));
    },

    onPluginEvtClickAddMember: function (ret) {
      client.uiPluginSetButtonState(3, 1, (ret) => {});
      var transfer2ConfParam = null;
      var memberList = prompt("Please enter the invitee number", "");

      if (ret.info.videoType == 0) {
        if (memberList != undefined && memberList != null && memberList != "") {
          var memberListArr = memberList.split(",");
          var memberListTemp = new Array();
          for (var i = 0; i < memberListArr.length; i++) {
            memberListTemp[i] = {
              number: memberListArr[i],
              name: "",
              smsPhone: "",
              email: "",
              autoInvite: 1,
              role: 0,
              extensions: "",
            };
          }
          transfer2ConfParam = { attendees: memberListTemp };
        } else {
          transfer2ConfParam = null;
        }
        client.transfer2Conf(transfer2ConfParam);
      } else {
        if (memberList != undefined && memberList != null && memberList != "") {
          var cloudecAttendeesArray = memberList.split(",");
          var cloudecAttendees = new Array();
          for (var i = 0; i < cloudecAttendeesArray.length; i++) {
            cloudecAttendees[i] = {
              number: cloudecAttendeesArray[i],
              name: cloudecAttendeesArray[i],
              role: 0,
            };
          }

          client.addAttendee(cloudecAttendees);
        } else {
          console.log("attendee number is empty");
          return;
        }
      }
    },

    //更改视频窗口大小
    onPluginEvtSetWindowSize: function (ret) {
      console.log("onPluginEvtSetWindowSize:" + JSON.stringify(ret));
    },

    onPluginEvtClickLeaveConf: function (ret) {
      client.leaveConf();
    },

    onPluginEvtClickEndConf: function (ret) {
      client.endConf();
    },

    onPluginEvtClickShowMemberList: function (ret) {
      client.uiPluginSetButtonState(4, 1, (ret) => {});
      console.log("onPluginEvtClickShowMemberList:" + JSON.stringify(ret));
    },

    onPluginEvtConfCtrlOperation: function (ret) {
      //延长会议
      console.log("onPluginEvtConfCtrlOperation:" + JSON.stringify(ret));
    },

    onPluginEvtClickStartShare: function (ret) {
      if (ret.info.videoType == 0) {
        isPluginClickShare = 0;
        client.transfer2Conf(null);
      } else {
        client.getAttendeeList(function (ret) {
          if (ret) {
            var attendeeList = new Array();
            attendeeList = ret.info;
            for (var i = 0; i < attendeeList.length; i++) {
              var member = attendeeList[i];
              if (member.isSelf == 1 && member.role == 1) {
                client.startScreenSharing(member.number, "");
              } else if (member.isSelf == 1 && member.role != 1) {
                isNochairSharing = 1;
                client.startScreenSharing(member.number, "");
              }
            }
          }
        });
      }
    },

    onPluginEvtClickStopShare: function (ret) {
      console.log("onPluginEvtClickStopShare:" + JSON.stringify(ret));
    },

    onPluginEvtClickRequestRemoteControl: function (ret) {
      console.log(
        "onPluginEvtClickRequestRemoteControl:" + JSON.stringify(ret)
      );
    },

    onPluginEvtClickReleaseRemoteControl: function (ret) {
      var number = prompt("Please enter the number", "");
      if (number != undefined && number != null && number != "") {
        client.setRemoteCtrl(1, 0, number);
      } else {
      }
      console.log(
        "OnPluginEvtClickReleaseRemoteControl:" + JSON.stringify(ret)
      );
    },

    onEvtConfctrlOperationResult: function (ret) {
      console.log(ret)
      if (ret.info.reasonCode === 0) {
        message.info(
          EC_ConfctrlOperationResult[ret.info.operationType] + "成功"
        );
      } else {
        message.error(
          EC_ConfctrlOperationResult[ret.info.operationType] + "失败"
        );
      }
    },

    onPluginEvtClickDevicesSetting: function (ret) {
      alert("Please start setting up the video and video settings you need.");
    },

    onEvtModifyPasswordResult: function (ret) {
      if (ret.info.reasonCode == 0) {
        alert("password has been updated.");
      } else {
        alert(
          "modify password failed >>>errorCode:" +
            ret.info.reasonCode +
            "errorInfo:" +
            ret.info.reasonDescription
        );
      }
    },
    onEvtStatisticInfo: function (ret) {
      console.log(ret);
      console.log("onEvtStatisticInfo");
    },

    onEvtSvcWatchInfoInd: function (ret) {
      console.log("onEvtSvcWatchInfoInd");
    },

    onEvtJoinDataConfResult: function (ret) {
      console.log(ret);
      if (isPluginClickShare == 1 && ret.result == 0) {
        isPluginClickShare = 0;
        client.getAttendeeList(function (ret) {
          if (ret) {
            var attendeeList = new Array();
            attendeeList = ret.info;
            for (var i = 0; i < attendeeList.length; i++) {
              var member = attendeeList[i];
              if (member.isSelf == 1 && member.role == 1) {
                client.startScreenSharing(member.number, "");
              }
            }
          }
        });
      } else {
        isPluginClickShare = 0;
      }
    },
    //匿名加入会议事件（但是匿名加入成功也会走onConfConnected，所以这里只处理失败的情况）
    OnEvtGetTempUserResult: function (ret) {
      if (ret.param.reasonCode === 0) {
        // message.info('匿名加入会议成功')
      } else {
        _this.props.dispatch({
          type: `client/setJoinMeetingStatus`,
          payload: {
            joinMeetingStatus: false,
            isSuccessJoinMeeting: false,
          },
        });
        message.warning("匿名加入会议失败");
      }
    },
    //以下是新增事件
    OnEvtRequestConfRightFailed: function (ret) {
      console.log("Request conference right failed.");
    },

    //媒体错误信息通知
    OnEvtMediaErrorInfo: function (ret) {
      console.log("OnEvtMediaErrorInfo" + JSON.stringify(ret));
    },

    //主席主动调用结束会议接口会收到OnEndConferenceResult事件
    OnEndConferenceResult: function (ret) {
      console.log("OnEndConferenceResult" + JSON.stringify(ret));
      if (ret.param.result == 0) {
        message.info("会议已结束");
        endConference(_this);
        // _this.props.dispatch({
        //   type: `client/setCurrentConferID`,
        //   payload: {
        //     currentConferID: null,
        //     currentConferTopic: null,
        //   },
        // });
        // _this.props.dispatch({
        //   type: `client/setISRefreshMeetingList`,
        //   payload: {
        //     updateISRefreshMeetingList: true,
        //   },
        // });
        // //如果现在是在会控页面，那就返回到主页面
        // setTimeout(() => {
        //   if (_this.props.history.location.pathname === "/meeting/control") {
        //     _this.props.history.go(-1);
        //   }
        // }, 1000);
      }
    },
    //退出失败
    OnEvtLogoutFailed: function (ret) {
      console.log("OnEvtLogoutFailed" + JSON.stringify(ret));
      message.error("会议退出失败");
    },

    //设置共享所有者失败
    OnEvtConfSetShareOwnerFailed: function (ret) {
      console.log("OnEvtConfSetShareOwnerFailed" + JSON.stringify(ret));
      message.error("设置共享所有者失败");
    },
    //开始共享失败
    OnEvtConfStartShareFailed: function (ret) {
      console.log("OnEvtConfStartShareFailed" + JSON.stringify(ret));
      message.error("开始共享失败");
    },
  };
  let client = cloudEC.createClient(listeners);
  this.props.dispatch({
    type: `client/setClient`,
    payload: {
      client,
    },
  });
  return client;
}

/*
 *结束会议的刷新事件，
 *主席自动结束与与会者接受结束事件
 */
function endConference(_this) {
  _this.props.dispatch({
    type: `client/setCurrentConferID`,
    payload: {
      currentConferID: null,
      currentConferTopic: null,
    },
  });
  _this.props.dispatch({
    type: `client/setISRefreshMeetingList`,
    payload: {
      updateISRefreshMeetingList: true,
    },
  });
  //如果现在是在会控页面，那就返回到主页面
  setTimeout(() => {
    if (_this.props.history.location.pathname === "/meeting/control") {
      _this.props.history.go(-1);
    }
  }, 1000);
}
