import {
    getMyInfo,
    androidbuyVip,
    getVipInfo,
    getWxQrcode,
    getLearnCard
} from '~/api/user'
import event from '~/mixins/event'
import {
    getProducts,
    userEvent
} from '~/api/global'
import {
    createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
    store
} from '~/store/index'
const app = getApp()
Page({
    behaviors: [event],
    data: {
        userInfo: {},
        vipTime: '',
        tasks: [],
        isIos: app.globalData.isIOS,
        qrCode: '',
        activationModal: false,
        activationRes: {},
        products: [],
        isPreferential: false
    },
    async onLoad() {
        // 手工绑定 
        this.storeBindings = createStoreBindings(this, {
            store,
            actions: {
                setUser: 'setUser'
            }
        })
        if (this.data.isIos) {
            let qrCode = await getWxQrcode()
            this.setData({
                qrCode: qrCode.ticketUrl
            })
        }
    },
    async onShow() {
        if (typeof this.getTabBar === 'function') {
            this.getTabBar().setData({
                selected: 4
            })
        }
        let uid = wx.getStorageSync('uid') || ''
        if (!uid) {
            getApp().callBack = (res) => {
                this.setUserInfo()
            }
        } else {
            this.setUserInfo()
        }
    },
    // 设置用户信息及vip状态
    async setUserInfo() {
        let userInfo = await getMyInfo()
        let vipTime = await getVipInfo()
        this.setUser(userInfo.user)
        this.getProducts()
        this.setData({
            userInfo,
            vipTime,
        })
    },
    async getProducts() {
        let {
            productList: products,
            isPreferential
        } = await getProducts()
        console.log(products);
        this.setData({
            products,
            isPreferential
        })
    },
    activationCode() {
        wx.showModal({
            title: '请输入激活码',
            editable: true,
            success: async ({
                confirm,
                content
            }) => {
                if (confirm) {
                    let regexp = /^[a-zA-Z0-9]{4}$/
                    if (regexp.test(content)) {
                        let activationRes = await getLearnCard({
                            cardNo: content
                        })
                        if (activationRes.code == 200) {
                            activationRes = {
                                code: 200,
                                message: '快去朗读挑战吧!'
                            }
                        }
                        this.setUserInfo()
                        if (typeof this.getTabBar === 'function') {
                            this.getTabBar().setData({
                                mask: true
                            })
                        }
                        this.setData({
                            activationModal: true,
                            activationRes
                        })
                    } else {
                        if (typeof this.getTabBar === 'function') {
                            this.getTabBar().setData({
                                mask: true
                            })
                        }
                        this.setData({
                            activationModal: true,
                            activationRes: {
                                code: 581,
                                message: '请检查激活码输入是否正确'
                            }
                        })
                    }
                }
            }
        })
    },
    toGzh() {
        this.selectComponent('#gzh').open()
    },
    async toBuy({
        currentTarget
    }) {
        if (currentTarget.dataset.isclick) {
            return
        }
        wx.showLoading({
            title: '提交中',
            mask: true
        })
        let res = await androidbuyVip({
            productId: currentTarget.dataset.id
        }).finally(() => {
            wx.hideLoading()
        })
        wx.miniapp.requestPayment({
            timeStamp: res.timestamp,
            mchId: res.partnerid,
            prepayId: res.prepayid,
            package: res.package,
            nonceStr: res.noncestr,
            sign: res.sign,
            success: async (res) => {
                setTimeout(() => {
                    this.setUserInfo()
                    this.selectComponent('#vipModal').open()
                }, 1500)
                userEvent({
                    action: 'ANDROID_PAY_SUCCESS',
                })
            },
            fail(res) {
                wx.showToast({
                    title: "支付失败",
                    icon: "none",
                    duration: 3000
                })
            },
            complete: (res) => {
                console.error('wx.miniapp.requestPayment complete:', res)
            }
        })
        return
        userEvent({
            action: 'ANDROID_PAY_ACTIVITY',
        })
        let {
            timeStamp,
            nonceStr,
            signType,
            paySign
        } = res
        // package保留字
        wx.requestPayment({
            timeStamp,
            nonceStr,
            package: res.package,
            signType,
            paySign,
            success: async (res) => {
                setTimeout(() => {
                    this.setUserInfo()
                    this.selectComponent('#vipModal').open()
                }, 1500)
                userEvent({
                    action: 'ANDROID_PAY_SUCCESS',
                })
            },
            fail(res) {
                wx.showToast({
                    title: "支付失败",
                    icon: "none",
                    duration: 3000
                })
            }
        })
    },
    jump({
        currentTarget
    }) {
        let url = currentTarget.dataset.url
        console.log(url);
        wx.navigateTo({
            url: url
        });
    },
    clipboar() {
        wx.setClipboardData({
            data: this.data.userInfo.user.eid,
            success: function (res) { //成功回调函数
                wx.showToast({
                    title: '已复制',
                    icon: "none"
                })
            }
        })
    },
    closeModal() {
        this.setData({
            activationModal: false
        })
        if (typeof this.getTabBar === 'function') {
            this.getTabBar().setData({
                mask: false
            })
        }
    },
    // 分享配置
    onShareAppMessage: function (res) {
        return {
            title: '自从用了它,家里朗朗书声,美妙极了!你家孩子也快来试试!',
            path: `/pages/index/index?uid=${wx.getStorageSync('uid')}`,
            imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/375-300-1.jpg'
        }
    },
    onShareTimeline: function () {
        return {
            title: '终于找到适合孩子的朗读神器了!动画配音,边玩边学!',
            query: `uid=${wx.getStorageSync('uid')}`,
            imageUrl: 'http://reader-wx.ai160.com/images/reader/v3/yuwen.jpg'
        }
    },
})