apiready = function() {

    var ctrl = {
        init: {},
        bind: {},
        checkData: {},
        checkIn: {},
        initBD: {},
        listenMessage: {},
        checkToUpdate: {},
        checkHasUpdated: {},
        cmpVersion: {},
        isRemember: false, // 是否勾选了记住密码，默认不记住
    }

    ctrl.init = function() {

        // add start 2019/4/29 kangzhi
        // 检测是否需要记住账号密码
        ctrl.checkIsRemember();
        // add end 2019/4/29 kangzhi

        // 允许调用接口
        $api.disabledRequest = false;

        // add start 2019/4/29 kangzhi
        // 将检测版本是否需要更新，由之前的index页面更改到login登录页面
        ctrl.checkToUpdate();
        ctrl.checkHasUpdated();
        // add end 2019/4/29 kangzhi

        ctrl.bind();
    }

    ctrl.bind = function() {

        $api.addEvt($api.dom("#check-in"), "touchend", function() {
            // $api.addCls($api.dom("#check-in"), 'btn-success');
            var data = ctrl.checkData();
            if (data) {
                ctrl.checkIn(data);
            }
        });

        // 体验账号登录
        // $api.addEvt($api.dom("#cus"), "touchend", function() {
        //     var data = {
        //         "loginFlag": 1
        //     }
        //     ctrl.experience();
        // });

        //点击忘记密码跳转到找回密码页
        $api.addEvt($api.dom("#forget-password"), "touchend", function() {
            api.openWin({
                name: 'forgetPassword',
                url: '../../html/user/findPassWord.html',

            });
        });

        //用户点击了服务条款按钮
        $api.addEvt($api.dom("#protocol"), "touchend", function() {
            api.openWin({
                name: "protocol",
                url: "../../html/user/protocol.html",
                animation: {
                    type: "movein",
                    subType: "from_bottom"
                }
            });
        });

        //阻止android的返回事件
        api.addEventListener({
            name: 'keyback'
        }, function(ret, err) {
            api.closeWidget({});
            return false;
        });

        //阻止ios的返回事件
        api.addEventListener({
            name: 'swiperight'
        }, function(ret, err) {
            return false;
        });

        // add start 2019/4/29 kangzhi
        $api.addEvt($api.dom("#remember-password"), "touchend", function() {

            if ($api.hasCls($api.dom("#remember-password"), 'is-remember')) {

                ctrl.isRemember = false;
                $api.removeCls($api.dom("#remember-password"), 'is-remember');

            } else {

                ctrl.isRemember = true;
                $api.addCls($api.dom("#remember-password"), 'is-remember');

            }

        });
        // add end 2019/4/29 kangzhi
    }

    ctrl.checkData = function() {
        var account = $api.trim($api.val($api.dom("#account")));
        var password = $api.val($api.dom("#password"));

        $api.text($api.dom("#account-tip"), '');
        $api.text($api.dom("#password-tip"), '');

        if (account.length == 0) {
            $api.text($api.dom("#account-tip"), '请输入账号');
            return false;
        }

        if (password.length == 0) {
            $api.text($api.dom("#password-tip"), '请输入密码');
            return false;
        }

        var data = {
            userName: account,
            password: password
        }

        return data;
    }
    // 体验用户登陆
    ctrl.experience = function() {

            $api.post('/admin/rest/user/login_experience', {}, function(ret, err) {
                if (err) {
                    api.toast({
                        msg: '网络错误',
                        duration: 2000,
                        location: 'bottom'
                    });
                    return false;
                }

                if (ret.code == 200) {
                    $api.setStorage("token", ret.body.token);
                    $api.setStorage("username", ret.body.userName);
                    $api.setStorage('cus', '1');
                    var realName = ret.body.replaceTo;
                    $api.setStorage("realName", realName);
                    $api.setStorage("guestKeys", ret.body.originalStr);
                    var cusExperience = true; // 体验客户的标志
                    ctrl.getCus(cusExperience);

                }
            });

        }
        // 通过token 获取客户的信息
    ctrl.getCus = function(cusExperience) {
        $api.get('/ems/rest/customer/token', {}, function(ret, err) {
            if (ret.code == 200) {
                // 如果是园区的董事长或者项目经理登录，
                // 可能存在多个客户（即项目与之对应，所以返回一个客户列表）
                var customers = ret.body.cus; // 返回的客户列表
                // 没有客户信息 禁止登录
                if (!customers || !customers.length) {
                    api.toast({
                        msg: '获取用户信息失败',
                        duration: 2000,
                        location: 'bottom'
                    });
                    return;
                }

                // 存储当前登录人员所对应的所有客户
                $api.setStorage('customers', customers);


                // 默认选择客户列表中的第一个登录 登录之后可以切换（如果多个）
                var currentCus = customers[0];
                // userId
                $api.setStorage("userId", ret.body.userId);
                // 客户角色id 董事长 项目经理 项目负责人
                $api.setStorage('cusRoleType', ret.body.cusRoleType);
                // 非体验客户
                if (!cusExperience) {
                    $api.prefix = ret.body.prefix;
                    $api.setStorageOfCus(currentCus);
                    $api.setStorage('cus', null);
                } else {
                    // 体验客户
                    $api.setStorageOfExperCus(currentCus);
                }


                ctrl.jump()
            } else {
                api.toast({
                    msg: '获取用户信息失败',
                    duration: 2000,
                    location: 'bottom'
                });
            }

        })
    }
    ctrl.checkIn = function(data) {

        $api.post("/admin/rest/user/login", data, function(ret, err) {

            if (err) {
                api.toast({
                    msg: '网络错误',
                    duration: 2000,
                    location: 'bottom'
                });
                return false;
            }
            if (ret.code == 200) {
                var role = null;
                var user = ret.body
                var userType = user.userType;
                // edit start
                // 巡检组长和抢修组长也可以登陆APP 1：运营中心管理员 2：员工 3：客户, 4：兼职, 5:体验账户
                if (userType != 3 && userType != 5 && userType != 2) {
                    $api.text($api.dom("#account-tip"), '账号不存在');
                    return false;
                }

                // 清空 storage
                $api.clearStorage();

                $api.setStorage("ocId", user.ocId);
                $api.setStorage("token", user.token);
                $api.setStorage("username", user.userName);
                $api.setStorage("userType", userType);
                // $api.setStorage("employeeType", employeeType);

                // add start 2019/4/29 kangzhi
                if (ctrl.isRemember) {
                    // 勾选了记住密码，将账号和密码保存
                    $api.setStorage("remember", '1');
                    $api.setStorage("account", data.userName);
                    $api.setStorage("password", data.password);
                }
                // add end 2019/4/29 kangzhi

                // 可以登陆APP角色： 组团长、巡检组长、抢修组长、客户站长、客户巡检组长
                // 组团长、巡检组长  抢修组长登陆
                if (userType == 2) { // 员工(包括自己员工、客户员工)
                    $api.setStorage("realName", user.userName);
                    $api.setStorage("isEmployee", true);

                    // 获取员工角色
                    var args = {
                        token: user.token
                    }
                    $api.get("/ems/rest/employee/role", args, function(ret, err) {

                        if (ret.code == 200) {
                            var roles = ret.body
                            // 保存 employeeId
                            $api.setStorage("employeeId", roles[0]['employeeId'])
                            // var roleList = []
                            var hasSetRoleIdStorage = false
                            
                            roles.forEach(function (element) {
                                // 将组团长、巡检组长、客户站长、客户巡检组长的角色信息存储
                                // 以下为 自己员工==============================================================
                                // 组团长
                                if (element.roleId == 2) {
                                    $api.setStorage("isZTZ", true)
                                    if (!hasSetRoleIdStorage) {
                                        $api.setStorage("roleId", 2)
                                        hasSetRoleIdStorage = true
                                    }
                                }
                                // 巡检组长
                                if (element.roleId == 3) {
                                    $api.setStorage("isXJZZ", true)
                                    if (!hasSetRoleIdStorage) {
                                        $api.setStorage("roleId", 3)
                                        hasSetRoleIdStorage = true
                                    }
                                }
                                // 以下为 客户员工===============================================================
                                // 站长
                                if (element.roleId == 15) {
                                    $api.setStorage("isKHZZ", true)
                                    if (!hasSetRoleIdStorage) {
                                        $api.setStorage("roleId", 15)
                                        hasSetRoleIdStorage = true
                                    }
                                }

                                // 客户值长
                                if (element.roleId == 18) {
                                    $api.setStorage("isKHZBZ", true)
                                    if (!hasSetRoleIdStorage) {
                                        $api.setStorage("roleId", 18)
                                        hasSetRoleIdStorage = true
                                    }
                                }

                                // 客户值班员
                                if (element.roleId == 16) {
                                    $api.setStorage("isKHZBY", true)
                                    if (!hasSetRoleIdStorage) {
                                        $api.setStorage("roleId", 16)
                                        hasSetRoleIdStorage = true
                                    }
                                }
                                
                                // roleList.push(element)
                            });

                            // if (roleList.length) {
                            //     $api.setStorage("roleId", roleList[0]['roleId']) // 登陆成功后默认使用第一个角色
                            // }
                            // $api.setStorage("roleList", roleList)

                            ctrl.jump()
                        } else {
                            api.toast({
                                msg: '获取账号角色信息失败',
                                duration: 2000,
                                location: 'bottom'
                            });
                        }
                    })

                }
                // edit end

                // userType 1：运营中心管理员 2：员工 3：客户, 4：兼职, 5:体验账户
                if (userType == 5) {
                    $api.setStorage('cus', '1');
                    var realName = ret.body.replaceTo;
                    $api.setStorage("realName", realName);
                    $api.setStorage("guestKeys", ret.body.originalStr);
                    var cusExperience = true; // 体验客户的标志
                    ctrl.getCus(cusExperience);
                }
                
                if (userType == 3) { // edit 2023/2/27
                    ctrl.getCus();
                }

            } else {
                $api.text($api.dom("#password-tip"), '密码错误');
            }
        });

    }
    ctrl.jump = function() {
        api.removeEventListener({
            name: 'loginout'
        });
        // console.log(1)
        //发出登录成功的消息
        api.sendEvent({
            name: 'logined'
        });
        // console.log(2)
        var edge = api.winWidth * 0.2;
        (edge < 0) && (edge = 60);
        api.openDrawerLayout({
            name: 'index',
            url: 'widget://html/index/index.html',
            leftPane: {
                edge: edge,
                name: 'index.leftPanel',
                url: 'widget://html/index/leftPanel.html'
            },
            reload: true,
            slidBackEnabled: false
        });
    }

    // add start 2019/4/29 kangzhi
    // 将检测版本功能从index页面移动到login页面中
    //比较版本号

    ctrl.cmpVersion = function(thisVersion, otherVersion) {
        var _this = thisVersion.split('.');
        var _other = otherVersion.split('.');

        for (var i = 0; i < 3; i++) {
            var _t = parseInt(_this[i]);
            var _o = parseInt(_other[i]);

            if (_t > _o) {
                return 1;
            } else if (_t < _o) {
                return -1;
            }
        }
        return 0;
    }

    //版本更新

    ctrl.checkToUpdate = function() {
        var thisVersion = api.readFile({
            sync: true,
            path: 'widget://resource/version.txt'
        });
        $api.getVersion(function(ret) {
            if (ret) {
                //如果当前版本低于服务器的最低版本  强制更新
                if (ctrl.cmpVersion(thisVersion, ret.minSupport) < 0) {
                    api.alert({
                        title: '版本更新',
                        msg: '版本太低，强烈建议更新',
                        buttons: ['确定']
                    }, function(ret, err) {
                        update(function() {
                            //关闭当前页  退出登录 跳转到登录页
                            api.openWin({
                                name: 'login',
                                url: 'widget://html/user/login.html',
                                reload: true,
                                animation: {
                                    type: "fade"
                                }
                            });

                            api.sendEvent({
                                name: 'loginout'
                            });

                            api.closeWin({
                                animation: {
                                    type: "fade"
                                }
                            });
                        });

                    });
                } else if (ctrl.cmpVersion(thisVersion, ret.latestVersion) < 0) {
                    //如果当前版本低于服务器的最新版本 建议更新
                    if (dialogBox) {
                        return;
                    }
                    var dialogBox = api.require('dialogBox');
                    dialogBox.alert({
                        texts: {
                            title: '版本更新',
                            content: '发现新的版本，请更新',
                            leftBtnTitle: '确定',
                            rightBtnTitle: '取消',
                        },
                        styles: {
                            bg: '#fff',
                            w: 300,
                            corner: 6,
                            title: {
                                marginT: 20,
                                titleSize: 18,
                                titleColor: '#000'
                            },
                            content: {
                                marginT: 10,
                                color: '#000',
                                size: 14
                            },
                            left: {
                                marginB: 7,
                                marginL: 20,
                                w: 130,
                                h: 35,
                                corner: 2,
                                bg: '#fff',
                                size: 18
                            },
                            right: {
                                marginB: 7,
                                marginL: 10,
                                w: 130,
                                h: 35,
                                corner: 2,
                                bg: 'white',
                                size: 18
                            }

                        }
                    }, function(ret) {
                        if (ret.eventType == 'right') {
                            var dialogBox = api.require('dialogBox');
                            dialogBox.close({
                                dialogName: 'alert'
                            });
                        } else if (ret.eventType == 'left') {
                            update();
                            var dialogBox = api.require('dialogBox');
                            dialogBox.close({
                                dialogName: 'alert'
                            });
                        }
                    });
                }

                //如果版本号不一样 标记已经提示过
                //一天之内不在提示
                if (ctrl.cmpVersion(thisVersion, ret.latestVersion) != 0) {

                    var exdate = new Date()
                    exdate.setHours(exdate.getHours() + 24)
                    document.cookie = "has_remind_update=1;expires=" + exdate.toGMTString();

                }


            }
        }, 'json');

        function update(callback) {

            var platform = api.systemType;
            if (platform == "ios") {
                api.openApp({
                    iosUrl: 'https://itunes.apple.com/us/app/%E7%94%B5%E5%8A%A1%E9%80%9Asaas/id1398709195?l=zh&ls=1&mt=8'
                }, function(ret, err) {
                    //coding...
                });
                callback && callback();
            } else if (platform == "android") {
                api.showProgress({
                    title: '下载中',
                    text: '请稍等...',
                    modal: false
                });

                api.download({
                    url: "https://cdn.dianwutong.com/app/dianwutong_saas/app.apk",
                    cache: false,
                    allowResume: true
                }, function(ret, err) {
                    api.hideProgress();
                    if (ret.state == 1) {
                        //下载成功
                        api.installApp({
                            appUri: ret.savePath
                        });
                        callback && callback();
                    } else {
                        api.alert({
                            title: '版本更新',
                            msg: '下载失败，请到电务通官网扫码下载最新app',
                            buttons: ['确定']
                        }, function(ret, err) {
                            //coding...
                            callback && callback();
                        });

                    }
                });

            }

        }
    }

    //检查是否更新

    ctrl.checkHasUpdated = function() {

        var lastVersion = $api.getStorage('lastVersion');

        var currentVersion = api.readFile({
            sync: true,
            path: 'widget://resource/version.txt'
        });

        if (lastVersion && ctrl.cmpVersion(lastVersion, currentVersion) < 0) {

            api.alert({
                title: '提示',
                msg: '版本更新成功，请重新登陆',
                buttons: ['确定']
            }, function(ret, err) {

                api.sendEvent({
                    name: 'loginout'
                });

                setTimeout(function() {
                    api.closeWin({
                        animation: {
                            type: 'fade'
                        }
                    });
                }, 500)

                api.openWin({
                    name: 'login',
                    url: 'widget://html/user/login.html',
                    animation: {
                        type: 'fade'
                    }
                });

            })

        } else {

            $api.setStorage('lastVersion', currentVersion);

        }


    }

    // 检测上次登录是否记住了账号密码
    ctrl.checkIsRemember = function() {

            var remember = $api.getStorage('remember');
            var account = $api.getStorage('account');
            var password = $api.getStorage('password');

            if (remember) {

                $api.val($api.dom("#account"), account);
                $api.val($api.dom("#password"), password);
                ctrl.isRemember = true;
                $api.addCls($api.dom("#remember-password"), 'is-remember');

            }

        }
        // add end 2019/4/29 kangzhi

    ctrl.init();
};
