<template>
	<view class="shop-mine">
		<!-- #ifdef APP-PLUS || APP -->
		<!-- <wrap-version-update id="wxf3657c94aa01a3f0" btnBgColor="#66be4d" :auto="false" ref="wrapVersion" @check="handleCheck"></wrap-version-update> -->
		<!-- #endif -->
  
		<view class="mine-header">
			<view class="avatar">
				<img v-if="isLogin && selfInfo.avatar" class="avatar_img" :src="selfInfo.avatar" alt=""/>
				<img v-else class="avatar_img" src="https://image.jxc4.com/image/9dc7d11b8e64049273dd1bc6ad938166.png?imageView2/1/w/120/h/120" alt=""/>
			</view>
			<view class="user-info">
				<view class="info" v-if="isLogin">
					<view>
						<view class="nick-name" v-if="selfInfo.name!== undefined "> {{ selfInfo.name}}</view>
						<!-- | hideMobile -->
						<view class="mobile" v-if="selfInfo.mobile">{{ selfInfo.mobile}}</view>
					</view>
					<view v-if="selfInfo.userMembers" class="vip">
						VIP{{ selfInfo.userMembers[0].memberTypeID }}
						<span v-if="endAt">({{ endAt }}到期)</span>
					</view>
				</view>
	
				<!-- #ifdef	MP-WEIXIN || APP-PLUS -->
				<button v-else class="btn-login" @click="login"> 立即登录/注册</button>
				<!-- #endif -->

				<!-- #ifdef MP-TOUTIAO -->
				<button v-else class="btn-login" @tap="login" data-eventsync="true" > 立即登录/注册</button>
				<!-- #endif -->

				<!-- #ifdef MP-ALIPAY -->
				<button v-else class="btn-login" open-type="getAuthorize" @getAuthorize="login" scope='phoneNumber'> 立即登录/注册</button>
				<!-- #endif -->

				<!-- #ifdef MP-KUAISHOU -->
				<view v-else class="btn-login" @click="login">立即登录/注册</view>
				<!-- #endif -->

			</view>
		</view>
	  	<!-- 订单块 -->
	  	<view v-if="isLogin && isShowShop" class="order-wall">

			<!-- #ifndef APP || APP-PLUS -->
			<left-right-cell>
				<template  #left>
					<view class="left">
						<view class="icon icon-order"></view>
						<text>我的订单</text>
					</view>
				</template>
				
				<template #right>
					<!-- @click.native="goMyOrder('all')" -->
					<text slot="" class="right" @click="goMyOrder('all')">查看全部订单</text>
				</template>
				
			</left-right-cell>
			<!-- #endif -->
  
			<!-- #ifdef APP || APP-PLUS -->
			<left-right-cell @click.native="goMyOrder('all')">
				<template #left>
					<view class="left">
						<view class="icon icon-order"></view>
						<text>我的订单</text>
					</view>
				</template>

				<template #right>
					<text class="right">查看全部订单</text>
				</template>				
			</left-right-cell>
			<!-- #endif -->

			<view class="order-status">
				<badge class="status-item" :count="orderCount.waitCount">
					<view class="status-item-wrapper" @click="goMyOrder('waitPay')">
						<view class="icon icon-pay"></view>
						<text class="text">待支付</text>
					</view>
				</badge>
				<badge class="status-item" :count="orderCount.deliverCount">
					<view class="status-item-wrapper" @click="goMyOrder('waitReceive')">
						<view class="icon icon-waitreceiving"></view>
						<text class="text">待收货</text>
					</view>
				</badge>
				<badge class="status-item" :count="0">
					<view class="status-item-wrapper" @click="goMyOrder('waitComment')">
						<view class="icon icon-waitcomment"></view>
						<text class="text">待评价</text>
					</view>
				</badge>
				<badge class="status-item" :count="0">
					<view class="status-item-wrapper" @click="goAfterSales">
						<view class="icon icon-aftersale"></view>
						<text class="text">售后/退款</text>
					</view>
				</badge>
			</view>
		</view>
		<!-- 订单块 -->
  
		<!-- 我的地址 -->
		<!--  && isShowShop -->
		<view class="my-cell mt20" @click="goAddressManager" v-if="isLogin && isShowShop">
			<left-right-cell>
				<template #left>
					<view class="left">
						<view class="icon icon-address"></view>
						<view>我的地址</view>
					</view>
				</template>
			</left-right-cell>
		</view>
		<!-- 我的地址 -->
  
		<!-- #ifdef MP-WEIXIN || MP-ALIPAY -->
		<!-- 会员中心 -->
		<!-- && isShowShop -->
		<view class="my-cell mt20" @click="goVip" v-if="isLogin">
			<left-right-cell>
				<template #left>
					<view class="left">
						<view class="icon-wsx icon-vip"></view>
						<view>会员中心</view>
					</view>
				</template>
			</left-right-cell>
		</view>
		<!-- 会员中心 -->
		<!-- #endif -->
  
		<!-- 联系客服 -->
		<view class="my-cell service" @click="contactService">
			<left-right-cell>
				<template #left>
					<view class="left">
						<view class="icon icon-service"></view>
						<view>联系客服</view>
					</view>
				</template>
			</left-right-cell>
		</view>
		<!-- 联系客服 -->

		<!-- #ifndef MP-KUAISHOU || MP-ALIPAY -->
		<!-- 我的推广码 -->
		<view class="my-cell promopte" @click="goPromote" v-if="isBindMobile && iosOrAndroid.platform!=='ios'">
			<left-right-cell>
				<template #left>
					<view class="left">
						<view class="icon icon-mypromote"></view>
						<view>我的推广码</view>
					</view>
				</template>
			</left-right-cell>
		</view>
		<!-- 我的推广码 -->
		<!-- #endif -->
	  
		<!-- #ifdef MP-WEIXIN -->
		<!-- 下载app -->
		<!-- <div class="my-cell promopte" @click="downloadAPP">
			<left-right-cell :noClick="true">
			<div slot="left" class="left">
				<div class="icon icon-downloadApp"></div>
				<div>点击下载APP</div>
			</div>
			</left-right-cell>
		</div> -->
		<!-- 下载app -->
		<!-- #endif -->
   
	  	<!-- #ifdef APP-PLUS || APP -->
	  	<view style="border-top: 1rpx solid #E4E7ED;"  @click="updateAPP">
			<!-- <left-right-cell>
				<template #left>
					<div class="left">
						<div class="icon icon-checkUpdate"></div>
						<div>检查更新</div>
					</div>
				</template>

				<template #right>
					<div class="right" >
						<div class="rightImgBox" v-if="versionText!=='当前版本号'">
							<img src="https://image.jxc4.com/image/229a8908c77ce7b489713ba4fdd6b996.png" alt="" clss="right-img" >
						</div>
						<div >
							<span :style="{color:versionText=='当前版本号'?'':'red'}">{{version}}</span>
						</div>
					</div>
				</template>
			</left-right-cell> -->
			<view style="display:flex;" class="checkUpdate">
				<view class="left">
					<view class="icon icon-checkUpdate"></view>
					<view>检查更新</view>
				</view>
				<view class="right" >
					<view class="rightImgBox" v-if="versionText!=='当前版本号'">
						<img src="https://image.jxc4.com/image/229a8908c77ce7b489713ba4fdd6b996.png" alt="" clss="right-img" >
					</view>
					<view>
						<span :style="{color:versionText=='当前版本号'?'':'red'}">{{version}}</span>
					</view>
				</view>
			</view>
		</view>
		<!-- #endif -->
	
  
		<!-- 退出登录 -->
		<view class="login-out mt20" @click="handleLogout" v-if="isLogin">退出登录</view>
		<!-- 退出登录 -->
		
		<!-- loading -->
		<zy-loading></zy-loading>

	</view>
  </template>
  
<script>
import reComputedCarCount from "@/mixins/reComputedCarCount.js";
import LeftRightCell from "@/components/layout/left-right-cell.vue";
import { mapGetters } from "vuex";
import Badge from "@/components/badge/badge.vue";
import { modal, errToast,jumpPage,setTabBarBadge } from "@/utils/uniapi.js";
import ZyLoading from "@/components/Loading/loading";
import { timeFormat3 } from '@/utils'
import {store} from '@/store'
import orderPage from '@/apis/orderPage';
import loginAPI from '@/apis/login'

export default {
	name: "ShopMine",
	mixins: [reComputedCarCount],
	components: {
		LeftRightCell,
		Badge,
		ZyLoading
	},
	data() {
		return {
			orderCount: {
				waitCount: 0,
				deliverCount: 0,
			},
			endAt: '',
			version: '1.0.0',
			versionText: "当前版本号",
			isChech: true,
		};
	},
	computed: {
		...mapGetters({
			selfInfo: "login/selfInfo",
			isLogin: "login/isLogin",
			isBindMobile: "login/isBindMobile",
			isMaterial: "indexPage/isMaterial",
			isShowShop: 'isShowShop',
			iosOrAndroid: "iosOrAndroid",
			tmpData:'login/tmpData',
			carCount:"cartPage/carCount"
		})
	},
	watch: {
		carCount: {
			handler(val) {
				if(val) setTabBarBadge('set',val)
			},
			immediate:true
		}
	},
	created() {
		if (this.selfInfo.userMembers) {
			this.endAt = timeFormat3(this.selfInfo.userMembers[0].endAt)
		}
		uni.showTabBar()		// 显示tabbar
		// #ifdef APP-PLUS || APP
			// this.getUpdate()
		// #endif
	},
	async onShow() {
		try {
			// await this.globalLogin()
			this.showLoad();
			if (this.isLogin) {
				await this.handleGetOrderCount();
			}
			// if (this.isMaterial) {
			// 	await getMatterStoreOrderStatus();
			// }
			if(this.carCount) setTabBarBadge('set',this.carCount)
		} catch (e) {
			console.error(e);
			errToast(e);
		} finally {
			uni.showTabBar()		// 显示tabbar
			this.hideLoad();
		}
	},
	async onPullDownRefresh() {
		console.log("下拉刷新");
		// uni.stopPullDownRefresh()
		try {
			this.showLoad();
			if (this.isLogin) {
				// 1.个人信息
				let selfInfo = await loginAPI.getSelfInfo() // 获取用户信息
				store.commit('login/saveSelfInfo', selfInfo)
				// 请求订单数量
				await this.handleGetOrderCount();
			}
		} catch (e) {
			console.error(e);
			errToast(e);
		} finally {
			uni.stopPullDownRefresh();
			this.hideLoad();
		}
	},
	filters: {
		hideMobile(mobile) {
			return mobile
				? mobile.split("").map((item, index) => {
					if (index >= 3 && index <= 6) return "*";
					else return item;
				  }).join("")
				: "";
		},
	},
	methods: {
		// 登录
		async login() {
			let that = this
			// #ifdef MP-WEIXIN
			let obj = {
				avatarUrl: 'https://image.jxc4.com/image/9dc7d11b8e64049273dd1bc6ad938166.png',
				nickName:String(new Date().getTime()).substring(0, 11) // 模拟手机号
			}
			uni.setStorageSync('aldstat_user_info', obj)
			await this.globalLogin()
			if (JSON.stringify(this.tmpData) !== '{}')	jumpPage('navigateTo', `/pagesAuth/auth-index/index?type=weixinmini`)
			
			// let obj = {
			// 	avatarUrl: 'https://image.jxc4.com/image/9dc7d11b8e64049273dd1bc6ad938166.png',
			// 	nickName:String(new Date().getTime()).substring(0, 11) // 模拟手机号
			// }
			// uni.setStorageSync('aldstat_user_info', obj)
			// jumpPage('navigateTo', `/pagesAuth/auth-index/index?type=weixinmini`)

			// #endif

			// #ifdef MP-TOUTIAO
			// 有手机号权限时的操作
			// uni.getUserProfile({
			//   success(res) {
			//     uni.setStorageSync('aldstat_user_info',res.userInfo)
			//     uni.login({
			//       force: true,
			//       success(r) {
			//         jumpPage("navigateTo",`/pagesAuth/auth-index/index?ttCode=${r.code}`)
			//       }
			//     });
			//   },
			//   fail(err) {
			//     console.log("getUserProfile 调用失败", err);
			//     uni.login({
			//       force: true,
			//       success(r) {
			//         jumpPage("navigateTo",`/pagesAuth/auth-index/index?ttCode=${r.code}`)
			//       },
			//     });
			//   },
			// });

			// 无手机号权限时
			
			tt.getUserProfile({
				async complete(res) {
					if (res.errMsg === "getUserProfile:ok") uni.setStorageSync('aldstat_user_info', res.userInfo)
					await that.globalLogin()
					if(JSON.stringify(that.tmpData) !== '{}') await store.dispatch('login/analyzePhone')
					jumpPage('switchTab','/pages/index/index')  // 跳转
				}
			})
			// #endif

			// #ifdef MP-KUAISHOU
			ks.getUserInfo({
					complete(res) {
						if(res.userInfo) uni.setStorageSync('aldstat_user_info',res.userInfo)
						uni.login({
							success(r) {
								jumpPage('navigateTo',`/pagesAuth/auth-index/index?type=ksMini&ksCode=${r.code}`)
							},
						})
				}
			});
			// #endif

			// #ifdef APP-PLUS || APP
			jumpPage('navigateTo',`/pagesAuth/auth-index/index?type=wxApp`)
			// #endif

			// #ifdef MP-ALIPAY
			my.getPhoneNumber({
				success: async (res) => {
					let encryptedData = JSON.parse(res.response);
					await that.globalLogin()
					if (JSON.stringify(this.tmpData) !== '{}') await store.dispatch('login/analyzePhone', encryptedData.response)
				},
				fail: (res) => {
					console.log("获取失败", res);
				},
			})
			// #endif
		},
		// 获取订单数量
		async handleGetOrderCount() {
			try {
				this.orderCount = await orderPage.getOrderCount();
			} catch (e) {
				throw e;
			}
		},
		// 退出登录
		async handleLogout() {
			let res = await modal(
				"确定退出?",
				"退出登录后将无法查看订单，重新登录即可查看"
			);
			if (res) {
				uni.clearStorageSync()	// 清除缓存
				store.commit("cartPage/saveCartList",[])					// 清除本地购物车
				store.commit("login/changeLoginStatus",false)				// 改变登录状态
				store.commit("indexPage/saveMaterialInfo",{})				// 清除物料信息
				store.commit('indexPage/savePromote','')					// 推广码
				store.commit('indexPage/saveQueryStoreID', '')				// 清除扫码进入的参数
				await store.dispatch('indexPage/getBrandInfo',{brandID:1})	// 将品牌更改为1
				setTabBarBadge('',0)
			}
		},
		

		// 下载app
		// downloadAPP() {
		//   wx.showModal({
		//     title: "提示",
		//     content: "点击确认复制地址到浏览器直接下载",
		//     showCancel: false,
		//     success() {
		//       copyData("http://www.jxc4.com/jxc4app/app.apk");
		//     },
		//   });
		// },
		
		// #ifdef APP-PLUS || APP
		updateAPP() {
			console.log('this.$refs',this.$refs.wrapVersion)
			return
			this.$refs.wrapVersion.check()
			if (!this.isChech) {
				uni.showToast({
					title: "当前版本为最新版",
					icon: "none",
					position: "bottom",
				});
			}
		},
		handleCheck(res) {
			if (this.iosOrAndroid) {
				let info = this.iosOrAndroid
				let version = Number(res.version.split('.').join(''))
				let appWgtVersion = Number(info.appWgtVersion.split('.').join(''))
				if (version > appWgtVersion) {
					this.version = res.version;
					this.versionText = "发现新版本";
					this.isChech = true;
					
				} else {
					this.version = info.appWgtVersion;
					this.versionText = "当前版本号";
					this.isChech = false;
				}
			} else {
				let that = this
				uni.getSystemInfo({
					success: info => {
						store.commit('setIosOrAndroid', info)
						that.handleCheck(res)
					}
				})
			}

		},
		// #endif

		//联系客服
		contactService() {
			uni.makePhoneCall({
				phoneNumber: "18048531223", //石老板电话
			});
		},
		
		// 跳转到所有订单
		goMyOrder(name) {
			jumpPage('navigateTo',`/pagesOrders/my-order/index?name=${name}`)
		},
		// 跳转到售后/退款
		goAfterSales() {
			jumpPage('navigateTo',`/pagesOrders/my-afsorder/index`)
		},
		// 跳转到地址管理页面
		goAddressManager() {
			jumpPage('navigateTo',`/pagesAddress/mine-address/index?isManager=true`)
		},
		//会员中心
		goVip() {
			jumpPage('navigateTo','/pagesMine/vip/index')
		},
		// 跳转到我的推广码
		goPromote() {
			jumpPage('navigateTo',"/pagesMine/my-promote/index")
		}
	}
};
</script>

<style lang="scss">
@import "./mine.scss";
page {
background: #f4f4f4;
}
</style>