// app.js
import utils from './utils/util.js'
import api from './utils/api.js'
import config from './utils/config.js'
// import {init} from './utils/myPage'
const OssUploader = require('/utils/plugins/ossUpload.js')
let isGetCoupon = false
App({
	onLaunch: function () {
		// 登录
		// 获取用户信息
		// this.getSetting()
		// init({})
		// this.globalData.brandId = config.brandId
		// console.log(this.globalData.brandId);
		this.getSystemInfoSync()
		// 获取nick
		let nick = wx.getStorageSync('nick')
		if(nick){
			const {unionId,userId,wxappOpenId,wxappEcdOpenId,wxchatOpenId} = nick
				wx.setStorageSync('subData', {
					unionId,
					userId,
					openId:wxappOpenId ? wxappOpenId : wxappEcdOpenId ? wxappEcdOpenId : wxchatOpenId
				})
		}
		// 可比克 字体
		wx.loadFontFace({
			family: 'PangMenZhengDao',
			source: 'url("https://hbrand.oss-cn-hangzhou.aliyuncs.com/BUSINESS/SCAN/cpp/kebike/1635742999484228.ttf")',
			global: true
		})
		if (wx.onNeedPrivacyAuthorization) {
			wx.onNeedPrivacyAuthorization((resolve, eventInfo) => {
				wx.removeStorageSync('nick')
				utils.needLogin()
				resolve({ event: 'exposureAuthorization' })
			})
		}
	},

	getCode() {
		return new Promise((resolve, reject) => {
			wx.login({
				success: res => {
					if (res.code) {
						// 防止获取两次code
						if (res.code !== this.globalData.code) {
							wx.checkSession({
								success: () => {
									this.globalData.code = res.code
									resolve(res.code)
								},
								fail: () => {
									wx.login({
										success: res => {
											this.globalData.code = res.code
											resolve(res.code)
										}
									})
								}
							})
						}
					}
				}
			})
		})
	},

	getLocation(type = 'gcj02') {
		const _this = this
		return new Promise((resolve, reject) => {
			wx.getFuzzyLocation({
				type,
				success(res) {
					_this.globalData.locate = `${res.latitude},${res.longitude}`
					resolve(res)
				},
				fail(res) {
					wx.setStorageSync('isIndexClick', false)
					wx.navigateTo({
						url: '/pages/defaultError/defaultError?errorId=0&errorMsg=授权失败|我们需要您的位置信息来判断您能否参与活动, 请允许授权'
					})
				}
			})
		})
	},

	updateUserInfo(code, memberInfo) {
		return this.Login(code, memberInfo)
	},
	async updateUserInfoScan(code, memberInfo) {
		await this.getLocation()
		return this.LoginScan(code, memberInfo)
	},

	getUserInfo() {
		return new Promise((resolve, reject) => {
			if (!wx.getUserProfile) {
				resolve({})
				return
			}
			wx.getUserProfile({
				desc: '用于完善会员资料',
				complete(res) {
					resolve(res)
				}
			})
		})
	},

	Login(code, { encryptedData = '', iv = '' }) {
		const _this = this
		const params = {
			encryptedData,
			iv,
			code
		}
		return new Promise((resolve, reject) => {
			this.api.updateUserInfo(params).then(res => {
				const {unionId,userId,wxappOpenId,wxappEcdOpenId,wxchatOpenId} = res.data
				wx.setStorageSync('nick', res.data)
				wx.setStorageSync('subData', {
					unionId,
					userId,
					openId:wxappOpenId ? wxappOpenId : wxappEcdOpenId ? wxappEcdOpenId : wxchatOpenId
				})
				if (res.status === 1) {
					resolve(res.data)
					_this.globalData.token = res.data.token
					_this.globalData.userId = res.data.userId
				}
			})
		})
	},
	LoginScan(code, { encryptedData = '', iv = '' }) {
		const _this = this
		const { locate } = _this.globalData
		const params = {
			encryptedData,
			iv,
			code,
			locate
		}
		return new Promise((resolve, reject) => {
			this.api.updateUserInfoScan(params).then(res => {
				const {unionId,userId,wxappOpenId,wxappEcdOpenId,wxchatOpenId} = res.data
				wx.setStorageSync('nick', res.data)
				wx.setStorageSync('subData', {
					unionId,
					userId,
					openId:wxappOpenId ? wxappOpenId : wxappEcdOpenId ? wxappEcdOpenId : wxchatOpenId
				})
				if (res.status === 1) {
					resolve(res.data)
					_this.globalData.token = res.data.token
				}
			})
		})
	},

	getCoupon(locate, presentId, cb, linkId = '') {
		if (isGetCoupon) {
			wx.showToast({
				title: '正在领取,请耐心等待',
				icon: 'none'
			})
			return
		} else {
			isGetCoupon = true
		}
		this.api
			.getCoupons({
				locate: locate,
				presentId: presentId,
				linkId: linkId
			})
			.then(res => {
				isGetCoupon = false
				if (res.status === 1) {
					setTimeout(() => {
						wx.showToast({
							title: `领取成功, 已领${wx.getStorageSync('couponForGetCount') + 1}张`,
							icon: 'none',
							duration: 3000
						})
					}, 1000)
				} else {
				}
				if (cb) {
					cb(res.data)
				}
			})
	},
	uploadFile(context, callBack, directory = 'fileData/') {
		let filePath = context
		if (typeof context === 'object') {
			wx.showLoading({
				title: context.msg
			})
			filePath = context.filePath
		}
		OssUploader(filePath, directory, res => {
			wx.hideLoading()
			callBack(res)
		})
	},
	/**
	 * @param {*} path 链接
	 * @return {*}
	 * @author: swordman
	 * @description: 获取链接路径
	 * @example:
	 */
	GetUrlParh(path) {
		//获取type
		if (!path) {
			return ''
		}
		// return path.split('n/')[1].split('?')[0]
		const parts = path.split('/'); // 以 '/' 为分隔符拆分字符串
		return parts[3].toLowerCase();
	},
	uploadFile(context, callBack, directory = 'fileData/') {
		let filePath = context
		if (typeof context === 'object') {
			wx.showLoading({
				title: context.msg
			})
			filePath = context.filePath
		}
		OssUploader(filePath, directory, res => {
			wx.hideLoading()
			callBack(res)
		})
	},
	// 订阅消息
	sendSubscribeMessage(tmplIds = [], cb) {
		if (wx.requestSubscribeMessage) {
			wx.requestSubscribeMessage({
				tmplIds,
				success(res) {},
				fail(res) {},
				complete(res) {
					if (cb) {
						cb(res)
					}
				}
			})
		} else {
			if (cb) {
				cb()
			}
		}
	},
	// 获取设备信息
	getSystemInfoSync() {
		try {
			const res = wx.getSystemInfoSync()
			console.log(res, '设备信息')
			this.globalData.systemInfo = res
		} catch (e) {}
	},
	getStatusBarHeight() {
		return this.globalData.systemInfo?.statusBarHeight || 20
	},
	getTitleBarHeight() {
		return this.globalData.systemInfo?.model.indexOf('iPhone') !== -1 ? 44 : 48
	},
	globalData: {
		userInfo: null,
		token: '',
		isUserInfoScope: false,
		isEnableLocation: 0,
		distance: 0,
		payAmount: 0,
		storeName: '',
		storeId: '',
		locate: '',
		weiyiUserIdentity: false, // 唯怡一码双扫用户身份判断,true:服务员,false:消费者
		qrCode: '', // 唯怡一码双扫页面调用的二维码
		brandId: '117', // 唯怡一码双扫使用内容117、测试196
		groupId: '', // 唯怡一码双扫使用内容
		summary: '', // 唯怡一码双扫使用内容
		thirdPhone: '', // 唯怡一码双扫使用内容
		simpleCode: '', // 唯怡一码双扫使用内容
		isUserPhone: '', // 唯怡一码双扫使用内容,判断用户是否需要填写手机号
		scopeCamera: '',
		systemInfo: null
	},
	utils: utils,
	api: api,
	config: config
})

// eslint-disable-next-line no-extend-native
Date.prototype.pattern = function (fmt) {
	// 日期处理
	const o = {
		'M+': this.getMonth() + 1, // 月份
		'd+': this.getDate(), // 日
		'h+': this.getHours() % 12 === 0 ? 12 : this.getHours() % 12, // 小时
		'H+': this.getHours(), // 小时
		'm+': this.getMinutes(), // 分
		's+': this.getSeconds(), // 秒
		'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
		S: this.getMilliseconds() // 毫秒
	}
	const week = {
		0: '\u65e5',
		1: '\u4e00',
		2: '\u4e8c',
		3: '\u4e09',
		4: '\u56db',
		5: '\u4e94',
		6: '\u516d'
	}
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
	}
	if (/(E+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (RegExp.$1.length > 1 ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[this.getDay() + ''])
	}
	for (const k in o) {
		if (new RegExp('(' + k + ')').test(fmt)) {
			fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
		}
	}
	return fmt
}