import { postUrl, postUrl3, postUrl4 } from '../../utils/util';
import apiArr from '../../api/water_filter';
import * as partnerApi from '../../api/partner';
const env = require('../../config/env.js')

// pages/newLogin/newLogin.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isLogin: false,
        loginType: 'account', // 默认手机登录
        password: "",
        account: "",
        type: "",
        checked: false,
        types: "1", //1用户 2师傅 3管理

        userLogin: false, //用户是否登录过
        masterLogin: false, //师傅是否登录过
        staticUrl: env.static_url,
    },
    //用户登录过 登录
    userLogin() {
        let that = this
        wx.redirectTo({
            url: '/pages/water_filter/water_filter'
        });
    },
    //用户登录
    onChange(e) {
        let that = this
        that.setData({
            checked: e.detail
        })
    },
    showTo() {
        wx.showModal({
            title: '提示',
            content: '请阅读并同意《用户服务协议和隐私政策》',
            complete: (res) => {
                if (res.cancel) {

                }

                if (res.confirm) {

                }
            }
        })
    },
    getPhoneNumber(event) {
        let that = this
        const { isLogin } = this.data;
        console.log('获取信息', event);
        if (event.detail.errMsg === "getPhoneNumber:ok") {
            wx.showLoading({
                title: '加载中',
                mask: true
            });

            postUrl(apiArr.loginGetPhone, {
                code: event.detail.code
            }, res => {
                if (isLogin) {
                    wx.setStorageSync('phone', res.phone);
                    wx.hideLoading();
                    wx.showToast({
                        title: '登录成功',
                        icon: 'success',
                        mask: true,
                        duration: 2000,
                        success: () => {
                            that.tohome();
                        }
                    });

                } else {
                    wx.hideLoading();
                    wx.showToast({
                        title: '登录失败',
                        icon: 'error',
                        mask: true,
                        duration: 2000,
                    })
                }
            })
        } else {
            wx.removeStorageSync('ctoken');
            wx.setStorageSync('loginMaster');
            wx.removeStorageSync('userId');
            wx.removeStorageSync('openId');
            wx.removeStorageSync('phone');
            wx.removeStorageSync('is_deal');
            wx.removeStorageSync('is_dev');
            wx.removeStorageSync('is_shop');
            wx.removeStorageSync('shopId');
            wx.removeStorageSync('mshopId');
            wx.removeStorageSync('dealer_id');
            console.error('用户拒绝授权:', event.detail.errMsg);
        }
    },
    headerLoginClick() {
        let that = this
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        wx.login({
            success: (res) => {
                postUrl(apiArr.login, {
                    code: res.code
                }, res => {
                    console.log('eaasdaadd', res)
                    wx.setStorageSync('is_deal', res.is_deal);
                    if (res.error) return;
                    postUrl(apiArr.loginInfo, {}, ress => {
                        if (ress.error) return;
                        // 保存userId 后续接口使用
                        wx.setStorageSync('userId', ress.user_id);
                        wx.setStorageSync('openId', ress.open_id);
                        wx.setStorageSync('shopId', ress.wshop_id);
                        wx.setStorageSync('mshopId', ress.mshop_id);
                        wx.setStorageSync('dealer_id', ress.dealer_id);
                        wx.setStorageSync('is_dev', ress.is_dev);
                        wx.setStorageSync('userInfo', ress)
                        this.setData({
                            isLogin: true,
                        })
                    }, res.token)
                    wx.setStorageSync('ctoken', res.token);
                    wx.setStorageSync('loginMaster', 1);
                    wx.setStorageSync('is_deal', res.is_deal);
                    wx.setStorageSync('is_shop', res.is_shop);
                    wx.hideLoading();
                })
            },
        })
    },
    tohome: function () {
        let that = this
        wx.redirectTo({
            url: '/pages/water_filter/water_filter'
        });
    },
    changeTypes(e) {
        let that = this
        that.setData({
            types: e.currentTarget.dataset.types
        })
    },

    onChangeLoginType(e) {
        let that = this
        that.setData({
            types: e.detail
        })
    },
    //师傅登录
    headerLoginClick2() {
        wx.showLoading({
            title: '加载中',
        });
        wx.login({
            success: (res) => {

                postUrl(apiArr.login, {
                    code: res.code
                }, res => {
                    console.log('eaasdaadd', res)
                    wx.setStorageSync('is_master', res.is_master);

                    if (res.error) return;
                    postUrl(apiArr.loginInfo, {}, ress => {
                        if (ress.error) return;
                        // 保存userId 后续接口使用
                        wx.setStorageSync('userId', ress.user_id);
                        wx.setStorageSync('userInfo', ress)
                        if (wx.getStorageSync('openId')) {
                            wx.setStorageSync('loginMaster', 1) //是否登录过师傅  2登录师傅
                        } else {
                            wx.setStorageSync('loginMaster', 2) //是否登录过师傅  2登录师傅
                        }
                        this.setData({
                            isLogin: true,
                        })
                    }, res.token)
                    wx.setStorageSync('ctoken', res.token);
                    wx.hideLoading();
                })
            },
        })
    },
    masterLogin() {
        let that = this
        if (wx.getStorageSync('is_master')) {
            wx.navigateTo({
                url: '/packages/master/masterIndex/index'
            });
        } else {
            wx.showToast({
                title: '您还不是师傅',
                icon: "none"
            })
        }
    },
    getPhoneNumber2(event) {
        let that = this
        const { isLogin } = this.data;
        console.log('获取信息', event);
        if (event.detail.errMsg === "getPhoneNumber:ok") {
            wx.showLoading({
                title: '加载中',
            });
            postUrl(apiArr.loginGetPhone, {
                code: event.detail.code
            }, res => {
                if (isLogin) {
                    console.log(res);
                    wx.setStorageSync('phone', res.phone);
                    wx.hideLoading();
                    wx.showToast({
                        title: '登录成功',
                        icon: 'success',
                        mask: true,
                        duration: 2000,
                        success: () => {
                            this.tohome2();
                        }
                    });
                } else {
                    wx.hideLoading();
                    wx.showToast({
                        title: '登录失败',
                        icon: 'error',
                        mask: true,
                        duration: 2000,
                    })
                }
            })
        } else {
            wx.removeStorageSync('ctoken');
            wx.removeStorageSync('userId');
            wx.removeStorageSync('openId');
            wx.removeStorageSync('phone');
            wx.removeStorageSync('is_deal');
            wx.removeStorageSync('is_dev');
            wx.removeStorageSync('is_shop');
            wx.removeStorageSync('shopId');
            wx.removeStorageSync('mshopId');
            wx.removeStorageSync('dealer_id');
            console.error('用户拒绝授权:', event.detail.errMsg);
        }
    },
    tohome2: function () {
        let that = this
        if (that.data.type == 'client') {
            wx.navigateTo({
                url: '/pages/water_filter/water_filter'
            });
        } else {
            if (wx.getStorageSync('is_master')) {
                wx.navigateTo({
                    // url: '/packages/master/order/index'
                    url: '/packages/master/masterIndex/index'
                });
            } else {
                wx.showToast({
                    title: '您还不是师傅',
                    icon: "none"
                })
            }
        }
    },

    //经销商登录
    accountIpt(e) {
        console.log(e);
        let that = this
        that.setData({
            account: e.detail.value
        })
    },
    accountIpt1(e) {
        console.log(e);
        let that = this
        that.setData({
            account: e.detail
        })
    },
    passwordIpt(e) {
        let that = this
        that.setData({
            password: e.detail.value
        })
    },
    passwordIpt1(e) {
        let that = this
        that.setData({
            password: e.detail
        })
    },
    accountLogin() {
        let that = this
        wx.showLoading({
            title: '登录中...',
            mask: true
        })
        console.log(partnerApi);
        wx.getSetting({
            withSubscriptions: true,
            success: (res) => {
                if (res.subscriptionsSetting && res.subscriptionsSetting.mainSwitch) {
                    const itemSettings = res.subscriptionsSetting.itemSettings || {};
                    const tmplMap = {
                        're34uubgvrwJLaiM3LhQEmvxrRxoNcJbo7b8gcbxx44': '新注册用户提醒',
                        '2BX7Zh5ccLzmHvvbCHuPWiaoZQyDCGfziCruxUct_EU': '订单续费通知',
                    };

                    // 收集未订阅的模板ID
                    const unsubscribedTmplIds = [];
                    Object.keys(tmplMap).forEach(tmplId => {
                        if (itemSettings[tmplId] !== 'accept') {
                            unsubscribedTmplIds.push(tmplId);
                        }
                    });

                    if (unsubscribedTmplIds.length > 0) {
                        // 逐个订阅未订阅的消息
                        wx.requestSubscribeMessage({
                            tmplIds: unsubscribedTmplIds,
                            success: (res) => {
                                postUrl(partnerApi.login, {
                                    account: that.data.account,
                                    password: that.data.password
                                }, res => {
                                    wx.hideLoading()
                                    if (res.msg == '操作成功') {
                                        wx.setStorageSync('atoken', res.token)
                                        that.getInfo()
                                    }
                                })
                            },
                            fail: (err) => {
                                postUrl(partnerApi.login, {
                                    account: that.data.account,
                                    password: that.data.password
                                }, res => {
                                    wx.hideLoading()
                                    if (res.msg == '操作成功') {
                                        wx.setStorageSync('atoken', res.token)
                                        that.getInfo()
                                    }
                                })
                            }
                        });
                    } else {
                        postUrl(partnerApi.login, {
                            account: that.data.account,
                            password: that.data.password
                        }, res => {
                            wx.hideLoading()
                            if (res.msg == '操作成功') {
                                wx.setStorageSync('atoken', res.token)
                                that.getInfo()
                            }
                        })
                    }
                }
            },
        });
    },
    getInfo() {
        let that = this
        postUrl4(partnerApi.loginInfo, {}, res => {
            console.log(res);
            wx.showToast({
                title: '登录成功！',
            })
            wx.setStorageSync('admin', res.data)
            setTimeout(() => {
                console.log(123);
                wx.navigateTo({
                    url: '/packages/partner/pages/partner',
                })
            }, 1500)

        })
    },

    navigateToAgreement() {
        wx.navigateTo({
            url: '../Agreement/Agreement',
        })
    },
    // 审核登录
    accountLogin2() {
        let that = this
        wx.showLoading({
            title: '登录中...',
            mask: true
        })
        let version = wx.getStorageSync('version')
        if (version) {
            wx.login({
                success: (res) => {
                    postUrl3(apiArr.accountLogin, {
                        phone: that.data.account,
                        code: res.code,
                        pass: that.data.password,
                        version,
                    }, version, res2 => {
                        wx.hideLoading()
                        wx.hideLoading()
                        if (res2.token) {
                            wx.setStorageSync('ctoken', res2.token);
                            wx.setStorageSync('loginMaster', 1);
                            wx.setStorageSync('is_deal', res2.is_deal);
                            wx.setStorageSync('is_dev', res2.is_dev);
                            wx.setStorageSync('is_shop', res2.is_shop);
                            postUrl(apiArr.loginInfo, {}, ress => {
                                if (ress.error) return;
                                // 保存userId 后续接口使用
                                wx.setStorageSync('userId', ress.user_id);
                                wx.setStorageSync('openId', ress.open_id);
                                wx.setStorageSync('shopId', ress.wshop_id);
                                wx.setStorageSync('mshopId', ress.mshop_id);
                                wx.setStorageSync('dealer_id', ress.dealer_id);
                                this.setData({
                                    isLogin: true,
                                })
                            }, res2.token)

                            wx.showToast({
                                title: '登录成功',
                                icon: 'success',
                                mask: true,
                                duration: 2000,
                                success: () => {
                                    console.log(wx.getStorageSync('is_dev'), 'isdev');
                                    if (wx.getStorageSync('is_dev') == '0' || wx.getStorageSync('is_dev') == '1') {
                                        wx.navigateTo({
                                            url: '/pages/water_filter/water_filter',
                                        })
                                    } else {
                                        setTimeout(() => {
                                            this.tohome();
                                        }, 2000)
                                    }
                                }

                            });

                        } else {

                        }
                    })
                },
            })
        }
    },

    getVersion() {
        wx.showLoading({
            title: '加载中...',
        })
        let that = this
        let version = ''
        const accountInfo = wx.getAccountInfoSync();
        if (accountInfo.miniProgram.version) {
            version = accountInfo.miniProgram.version
        } else {
            version = '1.0.28'
        }

        wx.setStorageSync('version', version)
        postUrl3(apiArr.getVersion, {}, version, res => {
            wx.hideLoading()
            if (res.versions) {
                let LoginType = res.versions.includes(version)
                wx.setStorageSync('LoginType', LoginType)
                that.setData({
                    LoginType
                })
            } else {
                wx.setStorageSync('LoginType', false)
                that.setData({
                    LoginType: false
                })
            }
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getVersion()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let that = this
        let userLogin = false
        let masterLogin = false
        if (wx.getStorageSync('ctoken')) {
            userLogin = true
        } else {
            userLogin = false
        }
        if (wx.getStorageSync('is_master')) {
            masterLogin = true
        } else {
            masterLogin = false
        }

        that.setData({
            userLogin,
            masterLogin,
        })
    },

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

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

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

    },

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

    },

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

    }
})