<template>
	<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-sticky>
	<van-row style="background: #fe9400;height: 5rem">
		<van-col span="13">
			<div style="text-align: center;margin-top: 1rem;color: #ffffff">
				<div v-if="that.actIndex==0">
					<p style="font-size: 1rem">等待买家付款</p>
					<p>{{formatDuring(that.orderDesc.notPayDownTime)}} 自动关闭</p>
				</div>
				<div v-if="that.actIndex==1">
					<p style="font-size: 1rem">买家已付款</p>
					<p>卖家正在组织发货</p>
				</div>
				<div v-if="that.actIndex==2">
					<p style="font-size: 1rem">卖家已发货</p>
					<p>{{formatTow(that.orderDesc.confirmReceiptDownTime)}}自动确认</p>
				</div>
				<div v-if="that.actIndex==3">
					<p style="font-size: 1em;margin-top: 1.8rem">交易成功</p>
				</div>
				<div v-if="that.actIndex==4">
					<p style="font-size: 1rem">交易已关闭</p>
					<p>系统自动关闭</p>
				</div>
			</div>
		</van-col>
		<van-col span="11" style="text-align: center">
			<img v-if="that.actIndex==0"  style="width: 5.5rem;margin-top: .4rem"  src="../../static/img/daifukuang.jpg" alt="">
			<img v-if="that.actIndex==1"  style="width: 5.5rem;margin-top: .4rem"  src="../../static/img/daifahuo.jpg" alt="">
			<img v-if="that.actIndex==2"  style="width: 5.5rem;margin-top: .2rem"  src="../../static/img/yifahuo.jpg" alt="">
			<img v-if="that.actIndex==3"  style="width: 5.5rem;margin-top: .6rem"  src="../../static/img/jiaoyichenggong.jpg" alt="">
			<img v-if="that.actIndex==4"  style="width:5rem;margin-top: .1rem"  src="../../static/img/yiguanbi.jpg" alt="">
		</van-col>
	</van-row>
	<van-row style="background: #ffffff;">
		<van-col span="3">
			<img style="width: 1.4rem;margin-left: .5rem;margin-top: 45%"  src="../../static/img/sub_address.png" alt="">
		</van-col>
		<van-col span="18">
			<div style="text-align: left;margin: 1rem auto">
				<p >收货人：{{that.orderDesc.receiver}}    {{that.orderDesc.phone}}</p>
				<p>收货地址：{{that.orderDesc.address}} </p>
			</div>
		</van-col>
	</van-row>
	<div class="border_address"></div>
	<van-row style="background: #ffffff;margin-top: .5rem">
		<van-cell :title="that.orderDesc.storeName" icon="shop-o" is-link @click="goto('/')">
		</van-cell>
		<van-divider />
	</van-row>
	<van-grid :center="false" :column-num="1" v-for="params in that.params">
		<!--@click="goto(`/pages/good/detail?skuId`)"-->
		<van-grid-item class="text-left" @click.native="goto(`/pages/good/detail?skuId=${params.skuId}&spuId=${params.spuId}`)"
		>
			<van-row>
				<van-col span="8" style="position: relative">
					<van-image class="self_center" width="100%"  lazy-load
						     :src="params.imgPath" />
					<!--订单详情活动角标-->
					<div class="sign" v-if="params.subScriptImgUrl">
						<img :src="params.subScriptImgUrl" alt="" />
						<div class="discount" style="color: rgba(247, 103, 67, 1)">{{params.discount}}</div>
					</div>
					<van-image :key="index" v-for="(item,index) in params.dailyIcons" :style="{left:index*68+'rpx'}" :src="item" style="position: absolute;bottom: 0" width="60rpx" />
				</van-col>
				<van-col span="15" offset="1">
					<p class="text-l ellipsis line_over2" style="height: 80rpx;">
						{{params.title}}
					</p>
					<div style="line-height: 1.2rem">
						<p class="text-s">规格：{{params.size}}</p>
						<p class="text-gray text-s" v-if="params.deliveryTime==0">交货期：现货</p>
						<p class="text-gray text-s" v-if="params.deliveryTime==1">交货期：15天</p>
						<p class="text-gray text-s" v-if="params.deliveryTime==2">交货期：30天</p>
						<p class="text-gray text-s" v-if="params.deliveryTime==2">交货期：45天</p>
						<div v-if="false">
							<p class="text-gray text-s" v-if="params.salePrice">
								<span style="float: right;color: #414141;margin-right: 5px"> 件数：x {{params.count}}</span>
								零售价￥{{params.productPrice}}</p>
							<p class="text-gray text-s " v-else>
								<span style="float: right;color: #414141"> 件数：x {{params.count}}</span>
								<span :class="{'line-through':params.actPrice}" >零售价￥{{params.productPrice}}</span></p>
							<div class="text-orange text-s">
								<van-button v-if="that.actIndex!=0&&that.actIndex!=4" type="default" style="float: right;background: #f7f7f7;padding: 12px" size="small" @click.stop="afterSales">申请售后</van-button>

								<text  class="text-gray text-s line-through" v-if="params.salePrice">优惠价￥{{params.salePrice}}</text>
								<text  class="text-gray text-s line-through" v-else></text>
								<p  style="font-size: 13px;color: #ff793e" v-if="params.actPrice">活动价￥{{params.actPrice}}</p>
							</div>
						</div>
						<div v-else>
							<!--<p class="text-gray text-s line-through" v-if="params.salePrice">-->
								<!--<span style="float: right;color: #414141;margin-right: 5px"> 件数：x {{params.count}}</span>-->
								<!--零售价￥{{params.productPrice}}</p>-->
							<p class="text-gray text-s ">
								<span style="float: right;color: #414141"> 件数：x {{params.count}}</span>
								<span style="color: #ff8467">￥{{params.payPrice}}</span></p>
							<p class="text-orange text-s" style="margin-top: .3rem">
								<van-button v-if="that.actIndex!=0&&that.actIndex!=4" type="default" style="float: right;background: #f7f7f7;padding: 12px" size="small" @click.stop="afterSales">申请售后</van-button>

								<!--<text  style="font-size: 13px;color: #ff793e" v-if="params.salePrice">优惠价￥{{params.salePrice}}</text>-->
							</p>
						</div>
					</div>
				</van-col>
			</van-row>
		</van-grid-item>
		<van-divider />
		<van-field   v-model="params.remark" readonly
				 label="商品备注："
		/>
		<van-divider />

	</van-grid>
	<div style="padding-bottom: 10rem;">
		<div style="text-align: right;padding: .6rem;background: #ffffff;">共计 {{that.orderDesc.total}} 件商品&nbsp&nbsp 合计 <span style="color: #ff7d60">￥:{{that.orderDesc.totalFee}}</span> </div>
		<div  style="width: 100%">
			<van-field  style="margin-top: .6rem" v-model="that.orderDesc.remark" readonly
					label="订单备注："
			/>
			<van-field  style="margin-top: .6rem" readonly  v-model="that.orderDesc.payTypeDesc"
					label="支付方式："
			/>
			<van-field  style="margin-top: .6rem" readonly v-model="that.orderDesc.orderCode"
					label="订单编号："
			/>
			<van-field  readonly  v-model="that.orderDesc.addDate"
					label="创建时间："
			/>
			<van-field  v-if="that.actIndex==2||that.actIndex==1||that.actIndex==3" readonly  v-model="that.orderDesc.onlinePayDate"
					label="付款时间："
			/>
			<van-field  v-if="that.actIndex==2||that.actIndex==3" readonly v-model="that.orderDesc.confirmDate"
					label="确认时间："
			/>
			<van-field  v-if="that.actIndex==2||that.actIndex==3" readonly v-model="that.orderDesc.deliveryDate"
					label="发货时间："
			/>
			<van-field   v-if="that.actIndex==3" readonly v-model="that.orderDesc.completionDate"
					 label="成交时间："
			/>
			<van-field  v-if="that.actIndex==4" readonly  v-model="that.orderDesc.cancelDate"
					label="取消时间："
			/>
		</div>
	</div>
	<van-action-bar v-if="that.actIndex==0" class="sh-t">
		<van-action-bar-button @click="cancel"  style="background: #ebebeb"  text="取消订单" />
		<van-action-bar-button @click="onSubmit"  style="background: #ff6a00;color: #ffffff"  text="付款" />
	</van-action-bar>
	<van-action-bar v-if="that.actIndex==2" class="sh-t">
		<van-action-bar-button   style="background: #ff6a00;color: #ffffff"   @click="sure" text="确认收货" />
	</van-action-bar>
	<van-action-bar v-if="that.actIndex==3" class="sh-t">
		<van-action-bar-button style="background: #ff6a00;color: #ffffff"   @click="onceBuy" text="再买" />
	</van-action-bar>
	<van-action-bar v-if="that.actIndex==4" class="sh-t">
		<van-action-bar-button style="background: #ff6a00;color: #ffffff"   @click="onceBuy" text="重新买" />
	</van-action-bar>
</template>

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

    const that = reactive({
        orderDesc:{},
        actIndex:0,
        params: [],
        good: {
            loading: false,
            finished: false,
            fail: false,
            page: 0,
            list: [] as any,
        },
        temOrderId:'',
    })
    onMounted(() => {
        that.actIndex = getCurrentInstance().ctx.$page.options.act
        that.temOrderId=getCurrentInstance().ctx.$page.options.url
        getOrderDetail()
    })
    onUnmounted(()=>{
        clearInterval(that.time)
    })
    // 待付款定时器
    function ding() {
        if(that.orderDesc.notPayDownTime>0){
            that.time = setInterval(() => {
                that.orderDesc.notPayDownTime--
                if (that.orderDesc.notPayDownTime < 0) {
                    clearInterval(that.time)
                }
            }, 1000)
        }
    }
    // 待付款定时器
    function ding2() {
        if(that.orderDesc.confirmReceiptDownTime>0){
            that.time = setInterval(() => {
                that.orderDesc.confirmReceiptDownTime--
                if (that.orderDesc.confirmReceiptDownTime < 0) {
                    clearInterval(that.time)
                }
            }, 1000)
        }
    }
    function onSubmit() {
        if(!that.orderDesc.hasAlipayAccount){
            Toast('商家未绑定支付宝收付款!');
            return
        }
        uni.setStorageSync('payMoney',that.orderDesc.totalFee)
        if(window.__wxjs_environment === 'miniprogram'){
            window._wx.miniProgram.redirectTo({url: "/pages/pay/pay?orderid="+[that.orderDesc.orderId]})
        }else {
            orderPay([that.orderDesc.orderId])
        }
    }
    function orderPay(idList) {
        api.orderPay(
            {
                "domain": uni.getStorageSync("subdomain"),
                "idList": idList,
            }
        ).then((res: any) => {
            window.location.href = res.payUri
        })
    }
    function goto(url: any) {
        url && uni.navigateTo({ url })
    }
    function cancel() {
        Dialog.confirm({
            title: '提示',
            confirmButtonColor:'#ff6800',
            message:
                '确认要取消订单？',
        })
            .then(() => {
                api.orderCancel(that.orderDesc.orderId).then((res)=>{
                    Toast.success(res);
                    goto(`/pages/order/orderList?index=0`)
                })
            })
            .catch(() => {
                // on cancel
            });
    }
    function formatTow(value) {
        var theTime = parseInt(value);// 需要转换的时间秒
        var theTime1 = 0;// 分
        var theTime2 = 0;// 小时
        var theTime3 = 0;// 天
        if(theTime > 60) {
            theTime1 = parseInt(theTime/60);
            theTime = parseInt(theTime%60);
            if(theTime1 > 60) {
                theTime2 = parseInt(theTime1/60);
                theTime1 = parseInt(theTime1%60);
                if(theTime2 > 24){
                    //大于24小时
                    theTime3 = parseInt(theTime2/24);
                    theTime2 = parseInt(theTime2%24);
                }
            }
        }
        var result = '';
        if(theTime > 0){
            result = ""+parseInt(theTime)+"秒";
        }
        if(theTime1 > 0) {
            result = ""+parseInt(theTime1)+"分"+result;
        }
        if(theTime2 > 0) {
            result = ""+parseInt(theTime2)+"小时"+result;
        }
        if(theTime3 > 0) {
            result = ""+parseInt(theTime3)+"天"+result;
        }
        return result;
    }

    function formatDuring(s) {
        var t = '';
        if (s > -1) {
            var hour = Math.floor(s / 3600)
            var min = Math.floor(s / 60) % 60
            var sec = s % 60
            if (hour < 10) {
                t = '0' + hour + "小时"
            } else {
                t = hour + "小时"
            }
            if (min < 10) {
                t += "0"
            }
            t += min + "分钟"
            if (sec < 10) {
                t += "0"
            }
            t += sec.toFixed(0)+'秒'
        }
        return t
    }
    function getOrderDetail() {
        api.getOrderDetail(that.temOrderId).then((res: any) => {
            that.orderDesc=res
            that.params=res.details
            if(res.notPayDownTime>0){
                ding()
            }
            if(res.confirmReceiptDownTime>0){
                ding2()
            }
        })
    }
    function afterSales() {
        uni.navigateTo({
            url: `/pages/order/afterSales`,
        });
    }
    function sure() {
        Dialog.confirm({
            title: '提示',
            confirmButtonColor:'#ff6800',
            message:
                '确认收货',
        })
            .then(() => {
                let obj = {
                    orderId: that.orderDesc.orderId,
                    domain: uni.getStorageSync('subdomain')
                }
                api.confirmReceipt(obj).then((res: any) => {
                    Toast.success('成功')
                    goto(`/pages/order/orderList?index=0`)
                })
            })
            .catch(() => {
                // on cancel
            });
    }

    function onceBuy() {
        let isBrandAgent = that.params.every(item => {
            return item.isBrandAgent
        })
        if (isBrandAgent) {
            let arr = []
            that.params.forEach(item => {
                arr.push(
                    {
                        "skuId": item.skuId,
                        "link": uni.getStorageSync("subdomain"),
                        "productQty": item.count
                    }
                )
            })
            api.batchAdd(arr).then(res => {
                uni.navigateTo({ url:`/?index=2` })
            })
        } else {
            Toast.fail('商家未代理该品牌');
        }
    }
    function onClickLeft() {
        history.back()
    }
</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;
		}
	}
	.sd{
		font-size: 30px;
	}
	.border_address{
		border: 2px solid;
		border-image-source: linear-gradient(to right, #fd942c, #f5180b);
		border-image-slice: 1;
	}
</style>