const client = require(path.join(__dirname, '../', 'js', 'module', 'client.js'))


let login_app = new Vue({
    el: '#login_app',
    mounted: function(){
        this.onWindowLoad();
    },
    data: {
        /** 版本信息 */
        version: '',
        /** 机构信息 */
        app_icon_url: '../css/img/logo/logo.png',
        app_title_name: '',
        /** 弹窗信息 */
        is_loading: false,
        is_show_msg: false,
        is_show_dialog: false,
        dialog_title: '',
        dialog_msg: '',
        dialog_button: [],
        dialog_callback: 0,
        /** 输入信息 */
        input_company_id: '',
        input_room_id: '',
        input_user_id: '',
        input_password: '',
        input_nick_name: '',
        input_class_password: '',
        input_remember: false,
        input_layout: "demo_portrait",
        /** 状态变量 */
        is_demo_mode: g_data.mode == 'demo',
        is_guest_mode: false,
        is_show_password: false,
        is_show_error_msg: false,
        is_show_set_menu: false,
        error_msg: ''
    },
    created: function(){

    },
    methods: {
        /** 窗口事件 */
        onWindowLoad: function(){
            // 获取当前版本
            var package = require("../package.json");
            this.version = package.version;

            // 有存储机构信息才显示关于页
            if (g_storage.getItem('companyId')){
                this.is_show_set_menu = true;
            }

            client.init(g_data.test);
            this.inputCompanyId();
            var lastMode = g_storage.getItem('mode');
            this.is_guest_mode = g_storage.getItem('guestMode');
            if (g_data.mode === lastMode){
                if (this.is_demo_mode){
                    this.input_room_id = g_storage.getItem('classId');
                    this.input_nick_name = g_storage.getItem('nickName');
                }else if (this.is_guest_mode){
                    this.input_company_id = '170470';
                    this.input_room_id = g_storage.getItem('classId');
                    this.input_nick_name = g_storage.getItem('nickName');
                }else{
                    this.input_company_id = '170470';
                    this.input_room_id = g_storage.getItem('classId');
                    this.input_user_id = g_storage.getItem('userId');
                    this.input_remember = g_storage.getItem('rememberPwd');
                    if (g_storage.getItem('rememberPwd')){
                        this.input_password = g_storage.getItem('userToken');
                    }                
                }
            }      
            document.addEventListener('keyup', (event)=>{
                if (event.keyCode == 13){
                    if (this.is_demo_mode){
                        this.enterDemoClass();
                    }else if (this.is_guest_mode){
                        this.enterByPassword();
                    }else{
                        this.enterByAccount();
                    }
                }
            })
        },
        minWindow: function(){
            sendIpcMessage('ComWin:Sys', 'min');
        },
        maxWindow: function(){
            sendIpcMessage('ComWin:Sys', 'max');
        },
        enterSet: function(){
            sendIpcMessage('WIN_LOGIN:SET');
        },
        closeWindow: function(){
            sendIpcMessage('ComWin:Sys', 'close');
            sendIpcMessage('QUITAPP');
        },
        setGuestMode: function(isGuestMode){
            this.is_guest_mode = isGuestMode;
        },
        switchPasswordMode: function(){
            log.info("[TAG-LOGIN] switchPasswordMode->enter");
            this.is_show_password = !this.is_show_password;
        },
        inputCompanyId: function(){
            this.input_company_id = '170470';
            if (0 != this.input_company_id){
                this.updateCompanyInfo(parseInt(this.input_company_id));
            }
        },
        checkVersion: function(companyId, callback){
            client.checkVersion(companyId, this.version, (ret, json)=>{
                if (ret){
                    if (compareVersion(this.version, json.latest_version)){
                        callback();
                    }else{
                        var items = ['去升级'];
                        if (!json.force_update){
                            items.push('不用了');
                            if (g_storage.getItem('updateNotify')){    // 非强制升级仅提醒一次
                                log.info("[TAG-LOGIN] do not notify for unforce update: "+json.latest_version);                                
                                callback();
                                return;
                            }
                            g_storage.setItem('updateNotify', true);
                        }
                        this.showDialog('检测到有新版本['+json.latest_version+']啦，快去下载升级吧!', items, (index)=>{
                            if (0==index){  // 升级
                                shell.openExternal(json.download_url);
                                this.closeWindow();
                            }else if (1==index){    // 忽略
                                callback();
                            }
                        })
                    }
                }else{
                    log.error("获取版本信息失败: "+json.error_msg);
                    callback();
                }
            })
        },
        enterByAccount: function(){
            this.input_company_id = '170470';
            if (0==this.input_company_id || this.input_user_id.length<1 || this.input_password.length<1){
                this.showErrorMsg("输入信息不能为空");
            }else{
                this.checkVersion(this.input_company_id, ()=>{
                    g_data.companyId = parseInt(this.input_company_id);
                    g_data.classId = parseInt(this.input_room_id);
                    g_data.userId = this.input_user_id;
                    g_data.guest = false;
                    g_data.userToken = this.input_password;
                    g_data.classToken = '';
                    g_storage.setItem('guestMode', this.is_guest_mode);
                    g_storage.setItem('rememberPwd', this.input_remember);
                    sendIpcMessage('WIN_CLASS:OPEN', {});
                    //sendIpcMessage('WIN_CLASSLIST:OPEN', {});
                })        
            }
        },
        enterByPassword: function(){
            if (0==this.input_room_id || this.input_nick_name.length<1){
                this.showErrorMsg("输入信息不能为空");
            }else{
                g_data.classId = parseInt(this.input_room_id);
                g_data.classToken = this.input_class_password;
                client.getGuestInfo(g_data.classId, this.input_nick_name, (ret, json)=>{
                    if (ret){
                        g_data.companyId = json.enterprise_id;
                        g_data.userId = json.user_id;
                        g_data.userToken = json.password;
                        g_data.guest = true;
                        this.checkVersion(json.enterprise_id, ()=>{
                            g_storage.setItem('guestMode', this.is_guest_mode);
                            g_storage.setItem('nickName', this.input_nick_name);
                            sendIpcMessage('WIN_CLASS:OPEN', {});
                        })                        
                    }else{
                        this.showErrorMsg("获取信息失败: "+json.error_msg);
                    }
                })
            }
        },
        enterDemoClass: function(){
            if (this.input_room_id==0 || this.input_nick_name.length<1){
                this.showErrorMsg("输入信息不能为空");
            }else{
                g_data.test = this.input_nick_name.startsWith("d@");
                g_data.classId = parseInt(this.input_room_id);
                var lastNick = g_storage.getItem('nickName');
                var userId = "";
                if (this.input_nick_name === lastNick){    // 昵称不变，尽量用户不变
                    userId = g_storage.getItem('userId');
                    g_data.userId = userId;
                    g_data.userToken = g_storage.getItem('userToken');
                }
                this.input_password = g_storage.getItem('userToken');
                client.init(g_data.test, 0, userId);
                client.initInfo(g_data.classId, this.input_nick_name, this.input_layout, (ret, response)=>{
                    if (!ret){
                        this.showErrorMsg("获取用户信息失败:"+response.error_code);                        
                    }else{
                        g_data.sdkAppId = parseInt(response.sdkappid);
                        g_data.companyId = parseInt(response.enterprise_id);
                        g_data.userSig = response.user_sig;
                        g_data.env = response.env;
                        if (response.user_id.length>1){
                            g_data.userId = response.user_id;
                            g_data.userToken = response.user_token;
                        }
                        g_storage.setItem("nickName", this.input_nick_name);
                        sendIpcMessage('WIN_CLASS:OPEN', {});
                    }
                })
            }
        },
        /** 内部方法 */
        showDialog: function (message, buttons, callback) {
            this.dialog_title = '提示';
            this.dialog_msg = message;
            this.dialog_button = buttons;
            this.dialog_callback = callback;
            this.is_show_msg = true;
        },
        updateCompanyInfo: function(companyId){
            client.getCompanyInfo(companyId, (ret, json)=>{
                if (ret){
                    //this.app_icon_url = json.icon;
                    this.app_title_name = json.name;
                }
            })
        },
        onDlgClick: function (index) {
            if (null != this.dialog_callback) {
                this.dialog_callback(index);
            }
            this.is_show_msg = false;
        },
        showErrorMsg: function(message){
            this.error_msg = message;
            this.is_show_error_msg = true;
        }
    }
})

Vue.config.errorHandler = (err, vm) =>{
    let { message, name, script, line, column, stack } = err;
    // 在vue提供的error对象中，script、line、column目前是空的。但这些信息其实在错误栈信息里可以看到。
    script = script ? script : '';
    line = line ? line : 0;
    column = line ? line : 0;
    // 解析错误栈信息
    let stackStr = stack ? stack.toString() : `${name}:${message}`;

    log.error("[TAG-CLASS] exception->"+stackStr);
}