import {
    userLogin,
} from '~/api/user'
import {
    createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
    store
} from '~/store/index'
let storeBindings
Page({
    data: {
        checkedAgree: false,
    },
    onLoad() {
        if (!this.storeBindings) {
            this.storeBindings = createStoreBindings(this, {
                store,
                actions: ['setUser']
            })
        }
    },
    /**
     * 退出页面时触发基础库回调，由基础库内部处理系统登录态。
     */
    onUnload() {
        this.storeBindings.destroyStoreBindings()
    },

    /**
     * 触发小程序登录，登录成功后自动退出页面
     */
    onTapWeixinMiniProgramLogin() {
        wx.weixinMiniProgramLogin({
            success: () => {
                wx.getMiniProgramCode({
                    success: async (res) => {
                        let data = {
                            code: res.code,
                            userChannelCode: 3001
                        }
                        let userRes = await userLogin(data)
                        this.setUser(userRes.data)
                        wx.setStorageSync('uid', userRes.data.uid)
                        wx.setStorageSync('user', userRes.data)
                        wx.showToast({
                            icon: 'loading',
                            title: '登录成功！',
                        })
                        wx.switchTab({
                            url: '/pages/index/index',
                        })
                    }
                })
            },
            fail: () => {
                wx.showToast({
                    title: '小程序登录失败',
                    icon: 'none'
                });
            }
        })
    },

    onCheckboxChange() {
        this.setData({
            checkedAgree: !this.data.checkedAgree
        });
    },

    /**
     * 
     * 使用单独的 webview 页面展示用户协议
     */
    onShowAgreement(e) {
        const urls = [
            'link1',
            'link2'
        ];
        const url = urls[e.target.dataset.idx];
        // wx.navigateTo({
        //   url: `/pages/webview/index?url=${url}`,
        // });
    },
})