/*
 * @description        用于公用的数据状态管理模块。
 * @example-state      state的调用方法            this.$store.state.common.$S_tabbar_tabIdx
 * @example-mutations  mutations的调用方法        this.$store.commit('MUTA_TABIDX',param);
 * @example-actions    actions的调用方法          this.$store.dispatch('ACTI_TABIDX',param);
 */ // 日志打印
import reportErr from '@/util/errorReport/log.js';
// 导入公用mixin
import comMix from '@/common/mixin.js';
// 导入接口
import {
	API_getOpenid,
	API_getMachine,
	API_getConponList,
	API_getCheckYHJList,
} from '@/common/api.js';
export default {
	name: 'common',
	/*
	 ** state格式：$S（表示store的数据）  tabbar（表示哪一个页面） tabIdx（表示页面的哪一个数据）
	 */
	state: {
		// 底部导航栏下标
		$S_tabbar_tabIdx: 0,
		// 购物车数据
		$S_tabbar_shopCarts: {},
		// 我的页面个人头像和昵称
		$S_mine_avatarNick: {
			avatarUrl: uni.getStorageSync('avatarNick').avatarUrl ||
				'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAMAAAAOusbgAAAASFBMVEX09Pby8vTe3uDPz9DJycm/v8C9vb3BwcLLy8vR0dLp6evn5+i1tbWysrLb29zu7vDNzc7r6+26urrg4OG3t7fj4+TFxcbV1dY8QE/jAAABo0lEQVRo3u2Yi3KCMBBFCY8EIWs0Iv7/n7Y4djqFZEXCTVtnzw+cYZfsqygEQRAEQRAEQRCEt0OVVd1o0x66rNq+tvRFc8ymdSf6gTnn8XaeZthLDm8/0JIM5s5SiCvaq3TQS96BxRVFaLHeM0XBPuhTXAz9ZGfjYkJm+ch4CVnBak5cA8UDJx5wXkUsCiY+82Jcr+h5cf9+4o4X42qX48XACsIVLrI4b6E5sQaKW06M7BIlJy6BYsUk2eIKV8EMIEQV0lu4aJsYwENXtCPD9wkT9hq0NzJX2wy72/FXAj0xLr1jDm9g1LToNeLBYS4+5PEu23Kuq8Bi5oMWy78gvs7F8OX4QTMXN3m8gY3xlEHrgvtTDX/JF09BPPb80o0UZQSO1cw94J5pTLzVzdIT7A3wokv/THtP9d6jZm/WaCfMnquba9dqJ9rdUv08ufNU7xPl5jXtRLNDvG+vaydSP1qN27yf9STpZanVP/MSk2LeGOf0aG/4r75J6dKrqlUML+L/INYp4pQrUJUiTrlNqEr7jegq15gvCIIgCIIgCIIg7M4HkS5rj/A3dbUAAAAASUVORK5CYII=',
			nickName: uni.getStorageSync('avatarNick').nickName || '暂无昵称'
		},
		// app.vue页面的个人登录信息
		$S_app_loginInfos: {},
		// 设备编码：不开机：166581708014999678137587，开机：1665819865612635251739970
		$S_home_clientId: '',
		// 优惠码集合，用来校验重复问题
		$S_car_discountCodeList: [],
		// 如果商品编码是A31-35的则是mini版，图片显示要小些，有新增的话要在/static/images/home/goods.js里面找对应编码
		$S_home_miniProduct: ['A31', 'A32', 'A33', 'A34', 'A35'],
		// 机器状态
		$S_home_clientStatus: {
			// 设备名称
			storeName: '自动售卖机',
			// 是否开机状态
			startStatus: false,
			contactName: '',
			contactPhone: '',
		},
		// 单种商品
		$S_singleBye_shopCarts: {},
		// 优惠券
		$S_home_coupon: '',
		// 优惠券列表
		$S_home_couponList: [],
		// 用户有没有领取过优惠券
		$S_home_hasReceCoup: false,
	},
	getters: {
		// 设备编码
		GETT_clientId(state) {
			return state.$S_home_clientId;
		},
		// 个人登录信息
		GETT_loginInfos(state) {
			return state.$S_app_loginInfos;
		},
		// 是否存在小程序个人信息
		isGetUserInfo(state) {
			if (!state.$S_mine_avatarNick.nickName || state.$S_mine_avatarNick.nickName === '暂无昵称') {
				return false;
			} else {
				return true;
			}
		},
		// 首页购物车的总价格
		totalPrice(state) {
			let totalPrice = 0;
			let shopCarts = state.$S_tabbar_shopCarts;
			if (shopCarts) {
				for (let key in shopCarts) {
					totalPrice = comMix.methods.$M_Big(totalPrice).add(shopCarts[key]['totalPrice']).toNumber();
				}
			}
			return totalPrice;
		},
		// 首页购物车的总数量
		totalNums(state) {
			let nums = 0;
			let shopCarts = state.$S_tabbar_shopCarts;
			if (shopCarts) {
				for (let key in shopCarts) {
					nums = comMix.methods.$M_Big(nums).add(shopCarts[key]['nums']).toNumber();
				}
			}
			return nums;
		},
		// 优惠码集合
		GETT_discountCodeList(state) {
			return state.$S_car_discountCodeList;
		},
		// mini商品编码
		GETT_miniProduct(state) {
			return state.$S_home_miniProduct;
		},
		// 机器状态
		GETT_clientStatus(state) {
			return state.$S_home_clientStatus;
		},
		// 单种商品
		GETT_singleBye_shopCarts(state) {
			return state.$S_singleBye_shopCarts;
		},
		// 优惠券
		GETT_home_coupon(state) {
			return state.$S_home_coupon;
		},
		// 优惠券列表
		GETT_home_couponList(state) {
			const list = [];
			const couponList = state.$S_home_couponList;
			if (couponList.length > 0) {
				couponList.forEach(item => {
					// 如果是没有被使用过的
					if (item.isUse !== '1') {
						list.push({
							label: `${item.discount}元`,
							value: item.discount,
							lastUseDate: item.lastUseDate,
							code: item.code,
							isCheck: false,
						})
					}
				})
			}
			return list;
		},
		// 优惠券的总金额
		GETT_home_totalCoupon(state) {
			let totalMon = 0;
			if (state.$S_home_couponList.length > 0) {
				state.$S_home_couponList.forEach(item => {
					totalMon = comMix.methods.$M_Big(totalMon).add(item.discount).toNumber();
				})
			}
			return totalMon;
		},
		// 用户有没有领取过优惠券
		GETT_home_hasReceCoup(state) {
			return state.$S_home_hasReceCoup;
		},
	},
	mutations: {
		/*
		 ** mutations格式：MUTA（表示mutations里的方法）TABIDX（表示页面的哪一个数据大写）
		 */
		// 改变底部导航栏下标
		MUTA_TABIDX: (state, data) => {
			state.$S_tabbar_tabIdx = data;
		},
		// 改变购物车数据
		MUTA_SHOPCARTS: (state, data) => {
			state.$S_tabbar_shopCarts = {};
			state.$S_tabbar_shopCarts = data;
		},
		// 改变个人头像和昵称
		MUTA_AVATARNICK: (state, data) => {
			state.$S_mine_avatarNick = {};
			state.$S_mine_avatarNick = data;
			uni.setStorageSync('avatarNick', data);
		},
		// 登录获取openid
		MUTA_GETOPENID: (state, data) => {
			state.$S_app_loginInfos = {};
			state.$S_app_loginInfos = data;
		},
		// 储存优惠码
		MUTA_DISCOUNTCODE: (state, data) => {
			state.$S_car_discountCodeList = [];
			state.$S_car_discountCodeList = data;
		},
		// 设置机器编码
		MUTA_SETCLIENTID: (state, data) => {
			state.$S_home_clientId = data;
		},
		// 设置机器状态
		MUTA_SETCLIENTSTATUS: (state, data) => {
			state.$S_home_clientStatus = {};
			state.$S_home_clientStatus = data;
		},
		// 改变单种商品
		MUTA_SINGSHOPCARTS: (state, data) => {
			state.$S_singleBye_shopCarts = {};
			state.$S_singleBye_shopCarts = data;
		},
		// 储存优惠券
		MUTA_SETCOUPON: (state, data) => {
			state.$S_home_coupon = '';
			state.$S_home_coupon = data;
		},
		// 储存优惠券列表
		MUTA_SETCOUPONLIST: (state, data) => {
			state.$S_home_couponList = [];
			state.$S_home_couponList = data;
		},
		// 查询优惠券有没有领取了
		MUTA_HASRECECOUP: (state, data) => {
			state.$S_home_hasReceCoup = false;
			state.$S_home_hasReceCoup = data;
		},
	},
	actions: {
		/*
		 ** actions格式：ACTI（表示actions里的方法）TABIDX（表示页面的哪一个数据大写）
		 */
		// 改变底部导航栏下标
		ACTI_TABIDX: (context, data) => {
			context.commit('MUTA_TABIDX', data);
		},
		// 改变购物车数据
		ACTI_SHOPCARTS: (context, data) => {
			context.commit('MUTA_SHOPCARTS', data);
		},
		// 登录获取openid
		ACTI_GETOPENID: (context) => {
			return new Promise((resolve, reject) => {
				// 登录获取code
				uni.login({
					provider: 'weixin',
					success: async (loginRes) => {
						const code = loginRes.code;
						const param = {
							code
						}
						// 调用openid接口
						const res = await API_getOpenid(param, {
							loading: false
						});
						context.commit('MUTA_GETOPENID', res);
						resolve(true);
					},
					fail: err => {
						// // 错误上报
						reportErr('uni.login的报错！！！', err);
						resolve(false);
					}
				});
			})
		},
		// 查询优惠券有没有领取了MUTA_HASRECECOUP
		ACTI_HASRECECOUP: ({
			commit,
			rootState
		}, coup) => {
			return new Promise(async (resolve, reject) => {
				const res = await API_getCheckYHJList({
					wxId: rootState.common.$S_app_loginInfos.id
				});
				commit('MUTA_HASRECECOUP', res);
				resolve(res);
			})
		},
		// 获取机器状态
		ACTI_SETCLIENTSTATUS: (context, clientId) => {
			return new Promise(async (resolve, reject) => {
				const param = {
					clientId
				};
				const res = await API_getMachine(param);
				const statusParam = {
					storeName: '自动售卖机',
					startStatus: false,
					contactName: res.contactName,
					contactPhone: res.contactPhone,
				}
				// 如果是关机状态可以执行下面操作
				if (res.status == 1) {
					statusParam.storeName = `${res.name}(${clientId})`;
					statusParam.startStatus = true;
				} else {
					statusParam.storeName = `${res.name}(${clientId})`;
					statusParam.startStatus = false;
				}
				context.commit('MUTA_SETCLIENTSTATUS', statusParam);
				// 如果开机
				if (res.status == 1) {
					resolve(true);
				} else {
					resolve(false);
				}
			})
		},
		// 获取优惠券
		ACTI_SETCOUPONLIST: ({
			commit,
			rootState
		}) => {
			return new Promise(async (resolve, reject) => {
				const param = {
					wxId: rootState.common.$S_app_loginInfos.id
				};
				const res = await API_getConponList(param, {
					loading: false
				});
				// 储存优惠券列表到vuex，用于支付判断有没有优惠券可选
				commit('MUTA_SETCOUPONLIST', res);
				resolve(true);
			});
		},
	}
}
