const config = require('../config/config')
const util = require('../utils/util')
const user = require('../utils/user')
const download = require('../utils/download')

Page({
	data: {
		open: false,

		signInClass: "",
		doorLeftClass: "",
		doorRightClass: "",
		doorInviteClass: ""
	},

	prevent() {
    return false
	},

	toggleDoor() {
		let { open, signInClass, doorLeftClass, doorRightClass, doorInviteClass } = this.data
		signInClass = open && 'signIn-btn-show' || 'signIn-btn-hide'
		if (open) setTimeout(() => this.setData({ signInClass: "" }), 1000);
		doorLeftClass = !open && 'door-left-open' || 'door-left-close'
		doorRightClass = !open && 'door-right-open' || 'door-right-close'
		doorInviteClass = !open && 'door-invite-show' || 'door-invite-hide'
		this.setData({ open: !open, signInClass, doorLeftClass, doorRightClass, doorInviteClass })
	},

	showAgreement({ currentTarget }) {
		const { type } =	currentTarget.dataset
		const url = type == 'user' ? config.userAgreement : config.privacyPolicy
		util.showLoad('加载中')
		download.openAgreement(url).then(() => util.hideLoad()).catch(() => util.hideLoad())
	},

	login() {
		if (wx.getStorageSync('token')) return wx.reLaunch({ url: '/pages/index/index' })

		util.showLoad('登录中')
		user.getSessionKey().then(res => {
			if (res.errcode) throw res.errmsg
			else {
				const data = { openId: res.openid }
				user.loginByPhone(data).then(() => {
					util.hideLoad()
					wx.reLaunch({ url: '/pages/index/index' })
				}).catch(err => {
					util.hideLoad()
					wx.removeStorageSync('token')
					wx.removeStorageSync('userInfo')
					util.showErrorToast(err)
				})
			}
		}).catch(() => {
			util.hideLoad()
			wx.removeStorageSync('token')
			wx.removeStorageSync('userInfo')
			util.showErrorToast('获取openid失败')
		})
	},
	
	onShareAppMessage() {
		return promise = new Promise(resolve => {
			resolve({
				title: '八马茶业开业邀请',
				path: "/packagePoster/index"
			})
		})
	}
})