import store from '@/store'
import StoreApi from '@/api/store'
import {
	openidCode,
	getCustomer,
	getAgents,
	getYhinfo,
	getUserDdinfo
} from '@/api/app'
import storage from '@/utils/storage'


import SettingModel from '@/common/model/Setting'

const CACHE_KEY = 'Store'

// 写入缓存, 到期时间10分钟
const setStorage = data => {
	const expireTime = 10 * 60
	storage.set(CACHE_KEY, data, expireTime)
}

// 获取缓存中的数据
const getStorage = () => {
	return storage.get(CACHE_KEY)
}

/**
 * 普通用户
 * 
 * 微信公众号进入
 * 从get参数获取code
 * code鉴权 err: 拦截弹出
 * 鉴权后获取 openid、userid
 * 更新用户信息
 * 
 * 注册代理商
 * 微信公众号进入
 * 从get参数获取code
 * code鉴权
 * 鉴权后获取 openid、userid
 * 更新用户信息
 * 
 * 注册通过
 * 更新用户信息
 * 
 */

// 获取后端接口鉴权设置
const getApiData = async (data) => {
	return new Promise(async (resolve, reject) => {
		// console.log(data, 'getApiData - 鉴权')
		let param = data?.param ? data?.param.split(',') : ['', '']
		
		// 临时调试 --start--
		// let resCode = getWxOpen('')
		// let param = 'pages/user/index,shopping'.split(',')
		// 临时调试 --ebd--
		
		if (param[1]) {
			storage.set('wx_v', param[1])
		}
		if (param[2]) {
			console.log('扫描企业二维码进入，手动更新企业码')
			storage.set('wx_qym', param[2])
		}
		// 获取 User Agent
		let userAgent = navigator.userAgent.toLowerCase();
		// 判断是否在微信中打开
		const type = (userAgent.indexOf('micromessenger') === -1)
		if (false) {
			store.commit('SET_PLATTYPE', '其他')
			store.commit('SET_VERIFYMSG', '错误！请在微信浏览器中打开')
			resolve({
				resCode: false,
				err: '请在微信浏览器中打开'
			})
			return
		} else {
			store.commit('SET_PLATTYPE', '微信')
		}

		let wxCode = data.code
		let resCode = ''
		if (wxCode) {
			// 鉴权
			resCode = await getWxOpen(wxCode)
			// 如果没有则存起来
			if (!storage.get('WX_CODE')) {
				storage.set('WX_CODE', wxCode)
			}
		} else if (!storage.get('wx_userid') || !storage.get('wx_openid')) {
			store.commit('SET_VERIFYMSG', '错误,没有鉴权码！')
		}

		// 获取用户基础信息
		// getCustomerData()

		// 初始化商城数据
		initStoreData(StoreApi.infoShop.data)
		// console.log(StoreApi.infoShop.data, '初始化商城数据结束')

		// 回调
		resolve({
			resCode: storage.get('WX_CODE') || resCode,
			err: `${resCode ? '没有鉴权码' : '没有鉴权码！'}`,
			infoShop: StoreApi.infoShop.data
		})
	})
}

// 初始化商城数据
const initStoreData = data => {
	// 将商城基本信息写入缓存
	setStorage(data)
	// 设置商城设置缓存
	SettingModel.setStorage(data.setting)
	// 设置全局自定义主题
	SettingModel.setAppTheme()
}

// 鉴权
const getWxOpen = async (wxCode) => {
	return new Promise(async (resolve, reject) => {
		try {
			// 鉴权
			const res = await openidCode({ code: wxCode, qym: storage.get('wx_qym') || '' })
			
			// 临时调试 --start--
			// const res = {
			// 	"Status": 0,
			// 	"Data": {
			// 		"subscribe": 1,
			// 		"userid": "2024081412514638086221",
			// 		"qym": "LGFMwT2m",
			// 		"qyid": "2024080212130193375040",
			// 		"appid": "wxefd01d28b7d41071",
			// 		"weburl": "http://211.149.199.65:5007/",
			// 		"openid": "oI0gr6inthqe1tc9Ex6nwpvGQ49E"
			// 	},
			// 	"Message": "操作成功",
			// 	"OtherData": null
			// }
			// 临时调试 --end--
			
			if (res.Data.userid) {
				storage.set('wx_openid', res.Data.openid)
				storage.set('wx_userid', res.Data.userid)
				storage.set('wx_qyid', res.Data.qyid)
				storage.set('wx_qym', res.Data.qym)

				// 如果目前用户是企业商，则拼写企业分销码
				if (res.Data.qyid) {
					let fxm =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${res.Data.appid}&redirect_uri=${res.Data.weburl}?param=pages/index/index,shopping,${res.Data.qym}&response_type=code&scope=snsapi_base&state=STATE`
					storage.set('wx_fxm', fxm)
				} else {
					storage.set('wx_fxm', '')
				}

				// 获取用户基础信息
				await getCustomerData()
				resolve(true)
			} else {
				resolve(false)
			}
		} catch (err) {
			resolve(false)
		}
	})

}

//  获取/更新 用户基础信息 
const getCustomerData = async () => {
	console.log('更新info信息', )
	return new Promise(async (resolve, reject) => {
		// 获取客户信息
		const resCustomer = await getCustomer({
			'customerid.value': storage.get('wx_userid')
		})
		console.log('获取客户信息')
		if (resCustomer.Data) {
			storage.set('wx_userinfo', resCustomer.Data.Data[0])
		}

		// 如果客户是代理商 获取代理商信息
		if (resCustomer.Data.Data[0]?.customertype == '代理商') {
			const resAgents = await getAgents({
				'agentsid.value': storage.get('wx_qyid')
			})
			console.log('获取代理商信息', )
			if (resAgents.Data) {
				storage.set('wx_dlsinfo', resAgents.Data.Data[0])
			}
		}

		if (storage.get('wx_v') === 'activation') {
			// 获取用户 与盒子 信息
			const resYhinfo = await getYhinfo({
				'yhinfocustomerid.value': storage.get('wx_userid'),
				'yhinfoopenid.value': storage.get('wx_openid')
			})
			console.log('获取用户与盒子信息', )
			if (resCustomer.Data) {
				storage.set('wx_yhinfo', resYhinfo.Data.Data)
			}
		} else {
			// 获取用户 与订单 信息
			const resYhinfo = await getUserDdinfo({
				'yhinfocustomerid.value': storage.get('wx_userid'),
				'yhinfoopenid.value': storage.get('wx_openid')
			})
			console.log('获取用户与订单信息', )
			if (resCustomer.Data) {
				storage.set('wx_yhinfo', resYhinfo.Data.Data)
			}
		}


		resolve(true)
	})

}

// 跳转用户端判断
const routerNavTo = async (data) => {
	console.log('开始跳转')
	if (data?.versions === 'enterprise') {
		console.log('******************企业注册页面******************')
		setTimeout(() => {
			this.$navTo('pages/firm/index')
		}, 2000)
	} else {
		console.log('******************商场选购页面******************')
		setTimeout(() => {
			this.$navTo('pages/index/index')
		}, 2000)
	}
}

/**
 * 获取商城基础信息
 * 有缓存的情况下返回缓存, 没有缓存从后端api获取
 */
const data = (isCache = true) => {
	return new Promise((resolve, reject) => {
		const cacheData = getStorage()
		if (isCache && cacheData) {
			resolve(cacheData)
		} else {
			// length of data
		}
	})
}

// 获取商城基本信息
const storeInfo = () => {
	return new Promise((resolve, reject) => {
		data().then(data => resolve(data.storeInfo))
	})
}

// 获取H5端访问地址
const h5Url = () => {
	return new Promise((resolve, reject) => {
		data().then(data => {
			const h5Url = data.clientData.h5.setting.baseUrl
			resolve(h5Url)
		})
	})
}

export default {
	data,
	storeInfo,
	h5Url,
	getApiData,
	getCustomerData,
}