<template>
	<view class="text-center pd-b-px-55">
		<van-sticky>
			<van-nav-bar
					  title="我的订单"
					  left-arrow
					  @click-left="onClickLeft"
			>
				<template #left>
					<van-icon name="arrow-left" size="25" color="#323233" />
				</template>
			</van-nav-bar>
			<van-tabs v-model:active="state.active" color="#ff6600"
				    title-active-color="#ff6600" @click-tab="changeTab">
				<van-tab title="全部">
				</van-tab>
				<van-tab title="待付款">
				</van-tab>
				<van-tab title="待发货">
				</van-tab>
				<van-tab title="待收货">
				</van-tab>
				<van-tab title="已完成">
				</van-tab>
				<van-tab title="已关闭">
				</van-tab>
			</van-tabs>
		</van-sticky>
		<div style="margin-top: .2rem"></div>
		<van-list :loading="state.good.loading" :finished="state.good.finished"  offset="10"
			    @load="onGoodLoad">
			<van-grid :center="false" :column-num="1" v-for="(item, index) in state.good.list" :key="index" v-if="state.good.list.length>0">
				<div style="background: #f1f5f8;padding: .8rem;font-size: 13px">
					<span>订单号：{{item.orderCode}}</span>
					<span style="color: #79abe7;margin-left: 1rem">{{item.statusDesc}}</span>
				</div>
				<van-grid-item class="text-left" v-for="good in item.details"
						   @click="goto(`/pages/good/detail?skuId=${good.skuId}&spuId=${good.spuId}`)">
					<van-row>
						<van-col span="8" style="position: relative">
							<van-image class="self_center" width="100%" height="100%" lazy-load
								     :src="good.goodsImg" />
						</van-col>
						<van-col span="15" offset="1">

							<p class="ellipsis line_over2 pd-t-10" style="margin-bottom:6px;font-size: 15px">
								{{ good.goodsInfo }}
							</p>
							<div style="line-height: 1.2rem;font-size: 13px">
								<p class="text-s">{{ good.spec }}</p>
								<p class="text-gray "></p>
								<div v-if="false">
									<p class="text-gray " >
										<span style="float: right;color: #545858"> 件数 x{{good.count}}</span>
										<!--<span class="text-gray" :class="{'line-through':!good.salePrice}" >零售价￥{{ good.productPrice }}</span>-->
									</p>
								</div>
								<div v-else>
									<!--<p class="text-gray " v-if="!good.salePrice">-->
										<!--<span style="float: right;color: #545858"> 件数 x{{good.count}}</span>-->
										<!--<span style="color: #ff8467">零售价￥{{ good.productPrice }}</span>-->
									<!--</p>-->
									<p > <span style="float: right;color: #545858" class="text-orange">
										件数 x{{good.count}}</span> <span class="text-orange">￥{{ good.payPrice }}</span></p>
								</div>
								<p class="text-orange" style="color: #ff793e;">
									<span style="float: right;color:#79abe7" v-if="good.deliveryTime==0"> 交货期：现货</span>
									<span style="float: right;color:#79abe7" v-if="good.deliveryTime==1"> 交货期：15天</span>
									<span style="float: right;color:#79abe7" v-if="good.deliveryTime==2"> 交货期：30天</span>
									<span style="float: right;color:#79abe7" v-if="good.deliveryTime==3"> 交货期：45天</span>
									<!--<text v-if="false">-->
										<!--<text class="text-gray line-through" v-if="good.salePrice"> 优惠价￥{{ good.salePrice }}</text>-->
									<!--</text>-->
									<!--<text v-else>-->
										<!--<text v-if="good.salePrice"> ￥{{ good.payPrice }}</text>-->
									<!--</text>-->

								</p>
								<!--<text class="text-orange" v-if="good.actPrice"> 活动价￥{{ good.actPrice }}</text>-->
							</div>
						</van-col>
					</van-row>
				</van-grid-item>
				<van-divider />
				<div style="background: #ffffff;display: flex;width: 100%;justify-content: end;flex-direction: column;text-align: right">
					<p style="text-align: right;margin-right: .5rem;margin-top: .6rem">共计 {{item.total}} 件商品&nbsp&nbsp 合计 <span style="color: #ff7d60">￥:{{item.totalFee}}</span> </p>
					<p style="text-align: right;margin-right: .5rem;margin-bottom: .6rem;margin-top: .6rem">
						<van-button v-if="state.active==1||item.statusDesc== '等待买家付款'" type="primary" style="background: #fe6c31;margin-right: 8px;padding: 0 23px" size="small" @click.stop="onSubmit(item.orderId,item)">付款</van-button>
						<van-button v-if="state.active==2&&item.hasRemindDelivery==0" type="primary" style="background: #fe6c31;margin-right: 8px;padding: 0 10px" size="small" @click.stop="remindDeliverGoods(item.orderId)">提醒发货</van-button>
						<van-button v-if="state.active==2&&item.hasRemindDelivery==1" type="default" style="margin-right: 8px;padding: 0 10px;color:#fe6c31;background: #ffffff;border: 1px solid #fe6c31" size="small" @click.stop="false">已提醒</van-button>
						<van-button v-if="state.active==3||item.statusDesc=='卖家已发货'" type="primary" style="background: #fe6c31;margin-right: 8px;padding: 0 10px" size="small" @click.stop="confirmReceipt(item.orderId)">确认收货</van-button>
						<van-button type="primary" style="background: #fe6c31;padding: 0 10px" size="small" @click.stop="gotoDetails(item)">查看详情</van-button>
					</p>
				</div>
				<van-divider />
			</van-grid>
			<div v-else class="justify-center" style="min-height: calc(100vh - 180px)">
				<van-empty description="您还没有相关订单" >
					<p  class="bottom-button">您可以看看有哪些想买的</p>
				</van-empty>
				<van-button class="text-l" color="linear-gradient(315deg, #FE521F 0%, #FE7902 100%)" round block
						style="width: 240rpx" @tap="goto('/')">
					随便逛逛
				</van-button>
			</div>
		</van-list>
		<view v-if="state.good.fail" class="text-ss text-gray pd-50" @click="failReset">请求失败，点击重试
			<van-icon name="replay" />
		</view>
	</view>
</template>

<script setup lang="ts">
    import api from "@/api";
    import {onMounted, reactive,getCurrentInstance} from 'vue';
    import { Dialog,Toast } from 'vant';
    import toTop from '@/components/tool/toTop.vue';

    const state = reactive({
        skuId: '',
        params: {},
        active: 0,
        good: {
            loading: false,
            finished: false,
            fail: false,
            page: 0,
            list: [] as any
        }
    })
    onMounted(() => {
        state.active = Number(getCurrentInstance().ctx.$page.options.index)
    });
    function is_weixn() {
	  let ua = navigator.userAgent.toLowerCase()
	  if(ua.match(/MicroMessenger/i)=='micromessenger'){
	      return true
	  }else {
	      return false
	  }
    }
    function onSubmit(e,data) {
        if(!data.hasAlipayAccount){
            Toast('商家未绑定支付宝收付款!');
            return
        }
        uni.setStorageSync('payMoney',data.totalFee)
        const isWxjs_environment  = uni.getStorageSync("isWxjs_environment") || false;
        if(isWxjs_environment) {
            window._wx.miniProgram.redirectTo({url: "/pages/pay/pay?orderid="+e+'&wxapplets='+uni.getStorageSync("subdomain")})
        }else {
            orderPay([e])
        }
    }
    function orderPay(idList) {
        api.orderPay(
            {
                "domain": uni.getStorageSync("subdomain"),
                "idList": idList,
            }
        ).then((res: any) => {
            if(is_weixn()){
                Dialog.alert({
                    confirmButtonColor:'rgb(255, 102, 0)',
                    confirmButtonText:'*请复制链接后在浏览器打开',
                    message: res.payUri,
                }).then(() => {
                    let oInput = document.createElement("input");
                    oInput.value = res.payUri;
                    document.body.appendChild(oInput);
                    oInput.select();
                    document.execCommand("Copy");
                    Toast.success("复制成功");
                    oInput.remove();
                });
            }else {
                window.location.href = res.payUri
		}
        })
    }

    function confirmReceipt(e) {
        Dialog.confirm({
            confirmButtonColor: '#ff6800',
            title: '提示',
            message:
                '确认收货？',
        })
            .then(() => {
                let obj = {
                    orderId: e,
                    domain: uni.getStorageSync('subdomain')
                }
                api.confirmReceipt(obj).then((res: any) => {
                    Toast.success(res.message || res.msg)
                })
                onGoodLoad()
            })
            .catch(() => {
                // on cancel
            });
    }

    function gotoDetails(item) {
        let status=0
        if(item.statusDesc =='等待买家付款'){
            status=0
        }else if(item.statusDesc =='买家已付款'||item.statusDesc =='卖家正在备货'){
            status=1
        }else if(item.statusDesc =='卖家已发货'){
            status=2
        }else if(item.statusDesc =='交易成功'){
            status=3
        }else if(item.statusDesc =='交易关闭'){
            status=4
        }
        uni.navigateTo({
            url: `/pages/order/orderDetails?act=${status}&url=${item.orderId}`
        });
    }
    function onClickLeft() {
        uni.navigateTo({
            url: `/pages/index?index=3`
        });
    }
    function goto(url: any) {
        url && uni.navigateTo({url})
    }

    function changeTab(e) {
        state.good.list = []
        state.good.page = 0
        uni.pageScrollTo({
            scrollTop: 0
        });
        onGoodLoad()
    }
    function remindDeliverGoods(orderId) {
        api.remindDeliverGoods({orderId:orderId}).then(res=>{
            state.active=2
            Toast.success('提醒成功')
            onGoodLoad()
        })
    }
    function onGoodLoad() {
        if (state.good.loading || state.good.fail) return
        state.good.loading = true
        ++state.good.page
        api.getOrderList({
            domain:uni.getStorageSync("subdomain"),
            pageNum: state.good.page,
            pageSize: 20,
            type:state.active
        }).then((data: any) => {
            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 failReset() {
        state.good.page -= 1
        state.good.finished = false
        state.good.fail = false
        onGoodLoad()
    }
</script>

<style lang="scss" scoped>
	.sign {
		position: absolute;
		right: 1.8vw;
		top: 0;
		width: 40px;
		text-align: center;

		img {
			width: 40px;
			margin-bottom: -18px;
		}

		.discount {
			font-family: MiSans-Semibold;
			text-shadow: 0.5px 0.5px #ddd;
			color: #A532E0;
			font-weight: 1000;
			font-size: 12px;
		}
	}
	.bottom-button {
		color: #969799;
		font-size: 13px;
		margin-top: -18px;
	}
</style>
