// pages/index-guest/index-guest.js
const app = getApp();
const util = require('../../utils/util.js');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgPath: app.globalData.imgPath,
        path: app.globalData.path,
        app_bottom: '大城细管·大城众管·大城智管',
        nowTime: util.formatDate(null, 'yyyy.MM.dd'),
        nextMeeting: null,
        hasNext: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 加入群聊
        if (wx.getStorageSync('groupId')) {
            let groupId = wx.getStorageSync('groupId');
            util.post({
                url: '/api/easemob/addGroupUser',
                data: {
                    chatgroupid: groupId,
                    usernames: [wx.getStorageSync('myUsername')]
                },
                success: (res) => {
                    wx.hideLoading();
                    console.info('addGroupUser', res);
                    if (res.data.code != 200) {
                        util.toast(res.data.msg);
                    } else {
                        let datas = res.data.data;
                        if (datas && datas.error) {
                            if (datas.error == 'not_found') {
                                wx.showModal({
                                    content: '您要加入的群聊不存在',
                                    showCancel: false
                                });
                            } else if (datas.error == 'forbidden_op') {
                                wx.showModal({
                                    content: '您已经在群聊中了，请不要重复加入',
                                    showCancel: false,
                                    success: (res) => {
                                        util.get({
                                            url: '/api/easemob/queryGroupDetails/' + groupId,
                                            success: (res) => {
                                                wx.hideLoading();
                                                console.info(res);
                                                if (res.data.code == 200) {
                                                    var nameList = {
                                                        myName: wx.getStorageSync('myUsername'),
                                                        your: res.data.data.data[0].name,
                                                        groupId: groupId
                                                    };
                                                    wx.navigateTo({
                                                        url: "../chat-group-detail/chat-group-detail?username=" + JSON.stringify(nameList)
                                                    });
                                                } else {
                                                    util.toast(res.data.msg);
                                                }
                                            }
                                        });
                                    }
                                });
                            } else {
                                util.toast(datas.error);
                            }
                        } else {
                            wx.showModal({
                                content: '群聊加入成功',
                                showCancel: false,
                                success: (res) => {
                                    util.get({
                                        url: '/api/easemob/queryGroupDetails/' + groupId,
                                        success: (res) => {
                                            wx.hideLoading();
                                            console.info(res);
                                            if (res.data.code == 200) {
                                                var nameList = {
                                                    myName: wx.getStorageSync('myUsername'),
                                                    your: res.data.data.data[0].name,
                                                    groupId: groupId
                                                };
                                                wx.navigateTo({
                                                    url: "../chat-group-detail/chat-group-detail?username=" + JSON.stringify(nameList)
                                                });
                                            } else {
                                                util.toast(res.data.msg);
                                            }
                                        }
                                    });
                                }
                            });
                        }
                    }
                    wx.removeStorageSync('groupId');
                }
            });
        }
    },

    onReady: function () {
        let that = this;
        let userInfo = wx.getStorageSync('userInfo');
        let roleInfo = wx.getStorageSync('roleInfo');

        if (!userInfo.usernameShow || !userInfo.nickName || !userInfo.headImgUrl) {
            wx.showModal({
                content: '轻应用需要取您的用户信息',
                showCancel: false,
                confirmText: '确定',
                success: (res) => {
                    if (res.confirm) {
                        wx.getUserProfile({
                            desc: '提升用户体验感',
                            success: (res) => {
                                userInfo.usernameShow = res.userInfo.nickName;
                                userInfo.nickName = res.userInfo.nickName;
                                userInfo.headImgUrl = res.userInfo.avatarUrl;
                                that.setData({
                                    username: userInfo.usernameShow,
                                    role_name: roleInfo.name,
                                    roleCode: roleInfo.code,
                                });
                                util.post({
                                    url: '/sys/user/updateNoAuth',
                                    data: {
                                        id: userInfo.id,
                                        nickName: res.userInfo.nickName,
                                        usernameShow: res.userInfo.nickName,
                                        headImgUrl: res.userInfo.avatarUrl
                                    }
                                });
                            },
                            fail: (res) => {
                                util.toast('拒绝授权将影响您的体验感');
                                that.setData({
                                    username: '未知用户',
                                    role_name: roleInfo.name,
                                    roleCode: roleInfo.code,
                                });
                            }
                        });
                    }
                },
            });
        } else {
            that.setData({
                username: userInfo.usernameShow,
                role_name: roleInfo.name,
                roleCode: roleInfo.code,
            });
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let that = this;
        let userInfo = wx.getStorageSync('userInfo');
        if (userInfo.usernameShow) {
            that.setData({
                username: userInfo.usernameShow
            });
        }

        // 下一场会议
        util.get({
            url: '/api/meeting/info/getNextMeeting',
            success: (res) => {
                wx.hideLoading();
                if (res.data.code != 200) {
                    util.toast(res.data.msg);
                } else {
                    let datas = res.data.data;
                    if (datas) {
                        that.setData({
                            hasNext: true,
                            nextMeeting: datas,
                            nextTitle: datas.title,
                            nextTime: util.formatDate(datas.receptionTime),
                            nextUnit: datas.receptionObject
                        });
                    }
                }
            }
        });
    },

    /**
     * 点击查看下一场会议详情
     */
    meetingInfo: function () {
        let nextMeeting = this.data.nextMeeting;
        if (nextMeeting) {
            wx.navigateTo({
                url: '../meeting-cover/meeting-cover?id=' + JSON.stringify(nextMeeting.id),
            });
        } else {
            util.toast('暂无下一场会议');
        }
    },

    /**
     * 日常巡检
     */
    dailyInspection: function () {
        wx.navigateTo({
            url: '../daily-inspection/daily-inspection',
        });
    },

    /**
     * 发布会议信息
     */
    informationRelease: function () {
        wx.navigateTo({
            url: '../information-release/information-release',
        });
    },

    /**
     * 会议巡检
     */
    meetingInspection: function () {
        wx.navigateTo({
            url: '../meeting-list/meeting-list?type=INSPECTION',
        });
    },

    /**
     * 分享海报
     */
    meetingCover: function () {
        wx.navigateTo({
            url: '../meeting-list/meeting-list',
        });
    },

    /**
     * 点击参观议程跳转至会议列表
     */
    visitAgenda: function () {
        wx.navigateTo({
            url: '../meeting-list/meeting-list',
        });
    },

    /**
     * 图片回传
     */
    uploadImage: function () {
        let that = this;
        wx.chooseImage({
            count: 1,
            success: function (res) {
                console.info(res);
                wx.uploadFile({
                    filePath: res.tempFilePaths[0],
                    name: 'file',
                    url: that.data.path + '/api/upload/record/upload',
                    header: {
                        "Content-Type": "multipart/form-data",
                        "Authorization": wx.getStorageSync('Authorization')
                    },
                    formData: {
                        fileType: 10
                    },
                    success(res) {
                        wx.hideLoading();
                        let datas = JSON.parse(res.data);
                        console.info(datas)
                        if (datas.code != 200) {
                            util.toast(datas.msg);
                        } else {
                            util.toast(datas.msg);
                        }
                    }
                });
            }
        });
    },

    /**
     * 内容投屏
     */
    contentScreen: function () {
        // 打开微信扫一扫
        wx.scanCode({
            onlyFromCamera: true,
            scanType: 'qrCode',
            success: (res) => {
                console.info('scanCode', res);
                if (res.path) {
                    let scene = res.path.split('=')[1];
                    util.get({
                        url: '/api/wechat/getQrCodeParams?key=' + scene,
                        success: (res) => {
                            console.info('getQrCodeParams', res);
                            if (res.data.code != 200) {
                                wx.hideLoading();
                                util.toast(res.data.msg);
                            } else {
                                if ('WIFI' == res.data.data.type) {
                                    let wifi = res.data.data.wifi;
                                    let password = res.data.data.password;
                                    // 获取设备系统类型
                                    wx.getSystemInfo({
                                        success: (res) => {
                                            console.info(res);
                                            if (!res.wifiEnabled) {
                                                wx.hideLoading();
                                                util.toast('请打开WIFI功能');
                                                return;
                                            }
                                            // 1、初始化Wi-Fi模块
                                            wx.startWifi({
                                                success: (res) => {
                                                    console.info('startWifi', res);
                                                    if (res.errMsg == 'startWifi:ok') {
                                                        // 4、连接Wi-Fi
                                                        wx.connectWifi({
                                                            SSID: wifi,
                                                            password: password,
                                                            success: (res) => {
                                                                wx.hideLoading();
                                                                console.info('connectWifi', res);
                                                                if (res.errMsg == 'connectWifi:ok') {
                                                                    util.toast('WIFI连接成功', 'success');
                                                                } else {
                                                                    util.toast(res.errMsg);
                                                                }
                                                            },
                                                            fail: (e) => {
                                                                wx.hideLoading();
                                                                console.info(e);
                                                                util.toast('WIFI连接失败');
                                                            }
                                                        });
                                                    } else {
                                                        wx.hideLoading();
                                                        util.toast(res.errMsg);
                                                    }
                                                },
                                                fail: (e) => {
                                                    wx.hideLoading();
                                                    console.info(e);
                                                    util.toast('初始化WiFi模块失败');
                                                }
                                            });
                                        },
                                        fail: (e) => {
                                            wx.hideLoading();
                                            util.toast('获取设备系统类型失败');
                                        }
                                    });
                                } else {
                                    wx.hideLoading();
                                    util.toast('请扫描WIFI小程序码');
                                }
                            }
                        }
                    });
                } else {
                    util.toast('请扫描WIFI小程序码');
                }
            },
            fail: (e) => {
                console.info('chooseImage fail', e)
                if (e.errMsg == 'scanCode:fail cancel') {
                    util.toast('取消扫码');
                } else {
                    util.toast('扫码失败，请重试');
                }
            }
        });
    },

    /**
     * 聊天室
     * @param {*} e 
     */
    chatRoom: function (e) {
        wx.navigateTo({
            url: '../chat-room/chat-room',
        });
    },

    /**
     * 地图
     */
    lightMap: function () {
        wx.navigateTo({
            url: '../light-map/light-map',
        });
    },

    /**
     * 文件浏览
     */
    fileBrowse: function () {
        wx.navigateTo({
            url: '../file-browse/file-browse',
        });
    },

    /**
     * 故障处理
     */
    faultHandle: function () {
        wx.navigateTo({
            url: '../fault-list/fault-list',
        })
    }

})