var Meeting = function Meeting() {
    this.localUserInfo = {
        //创建会议的参数对象
        name: "", //会议名称
        masterId: "", //主持人用户ID
        masterName: "", //主持人名字
        masterNumber: "", //主持人号码
        region: "", //号码对应的PAAS域ID
        record: true, //是否录像录音true:录像录音 false:不录
        type: "video", //会议类型“audio”: 音频会议 “video”: 音视频会议
        mode: "group", //会议模式“p2p”:点对点“group”:群聊
    };
    this.InvitedMembers = {
        //邀请会议的参数对象
        id: "", //会议id
        inviteId: "", //邀请人ID
        inviteName: "", //邀请人名字
        inviteNumber: "", //邀请人号码
        member: [],
    };
    this.InvitedMembersSingle = {
        //单兵
        id: "", //会议id
        inviteId: "", //邀请人ID
        inviteName: "", //邀请人名字
        inviteNumber: "", //邀请人号码
        member: [],
    };
    this.InvitedMembersVehicle = {
        //车载
        id: "", //会议id
        inviteId: "", //邀请人ID
        inviteName: "", //邀请人名字
        inviteNumber: "", //邀请人号码
        member: [],
    };
    this.InvitedMembersUav = {
        //无人机
        id: "", //会议id
        inviteId: "", //邀请人ID
        inviteName: "", //邀请人名字
        inviteNumber: "", //邀请人号码
        member: [],
    };
    this.InvitedMembersTalkie = {
        //对讲机
        id: "", //会议id
        inviteId: "", //邀请人ID
        inviteName: "", //邀请人名字
        inviteNumber: "", //邀请人号码
        member: [],
    };
    this.inviteSelf = {
        userName: "",
        department: "",
        userId: "",
        region: "",
        number: "",
        type: "client",
    };
    this.meetingInfoback = ""; //各个接口返回信息
    this.$Message = {
        warning: (data) => {
            console.log(data);
            // alert(data)

        }
    };
    this.targetid = "vPlayArea"
};

Meeting.prototype = {
    initSocket(userCode, callback) {
        const self = this;
        //初始websocket实例，保存在window中方便调用。一个浏览器tab页面只能初始化一次。所有的控件窗口，通过该websocket实例去生成不同的窗口实例，不同的控件窗口通过自己的窗口实例去调用初始化、关闭、隐藏等
         window.theSocket= this.theSocket = new InitWebSocketClass(
            userCode,
            localStorage.getItem("token"), {
                //客户端登陆成功通知;
                loginSuccess: (v) => {
                    console.log("loginSuccess-->", v);
                    // self.initWnd();
                },
                //客户端窗口被拉起通知
                onCreateVideoSuccess: (v) => {
                    console.log("客户端onCreateVideoSuccess-----", v);
                },
                //重点:统一分发客户端ws消息;vue 可以统一用$bus分发.第三方消息分发自定
                onSocketBackInfos: (data) => {
                    //视频窗口创建成功通知
                    if (
                        data &&
                        data.method === "createVideoDialogReuslt" &&
                        data.params.result === 0
                    ) {
                        if (data.params.handleName === "#"+this.targetid) {
                            //客户端窗口创建好后,界面显示窗口;
                            callback && callback()
                            self[self.targetid].resize();
                            this.$Message.warning("视频窗口创建成功！");
                        }
                    }
                },
            }
        );
        //socket实例初始化websocket回调方法;
        window.theSocket
            .initWebSocket()
            .then((v) => {
                if (v) {
                    this.$Message.warning("视频插件登陆完成!");
                }
                callback();
            })
            .catch((v) => {
                this.$Message.warning("若要观看实时视频，请先安装视频插件大华应急指挥调度实战平台客户端打开失败, 请尝试刷新页面重试");
            });

    },
    //初始化视频窗口实例,先获取自己用户code,再初始化窗口,严格按照封装参数传,别漏了
    getUserCode(callback) {
        let self = this;
        $.ajax({
            type: "GET",
            url: setting.URL + "/ras/user/info",
            contentType: "application/json", //如果提交的是json数据类型，则必须有此参数,表示提交的数据类型
            dateType: "json",
            beforeSend: (xhr) => {
                xhr.setRequestHeader("X-Subject-Token", localStorage.getItem("token"));
                xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            },
            success: (res) => {
                //obj
                if (res && res.userCode) {
                    let {
                        userCode
                    } = res;
                    //初始化websocket;
                    return self.initSocket(userCode, callback);
                }
            },
        });
    },
    //初始化视频窗口-dom
    initWnd() {
        //左边窗口类型参数 分割 2行2列
        const typeObj = {
            rows: 1,
            cols: 1,
            wndSpaceing: 0,
            embedVideoMode: true,
            playerCtrlBarEnable: false,
            displayMode: 1,
            playMode: 0,
            playParams: {},
            webControlExpend: true
        };
        //左边窗口实例
        window[this.targetid] = this[this.targetid] = new VideoPlay(
            "#"+this.targetid,
            window.theSocket.websocket, //一个浏览器tab页面公用一个
            window.theSocket.socketCode, //一个浏览器tab页面公用一个
            typeObj
        );
        //左边窗口初始化
        this[this.targetid].init();
    },
    //播放视频
    playVideo(item) {

        if (!window.theSocket.websocket) {
            this.$Message.warning("请先打开视频插件");
            return;
        }
        if (item.type == "client") {
            this.slectOptionmini(item.userId).then((arr) => {
                if (arr) {
                    this[this.targetid].openAppVideo(arr);
                }
            });
        } else if (item.type == "single") {
            //播放单兵视频
            this.pullFlow(item.channelId);
        } else if (item.type == "vehicle") {
            //播放车载视频
            this.pullFlow(item.channelId);
        } else if (item.type == "uav_dev") {
            //播放无人机视频
            this.pullFlow(item.channelId);
        }
    },
    //   setDesignDivision(rows, cols) {
    //     // console.log(this.localUserInfo);
    //     const params = JSON.stringify({
    //         loginIp: setting.URL,
    //         method: "SetDesignDivision",
    //         userCode: this.localUserInfo.masterId,
    //         params: {
    //             handleName:'#vPlayArea',
    //             rows: Number(rows),
    //             cols: Number(cols)
    //         },
    //         socketCode: window.theSocket.socketCode
    //     });
    //     console.log(params);
    //     this.webSocketSend(params);
    // },
    //设备视频拉流
    pullFlow(chinnelId) {
      
        if (chinnelId) {
            this[this.targetid].showBrower(true);
            this[this.targetid].dragResize(0,0,0,0);
            window[this.targetid] && window[this.targetid].realTimeVideo && window[this.targetid].realTimeVideo([{
                "channelId": chinnelId
            }]);
        }
    },
    /*  创建会商  */
    async creatMeeting() {
        let _this = this;
        if (!_this.localUserInfo.name) {
            _this.$Message.warning("请创建会商名称");
            return;
        }
        await $.ajax({
            type: "POST",
            url: setting.URL + "/mcu/meeting",
            contentType: "application/json", //如果提交的是json数据类型，则必须有此参数,表示提交的数据类型
            dateType: "json",
            data: JSON.stringify(_this.localUserInfo),
            beforeSend: function(xhr) {
                xhr.setRequestHeader("X-Subject-Token", localStorage.getItem("token"));
                xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                //xhr.setRequestHeader("Origin",null);
            },
            success: function(res) {
                //obj
                _this.InvitedMembers.id = res.id; //创建了会议id,保存起来,为了邀请成员;
                _this.InvitedMembersSingle.id = res.id; //单兵;
                _this.InvitedMembersVehicle.id = res.id; //车载;
                _this.InvitedMembersUav.id = res.id; //无人机;
                _this.InvitedMembersTalkie.id = res.id; //单兵;
                _this.meetingId = res.id;
                localStorage.setItem("meetingId", res.id);
                _this._debug("创建会商返回的信息", res);
                // _this.searchMeetingMember(); //add创建会商然后,开始查会议成员显示在列表中;
            },
            error: function(data) {},
        });
    },
    /* 邀请会商成员 */
    startInvite(member) {
        let _this = this;
        _this.InvitedMembers.member = [
            _this.inviteSelf,
            ...([member] || []),
            //   {
            //     type: "tandemPhone",
            //     number: _this.outLinenum,
            //     userName: _this.outLinenum,
            //     region: _this.paasId,
            //   },
        ];
        $.ajax({
            type: "POST",
            url: setting.URL + "/mcu/meeting/member",
            contentType: "application/json", //如果提交的是json数据类型，则必须有此参数,表示提交的数据类型
            dateType: "json",
            data: JSON.stringify(_this.InvitedMembers),
            beforeSend: function(xhr) {
                xhr.setRequestHeader("X-Subject-Token", localStorage.getItem("token"));
                xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            },
            success: function(res) {
                //obj
                _this._debug("邀请会商成后的信息", res);
                //_this.searchMeetingMember(); //add创建会商然后,开始查会议成员显示在列表中;
            },
            error: function(data) {
                if (data.responseJSON.code == "mcuIdNotExist") {
                    _this.$Message.warning("未创建会商");
                } else if (data.responseJSON.code == "mcuIdInvalid") {
                    _this.$Message.warning("会议ID无效");
                } else if (data.responseJSON.code == "mcuMeetingMemMax") {
                    _this.$Message.warning("会议用户数满");
                }
            },
        });
    },
    /*  关闭会商操作 */
    deleteMeeting() {
        try {
            let _this = this;
            let deleteMeetingId = _this.meetingId;
            if (!deleteMeetingId) {
                _this.$Message.warning("未创建会商");
                _this._debug("未创建会商", "");
                return;
            }
            $.ajax({
                type: "DELETE",
                url: setting.URL + "/mcu/meeting/" + deleteMeetingId,
                contentType: "application/json", //如果提交的是json数据类型，则必须有此参数,表示提交的数据类型
                dateType: "json",
                data: JSON.stringify(_this.localUserInfo),
                beforeSend: function(xhr) {
                    xhr.setRequestHeader("X-Subject-Token", localStorage.getItem("token"));
                    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                },
                success: function(res) {
                    //obj
                    _this._debug("关闭会议成功", res);
                    localStorage.removeItem("meetingId");
                    _this.meetingId = ""; //置空
                    _this.meetMemberList = []; //置空
                    _this.meetMemberList2 = []; //置空
                },
                error: function(data) {
                    //obj
                    _this._debug("关闭会议错误提示", data);
                    if (data.responseJSON.code === "mcuIdNotExist") {
                        _this.$Message.warning("未创建会商");
                    }
                },
            });
        } catch (E) {}
    },

  



    deleteAllMeeting(callback) {
        let _this = this;
        let s = "?";
        var index =0;
        var doindex=0;
        let searchParams = {
            "userDomain": "",
            "userId": _this.localUserInfo.userId,
            "local": "0"
        };
        for (let k in searchParams) {
            s = s + k + "=" + searchParams[k] + "&"
        }
        s = s.substr(0, s.length - 1);
        //console.log(s);
        $.ajax({
            type: 'GET',
            url: setting.URL + "/imu/group/list" + s,
            contentType: "application/json", //如果提交的是json数据类型，则必须有此参数,表示提交的数据类型 
            dateType: 'json',
            beforeSend: function(xhr) {
                xhr.setRequestHeader("X-Subject-Token", localStorage.getItem("token"));
                xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                //xhr.setRequestHeader("Origin",null);
            },
            success: function(res) { //string
                if (res) {
                    _this.allGroupColumnsData = JSON.parse(res).results;
                    _this._debug("查询所有该用户参与的群组信息success", res);

                    //所有与我有关的会商;
                    let allRelateMeeting = [];
                    if (JSON.parse(res).results !== null) {
                        JSON.parse(res).results.forEach((item) => {
                            if (item.meetId) {
                                index++;

                                allRelateMeeting.push(item);
                                $.ajax({
                                    type: "DELETE",
                                    url: setting.URL + "/mcu/meeting/" + item.meetId,
                                    contentType: "application/json", //如果提交的是json数据类型，则必须有此参数,表示提交的数据类型
                                    dateType: "json",
                                    data: JSON.stringify(_this.localUserInfo),
                                    beforeSend: function(xhr) {
                                        xhr.setRequestHeader("X-Subject-Token", localStorage.getItem("token"));
                                        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                                    },
                                    success: function(res) {
                                        //obj
                                        doindex++;
                                        if(doindex == index){
                                            callback();
                                        }
                                    
                                    },
                                    error: function(data) {
                                        //obj
                                        doindex++;
                                        if(doindex == index){
                                            callback();
                                        }
                                      
                                    },
                                });

                            }
                        });
                    }else{
                        callback();
                    }
                    _this._debug("查询所有该用户参与的会商success", allRelateMeeting);
                }
            },
            error: function(data) {
                callback();

            }
        });
    },
    /* 通过deviceCode查询设备channelId */
    searchChinnelId(deviceCode, deviceType) {
        let _this = this;
        return new Promise((resolve) => {
            $.ajax({
                type: "GET",
                url: setting.URL + "/videoService/devicesManager/devices/" + deviceCode,
                contentType: "application/json", //如果提交的是json数据类型，则必须有此参数,表示提交的数据类型
                dateType: "json",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader(
                        "X-Subject-Token",
                        localStorage.getItem("token")
                    );
                    xhr.setRequestHeader(
                        "Content-Type",
                        "application/json;charset=UTF-8"
                    );
                    //xhr.setRequestHeader("Origin",null);
                },
                success: function(res) {
                    //obj
                    if (res) {
                        if (deviceType == "single") {
                            //单兵
                            _this.channelId = res.encoderUnit.channels[0].channelId;
                            resolve(res.encoderUnit.channels[0].channelId);
                            _this._debug(
                                "单兵channelId",
                                res.encoderUnit.channels[0].channelId
                            );
                        } else if (deviceType == "vehicle") {
                            //车载
                            _this.channelId = res.encoderUnit.channels[0].channelId;
                            resolve(res.encoderUnit.channels[0].channelId);
                            _this._debug(
                                "车载channelId",
                                res.encoderUnit.channels[0].channelId
                            );
                        } else if (deviceType == "uav") {
                            //无人机
                            _this.channelId = res.encoderUnit.channels[0].channelId;
                            resolve(res.encoderUnit.channels[0].channelId);
                            _this._debug(
                                "无人机channelId",
                                res.encoderUnit.channels[0].channelId
                            );
                        } else if (deviceType == "talkie") {
                            //对讲机
                            if (res.encoderUnit.channels[0].channelId) {
                                _this.channelId = res.encoderUnit.channels[0].channelId;
                                resolve(res.encoderUnit.channels[0].channelId);
                            }
                            _this._debug(
                                "对讲机channelId",
                                res.devAudioUnit.channels[0].channelId
                            );
                        }
                    }
                },
                error: function(data) {
                    //
                },
            });
        });
    },
    queryUser(userCode) {
        let _this = this;
        return new Promise((resolve) => {
            $.ajax({
                type: "GET",
                url: setting.URL + "/ras/user/" + userCode,
                contentType: "application/json", //如果提交的是json数据类型，则必须有此参数,表示提交的数据类型
                dateType: "json",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader(
                        "X-Subject-Token",
                        localStorage.getItem("token")
                    );
                    xhr.setRequestHeader(
                        "Content-Type",
                        "application/json;charset=UTF-8"
                    );
                },
                success: function(res) {
                    //obj
                    if (res && res.chnId) {
                        resolve(res);
                    }
                },
                error: function(data) {},
            });
        });
    },
    /* app拉流 */
    slectOptionmini(userCode) {
        let _this = this;
        return new Promise((resolve) => {
            $.ajax({
                type: "GET",
                url: setting.URL + "/ras/user/" + userCode,
                contentType: "application/json", //如果提交的是json数据类型，则必须有此参数,表示提交的数据类型
                dateType: "json",
                beforeSend: function(xhr) {
                    xhr.setRequestHeader(
                        "X-Subject-Token",
                        localStorage.getItem("token")
                    );
                    xhr.setRequestHeader(
                        "Content-Type",
                        "application/json;charset=UTF-8"
                    );
                },
                success: function(res) {
                    //obj
                    if (res && res.chnId) {
                        let arr = [{
                            channelId: res.chnId,
                            userCode: res.userCode,
                            regionId: res.paasId,
                            domainId: "",
                        }, ];
                        resolve(arr);
                    }
                },
                error: function(data) {},
            });
        });
    },
    /* 打开客户端 */
    async openClient(callback) {
        return this.getUserCode(callback);
    },
    closeClient() {
        try {
            this.theSocket &&
                this.theSocket.closeClient &&
                this.theSocket.closeClient();
        } catch (E) {}
    },
    closeVideo() {
        try {
            // this.theSocket.closeAllVideo && this.theSocket.closeAllVideo();
            this[this.targetid].closeAllVideo();
            this[this.targetid].showBrower(false);
        } catch (E) {}
    },
    /* 获取群聊fromName */
    async getLocalUserInfo() {
        let _this = this;
        await $.ajax({
            type: "GET",
            url: setting.URL + "/ras/user/info",
            contentType: "application/json", //如果提交的是json数据类型，则必须有此参数,表示提交的数据类型
            dateType: "json",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("X-Subject-Token", localStorage.getItem("token"));
                xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            },
            success: function(res) {
                //obj
                _this.loginPassword = res.loginPassword; //获取登录为密码.为登录用户话机注册做准备(需要res解密)

                _this.localUserInfo.masterName = res.userName;
                _this.localUserInfo.masterId = res.userCode;
                _this.localUserInfo.masterNumber = res.userPhone;
                _this.localUserInfo.region = res.paasId;

                _this.InvitedMembers.inviteId = res.userCode;
                _this.InvitedMembers.inviteName = res.userName;
                _this.InvitedMembers.inviteNumber = res.userPhone;
                _this.inviteSelf = {
                    userName: res.userName + "(系统APP接入)",
                    department: res.deptName,
                    userId: res.userCode,
                    region: res.paasId,
                    number: res.userPhone,
                    type: "client",
                };
                //单兵
                _this.InvitedMembersSingle.inviteId = res.userCode;
                _this.InvitedMembersSingle.inviteName = res.userName;
                _this.InvitedMembersSingle.inviteNumber = res.userPhone;
                //车载
                _this.InvitedMembersVehicle.inviteId = res.userCode;
                _this.InvitedMembersVehicle.inviteName = res.userName;
                _this.InvitedMembersVehicle.inviteNumber = res.userPhone;
                //无人机
                _this.InvitedMembersUav.inviteId = res.userCode;
                _this.InvitedMembersUav.inviteName = res.userName;
                _this.InvitedMembersUav.inviteNumber = res.userPhone;
                //对讲机
                _this.InvitedMembersTalkie.inviteId = res.userCode;
                _this.InvitedMembersTalkie.inviteName = res.userName;
                _this.InvitedMembersTalkie.inviteNumber = res.userPhone;
            },
            error: function(data) {},
        });
    },
    _debug(tip, res) {
        let _this = this;
        _this.meetingInfoback += tip + "--》  " + JSON.stringify(res) + "\n\n";
        // let container = _this.$el.querySelector("#meetResBack textarea");
        // container.scrollTop = container.scrollHeight;
    },
    settargetId(id){
        let _this = this;
        if(id!=""){
            _this.targetid = id;
        }
       
        _this.initWnd();

    }
};