import {
    ApiModel
} from "../../utils/api";
const _Http = new ApiModel();
import {
    TestVerify
} from "../../utils/verify"
const _Verify = new TestVerify();
const utilMd5 = require('../../utils/md5');
let countDownTime1 = null;
Page({
    /**
     * 页面的初始数据
     */
    data: {
        rulesChecked: true,
        popups: false, //弹出层控制
        pageType: "login", //页面类型 login 手机登录页面 signin 注册页面 firm 商户认证 changeUser 切换用户
        butText: "", //按钮文本
        attinfos: [], //logo
        /* 登录 */
        fphonenumber: null, //手机号码
        password: null, //验证码
        /* 个人注册 */
        fname: "", //用户名
        frole: "", //用户身份
        /* 商户注册 */
        fbrand: "", //品牌名
        saleprodclass: [], //经营类目
        showSaleprodclass: "", //表单显示经营类目
        fagentname: "", //公司名称
        fcontact: "", //联系人
        fintroduction: "", //公司介绍
        faddress: "", //公司地址
        fdutyparagraph: "", //统一社会代码
        /* 用户选择 */
        userIndex: 0, //多用户选择下标
        throttle: true, //商户认证截流
        /* 错误提示 */
        errTips: {
            fphonenumber: false, //手机号码
            password: false, //验证码
        },
        countDownTime: 60, //倒计时
        dataList: ["暂无分类"], //分类列表
    },
    /* input事件剔除特殊字符 */
    eliminate(value) {
        const {
            name
        } = value.target.dataset;
        this.setData({
            [name]: _Verify.Eliminate(value.detail)
        })
    },
    /* 用户守则 */
    rulesOnChange() {
        this.setData({
            rulesChecked: !this.data.rulesChecked
        })
    },
    viewRules() {
        wx.downloadFile({
          url: 'https://bwj.obs.cn-east-2.myhuaweicloud.com/resources/PrivacyPolicy.docx',
          success:(res)=>{
              console.log(res)
              wx.openDocument({
                filePath: res.tempFilePath,
                fail: (err) => {
                    console.log(err)
                    wx.showToast({
                        title: '读取失败,请稍后再试',
                        icon: "none"
                    })
                }
            })
          },
          fail:(err)=>{
              console.log(err)
              wx.showToast({
                title: '读取失败,请稍后再试',
                icon: "none"
            })
          }
        })
        return
        
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.type) {
            this.setData({
                pageType: "changeUser"
            })
        };
        if (wx.getStorageSync('userData').fphonenumber != null) this.setData({
            fphonenumber: wx.getStorageSync('userData').fphonenumber
        })
        /* 设置按钮文本 */
        this.changeButText()
    },

    /* 选择类目回调 */
    saleprodChange(arr) {
        let {
            detail
        } = arr, showSaleprodclass = "";
        console.log(arr)
        for (let i = 0; i < detail.length; i++) {
            showSaleprodclass += (detail[i] + '，');
        };
        this.setData({
            popups: false,
            saleprodclass: detail,
            showSaleprodclass: showSaleprodclass.slice(0, showSaleprodclass.length - 1),
            "errTips.showSaleprod": false
        })
    },
    /* 缓存登录用户关键数据 */
    retentionOfCriticalData(index) {
        //获取用户选择的信息列表
        const user = wx.getStorageSync('account_list')[index];
        let data = {
            token: user.token,
            fisadministrator: user.fisadministrator,
            tagentsid: user.tagentsid,
            tenterpriseid: user.tenterpriseid,
            userid: user.userid,
            index: index,
            fphonenumber: this.data.fphonenumber
        };
        /* 储存 */
        wx.setStorageSync('userData', data);
        if (getApp().globalData.socketEstablish) getApp().globalData.SocketTask.close(function (res) {
            console.log('WebSocket连接已关闭！readyState=' + that.globalData.SocketTask.readyState)
            that.globalData.socketEstablish = false;
        });
    },
    /* 登录页面提交数据 */
    loginSubmit() {
        //验证手机号码
        if (!_Verify.phoneNumber(this.data.fphonenumber, 1)) return this.setData({
            "errTips.fphonenumber": true
        })
        /* 验证验证码 */
        if (this.data.password == null) {
            this.setData({
                "errTips.password": true
            })
            wx.showToast({
                title: '无效验证码',
                icon: "none"
            })
            return;
        };
        /* 发送请求 */
        _Http.login({
            "phonenumber": this.data.fphonenumber,
            "password": utilMd5.hexMD5(this.data.password),
            "client": "wechat_customer"
        }).then(res => {
            /* 结果验证 */
            if (res.msg != '成功') {
                this.setData({
                    "errTips.password": true
                })
                wx.showToast({
                    title: '无效验证码',
                    icon: "none"
                })
                return;
            };
            //账号列表保存到全局变量中
            wx.setStorageSync('account_list', res.account_list);
            wx.setStorageSync('servicehotline', res.servicehotline);
            /* 判断账号 新 单 多  isnewregister*/
            if (res.account_list.length == 1 && res.account_list[0].isnewregister == 1) {
                //新账号
                this.retentionOfCriticalData(0)
                //跳转到个人注册
                this.setData({
                    pageType: 'signin'
                })
                //更改按钮内容
                this.changeButText()
            } else if (res.account_list.length == 1 && res.account_list[0].isnewregister == 0) {
                //单账号
                this.retentionOfCriticalData(0)
                //跳转到首页
                this.jumpOverToIndex()
            } else if (res.account_list.length > 1) {
                //多账号
                //跳转到账号选择
                this.setData({
                    pageType: 'changeUser'
                })
                //更改按钮内容
                this.changeButText()
            }

        })
    },
    /* 提交数据 */
    submitData(e) {
        const {
            name
        } = e.currentTarget.dataset;
        if (name == "login") {
            if(!this.data.rulesChecked) return wx.showToast({
              title: '请勾选同意协议后登录',
              icon:"none"
            })
            //登录页面提交信息
            this.loginSubmit()
            //getApp().getUserProfile();
        } else if (name == "changeUser") {
            //多账号选择
            this.retentionOfCriticalData(this.data.userIndex)
            //跳转到首页
            this.jumpOverToIndex()
        } else if (name == "signin") {
            //个人注册提交数据后跳转商户认证页面
            this.savePersonalInformation()
            //查询类目列表
            _Http.basic({
                "accesstoken": wx.getStorageSync('userData').token,
                "classname": "enterprise.system.prodclass",
                "method": "query_typeselectList",
                "content": {}
            }).then(res => {
                if (res.msg != '成功') return;
                let dataList = [];
                for (let i = 0; i < res.data.length; i++) {
                    dataList.push({
                        value: res.data[i],
                        index: i,
                        checked: false
                    })
                }
                this.setData({
                    dataList
                })
            })
            //getApp().getUserProfile();
            //更改按钮内容
            this.changeButText()
        } else if (name == "firm") {
            //商户认证提交
            this.merchantsToSubmit();
        }
    },
    /* 商户提交前验证表单 */
    merchantsToSubmitVerify() {
        let errTips = this.data.errTips,
            verify = true;
        //验证联系方式
        if (!_Verify.phoneNumber(this.data.fphonenumber)) {
            errTips.fphonenumber = true;
            verify = false;
        }
        this.setData({
            errTips
        })
        return verify;
    },
    /* 添加图片 */
    imageChange(data) {
        this.setData({
            attinfos: data.detail.fileList
        })
    },
    coverImageChange(data) {
        this.setData({
            coverAttinfos: data.detail.fileList
        })
    },
    /* 商户认证提交表单 */
    merchantsToSubmit() {
        // 验证
        if (!this.merchantsToSubmitVerify()) return wx.showToast({
            title: '请检查表单内容',
            icon: "none"
        });
        //截流
        if (!this.data.throttle) return;
        //发送请求
        _Http.basic({
            "accesstoken": wx.getStorageSync('userData').token,
            "classname": "customer.tagents.tagents",
            "method": "modify_enterpriseAgent",
            "content": {
                "ftype": "商户认证",
                "data": [{
                    "fbrand": this.data.fbrand,
                    "fagentname": this.data.fagentname,
                    "fcontact": this.data.fcontact,
                    "fphonenumber": this.data.fphonenumber,
                    "faddress": this.data.faddress,
                    "fdutyparagraph": this.data.fdutyparagraph,
                    "fintroduction": this.data.fintroduction,
                    "saleprodclass": this.data.saleprodclass
                }]
            }
        }).then(res => {
            if (res.msg != "成功") return wx.showToast({
                title: res.data,
                icon: "none"
            });
            this.setData({
                throttle: false
            })
            wx.showToast({
                title: "提交成功",
                icon: "none"
            });
            setTimeout(() => {
                wx.switchTab({
                    url: '/pages/tabbar-pages/home/index',
                })
            }, 500);
        })
    },
    /* 获取焦点 */
    inputFocus(e) {
        const {
            name
        } = e.currentTarget.dataset;
        let errTips = this.data.errTips;
        errTips[name] = false;
        this.setData({
            errTips
        })
    },
    /* 失去焦点 */
    inputBlur(e) {
        const {
            name
        } = e.currentTarget.dataset;
        const {
            value
        } = e.detail;
        if (name == 'fphonenumber') {
            if (!_Verify.phoneNumber(this.data.fphonenumber, 1)) return this.setData({
                "errTips.fphonenumber": true
            })
        };
        if (value.trim() == "") {
            let errTips = this.data.errTips;
            errTips[name] = true;
            this.setData({
                errTips
            })
        }
    },
    /* 个人注册页面保存个人信息 */
    savePersonalInformation(is) {
        const {
            fphonenumber
        } = this.data
        let tail = fphonenumber.toString().substring(fphonenumber.toString().length - 4);
        let data = {
            fname: tail + "用户",
            frole: "管理员"
        }
        if (this.data.fname != '') {
            data.fname = this.data.fname
        };
        if (this.data.frole != '') {
            data.frole = this.data.frole
        }
        _Http.basic({
            "accesstoken": wx.getStorageSync('userData').token,
            "classname": "customer.usercenter.usermsg.usermsg",
            "method": "update_usermsg",
            "content": data
        }).then(res => {
            if (res.msg != '成功') return wx.showToast({
                title: res.data,
                icon: 'none'
            })
            let obj1 = wx.getStorageSync('userData');
            const data = [Object.assign(res.data[0], obj1)]
            wx.setStorageSync('account_list', data);
            if (is) {
                wx.reLaunch({
                    url: '/pages/tabbar-pages/home/index'
                })
            } else {
                this.setData({
                    pageType: "firm"
                })
            }
        })
    },
    /* 多用户选择下标传递 */
    userChange(index) {
        this.setData({
            userIndex: index.detail.userIndex
        })
    },
    /* 获取验证码 */
    getVerifyCode() {
        //验证手机号码
        if (!_Verify.phoneNumber(this.data.fphonenumber, 1)) return this.setData({
            "errTips.fphonenumber": true
        });
        /* 倒计时中阻止 */
        if (this.data.countDownTime != 60) return wx.showToast({
            title: '请勿重复获取验证码',
            icon: "none"
        });
        this.setData({
            countDownTime: this.data.countDownTime - 1
        })
        _Http.getPassword({
            "phonenumber": this.data.fphonenumber,
            "client": "wechat_customer"
        }).then(res => {
            console.log("验证码", res)
            countDownTime1 = setInterval(() => {
                if (this.data.countDownTime != 0) {
                    this.setData({
                        countDownTime: this.data.countDownTime - 1
                    })
                } else {
                    clearInterval(countDownTime1);
                    this.setData({
                        countDownTime: 60
                    })
                }
            }, 1000);
            wx.showToast({
                title: res.msg,
                icon: "none",
                duration: 5000
            })
        })
    },
    /* 跳转首页 */
    jumpOverToIndex() {
        //如果是个人注册页面，保存数据后进入首页
        if (this.data.pageType == 'signin') {
            const that = this;
            if (this.data.fname != '' || this.data.frole != '') {
                wx.showModal({
                    title: '提示',
                    content: '是否保存已输入的信息',
                    success: (res) => {
                        console.log(res)
                        if (res.confirm) {
                            that.savePersonalInformation(true)
                        } else {
                            wx.reLaunch({
                                url: '/pages/tabbar-pages/home/index'
                            })
                        }
                    }
                })
            } else {
                that.savePersonalInformation(true)
                wx.reLaunch({
                    url: '/pages/tabbar-pages/home/index'
                })
            }
        } else {
            /* 跳转到首页 */
            wx.reLaunch({
                url: '/pages/tabbar-pages/home/index'
            })
        }
    },
    /* 修改按钮内容 */
    changeButText() {
        const {
            pageType
        } = this.data
        if (pageType == 'login') {
            this.setData({
                butText: "登 录"
            })
        } else if (pageType == 'signin') {
            this.setData({
                butText: "下一步"
            })
        } else if (pageType == 'firm') {
            this.setData({
                butText: "立即创建"
            })
        } else if (pageType == 'changeUser') {
            this.setData({
                butText: "选择进入"
            })
        }
    },
    /* 弹出层控制 */
    showPop() {
        this.setData({
            popups: !this.data.popups
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        clearInterval(countDownTime1);
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})