<template>
	<view class="pd-b-px-55">
		<view class="top_box">
			<view class="user_box justify-between justify-middle pd-l-50 pd-r-30 pd-v-45">
				<view class="justify-middle">
					<view class="user_head">
						<van-image fit="cover" width="80rpx" height="80rpx"
							     @tap="onImagePreview(state.user.userHeadImage||'https://img.edsmall.com/ROOT/ETao/fenxiao/h5/mall_default.png')" round
							     :src="state.user.userHeadImage||'https://img.edsmall.com/ROOT/ETao/fenxiao/h5/mall_default.png'" />
					</view>
					<view class="mg-l-30 text-white text-xl">{{ state.user.userPhone }}</view>
				</view>
				<view class="user_edit btn" @tap="goto('/pages/my/detail')">账户管理
					<van-icon name="edit" />
				</view>
			</view>
			<van-cell-group inset class="mg-b-40">
				<van-cell :border="false">
					<template #title>
						<view class="flex wrap justify-between">
							<view v-for="item in state.actionList" class="text-center btn pd-h-25 pd-v-20"
								@tap="goto(item.url)">
								<van-badge :content="item.badge>0?item.badge:''">
									<van-image width="32px" height="32px" :src="item.icon" />
								</van-badge>
								<view class="text-s">{{ item.name }}</view>
							</view>
						</view>
					</template>
				</van-cell>
				<van-divider class="mg-v-0" />
				<van-cell :border="false">
					<template #title>
						<view class="justify-between text-center">
							<view class="long_action_btn justify-center btn" @tap="goto('/pages/my/fav')">
								<view class="justify-middle">
									<van-image class="pd-r-px-10" width="20px" height="20px"
										     src="/static/img/fav.png" />
									我的收藏
								</view>
							</view>
							<view class="v-divider" />
							<view class="long_action_btn justify-center btn"
								@tap="goto('/pages/my/address')">
								<view class="justify-middle">
									<van-image class="pd-r-px-10" width="20px" height="20px"
										     src="/static/img/address.png" />
									收货地址
								</view>
							</view>
						</view>
					</template>
				</van-cell>
			</van-cell-group>
		</view>
		<van-sticky v-if="state.good.list.length > 0">
			<van-cell-group class="sh" style="border-radius: 8px 8px 0 0">
				<van-cell style="border-radius: 8px 8px 0 0">
					<template #title>
						<view class="justify-middle">
							<text class="text-l">为您推荐</text>
							<view class="v-divider mg-h-px-10" />
							<text class="text-ss text-gray">大牌任你选</text>
						</view>
					</template>
					<template #right-icon>
						<view class="justify-middle text-daryGray text-s btn"
							@tap="goto('/pages/goodList/index')">
							查看更多
							<van-icon name="arrow" />
						</view>
					</template>
				</van-cell>
			</van-cell-group>
		</van-sticky>
		<van-list :loading="state.good.loading">
			<van-row gutter="12" style="margin: 15rpx 20rpx;">
				<van-col  span="12"  v-for="item in state.good.list" style="margin-bottom: 25rpx">
					<ShopCard :item="item"></ShopCard>
				</van-col>
			</van-row>
		</van-list>
		<to-top />
	</view>
</template>

<script setup lang="ts">
    import ShopCard from '@/components/ShopCard.vue';
    import toTop from '@/components/tool/toTop.vue';
    import {onBeforeMount, reactive} from "vue";
    import {Dialog, ImagePreview} from 'vant';
    import api from "@/api";
    import {onShow} from "@dcloudio/uni-app";

    const state = reactive({
        user: {} as any,
        phone: '',
        // 建议以后走运营中心，我想走
        actionList: [
            {
                name: '待付款',
                url: '/pages/order/orderList?index=1',
                icon: 'https://img.edsmall.com/ROOT/ETao/fenxiao/h5/order_wait_pay.png',
                badge: ''
            },
            {
                name: '待发货',
                url: '/pages/order/orderList?index=2',
                icon: 'https://img.edsmall.com/ROOT/ETao/fenxiao/h5/order_wait_deliver.png',
                badge: ''
            },
            {
                name: '待收货',
                url: '/pages/order/orderList?index=3',
                icon: 'https://img.edsmall.com/ROOT/ETao/fenxiao/h5/order_wait_receive.png',
                badge: ''
            },
            {
                name: '我的订单',
                url: '/pages/order/orderList?index=0',
                icon: 'https://img.edsmall.com/ROOT/ETao/fenxiao/h5/order_all.png',
                badge: ''
            },
        ],
        good: {
            loading: false,
            finished: false,
            fail: false,
            page: 0,
            list: [] as any
        },
    });

    onShow(() => {
        if (state.phone) {
            accountInfo()
            getOrderCount()
        }
    })
    function getUrl(url) {
        const q = {};
        url.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => q[k] = v);
        return q;
    }
    onBeforeMount(() => {
        console.log(window.location.href,'window.location.href');
        let href =getUrl(window.location.href).mobilePhone? true:false
        console.log(href,'href');
        // 判断小程序是否登录成功
	  if(href){
            api.wxlogin({
                mobilePhone:getUrl(window.location.href).mobilePhone,
            }).then((data: any) => {
                uni.setStorageSync('user', data)
                uni.setStorageSync('login', {
                    store: false,
                    phone:getUrl(window.location.href).mobilePhone,
                    pwd:  '',
                })
                state.phone = data.account
                accountInfo()
                getOrderCount()
                onGoodLoad()
            })
	  }else {
            const user: any = uni.getStorageSync('user') || {account: undefined}
            if (user.token) {
                state.phone = user.account
                if (!state.phone) {
                    Dialog.alert({
                        title: '数据异常',
                        message: '当前用户缺少手机信息，请联系开发人员#021',
                        confirmButtonText: '返回首页'
                    }).then(() => {
                        uni.reLaunch({
                            url: '/'
                        })
                    })
                    return
                }
                accountInfo()
                getOrderCount()
                onGoodLoad()
            } else {
                const isWxjs_environment = uni.getStorageSync("isWxjs_environment") || false;
                if (isWxjs_environment) {
                    window._wx.miniProgram.redirectTo({url: "/pages/login/login"})
                } else {
                    Dialog.confirm({
                        message: '您尚未登录，请前往登录',
                        title: "提示",
                        cancelButtonText: '返回首页'
                    }).then(() => {
                        uni.reLaunch({
                            url: '/pages/login/login'
                        })
                    }).catch(() => {
                        uni.reLaunch({
                            url: '/'
                        })
                    });
                }
            }
	  }
    })

    function accountInfo() {
        api.accountInfo({phone: state.phone}).then((data: any) => {
            state.user = data
        })
    }

    function getOrderCount() {
        api.getOrderCount().then((data: any) => {
            state.actionList[0].badge = data.waitForPay
            state.actionList[1].badge = data.waitForDelivery
            state.actionList[2].badge = data.waitForReceive
        })
    }

    function goto(url: any) {
        url && uni.navigateTo({url})
    }

    function onGoodLoad() {
        if (state.good.loading || state.good.fail) return
        state.good.loading = true
        state.good.page += 1
        api.productList({sortType: 0, pageSize: 20, link: uni.getStorageSync("subdomain")}).then((data: any) => {
            if (!data) return
            if (!data || !data.hasNextPage) {
                state.good.finished = true
            }
            state.good.list.push(...data.list)
        })
            .catch(() => {
                state.good.fail = true
            })
            .finally(() => {
                state.good.loading = false
            })
    }

    function onImagePreview(url: string) {
        ImagePreview({images: [url], closeable: true})
    }
</script>

<style lang="scss" scoped>
	.top_box {
		background: url('@/static/img/dz/my_bg1.png') no-repeat;
		background-size: 100% auto;

		.user_box {

			.user_head {
				width: 78 rpx;
				height: 78 rpx;
				border: 2 rpx solid #fff;
				position: relative;
				border-radius: 50%;

				&::before {
					content: "";
					position: absolute;
					border-radius: 50%;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					background: linear-gradient(180deg, #ffe5cd 0%, #ffb399 100%);
				}
			}

			.user_edit {
				color: #fff;
				background: rgba(255, 255, 255, 0.1000);
				border-radius: 50px;
				border: 1px solid rgba(255, 255, 255, 0.2400);
				padding: 6px 12px;
				font-size: 12px;
			}
		}

		.long_action_btn {
			width: 48%;
		}
	}

	.v-divider {
		width: 0.5px;
		height: 20px;
		background: #DDDDDD;
	}
</style>
