<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>
	<div class="border_address"></div>
	<van-row style="background: #ffffff;" @click="gotoAddress">
		<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.addressObj.receiverName}} {{that.addressObj.phone}}</p>
				<p>收货地址：{{that.addressObj.region}} {{that.addressObj.detailAddress}}</p>
			</div>
		</van-col>
	</van-row>
	<div class="border_address"></div>
	<div style="background: #ffffff;font-size: 13px;text-align: left;padding: .8rem;margin-top: 1rem">
		<h3>商品信息&nbsp<span style="font-size: 12px;color: #d1d2d3;margin-right: 3px">|&nbsp您要结算的商品</span></h3>
	</div>
	<div v-for="item in that.cartList">
		<div v-for="(good,index) in item.orderDetails" :key="index">
			<van-grid :center="false" :column-num="1">
				<van-grid-item class="text-left">
					<van-row>
						<van-col span="8" style="position: relative">
							<van-image class="self_center" width="100%" height="100%" lazy-load
								     :src="good.goodsImg" />
							<!--结算页活动角标-->
							<div class="sign" v-if="good.subScriptImgUrl">
							<img :src="good.subScriptImgUrl" alt="" />
							<div class="discount" style="color: rgba(247, 103, 67, 1)">{{good.discount}}</div>
							</div>
							<view style="position: absolute;left: 0;bottom: 0;" v-if="good.conner.dailyIcons[0]">
								<span style="margin-right: 5px" v-for="item in good.conner.dailyIcons">
									<van-image    width="60rpx" height="32rpx" :src="item" />
								</span>
							</view>
						</van-col>

						<van-col span="15" offset="1">
							<p class="text-l ellipsis line_over2" style="height: 80rpx;">
								{{good.goodsInfo}}
							</p>
							<div style="line-height: 1.2rem">
								<p class="text-s">规格：{{good.spec}}</p>
								<p class="text-gray text-s" style="color: #5392e2">
									交货期：{{good.deliveryDateStatusMsg}}</p>

								<p v-if="good.actPrice"  class="text-gray text-s"
								   :class="{'line-through':!good.salePrice}"
								>
									<span style="float: right;color: #414141"> 件数：x {{good.count}}</span>
									零售价￥{{good.productPrice}}</p>
								<p v-else class="text-s"
								   :class="{'line-through':good.salePrice,'text-orange':!good.salePrice,'text-gray':good.salePrice}">
									<span style="float: right;color: #666666"> 件数：x {{good.count}}</span>
									零售价￥{{good.productPrice}}</p>
								<div v-if="good.actPrice">
									<p class="text-gray text-s line-through" style="margin-top: .3rem"
									   v-if="good.salePrice">优惠价￥<text class="text-bold text-l">{{good.salePrice}}</text>
									</p>
								</div>
								<div v-else>
									<p class="text-orange text-s" style="margin-top: .3rem"
									   v-if="good.salePrice">优惠价￥<text class="text-bold text-l">{{good.salePrice}}</text>
									</p>
								</div>
								<p class="text-orange text-s" style="margin-top: .3rem" v-if="good.actPrice"
								   >活动价￥<text class="text-bold text-l">{{good.actPrice}}</text>
								</p>
							</div>
						</van-col>
					</van-row>
				</van-grid-item>
				<van-divider />
			</van-grid>
			<van-field
					  rows="1"
					  v-model="good.remark"
					  readonly
					  autosize
					  label="商品备注："
					  type="textarea"
			>
				<template #button>
					<van-icon name="records" size="20"
						    @click="that.temIndexRemark=index,showRemark(true,good.remark)" />
				</template>
			</van-field>
		</div>
	</div>
	<van-field
			  v-model="that.params.orderRemarks"
			  readonly
			  rows="1"
			  autosize
			  label="订单备注："
			  type="textarea"
			  style="margin-top: 10px"
	>
		<template #button>
			<van-icon name="records" size="20"  @click="showRemark(false,that.params.orderRemarks)" />
		</template>
	</van-field>
	<div style="background: #ffffff;font-size: 13px;text-align: left;padding: .8rem;padding-bottom: 80px">
		<h3>支付方式&nbsp<span style="font-size: 12px;color: #d1d2d3;margin-right: 3px">|&nbsp您要结算的商品</span></h3>
		<van-divider />
		<div>
			<van-radio-group v-model="that.checked">
				<van-radio name="1"><p style="font-size: 14px"> {{that.payType}}支付（强烈推荐）</p>
					<p style="color: #b8b8b8">使用{{that.payType}}担保交易，保障双方利益。</p></van-radio>
			</van-radio-group>
		</div>
	</div>
	<van-dialog confirmButtonColor="#ff6800" v-model:show="that.show" :title="`${that.isGood?'商品':'订单'}备注`"
			show-cancel-button @confirm="saveRemark">
		<van-cell-group inset>
			<van-field
					  v-model="that.temRemarks"
					  rows="2"
					  autosize
					  type="textarea"
					  maxlength="120"
					  :placeholder="`请输入${that.isGood?'商品':'订单'}备注...`"
					  show-word-limit
			/>
		</van-cell-group>
	</van-dialog>
	<van-submit-bar :price="that.totalOrderMoney*100" button-text="提交订单" button-color="#ff6600"
			    :loading="that.loading" @submit="onSubmit">
		<template #default>
			<span style="float: right">总共：{{that.total}}件商品</span>
		</template>
	</van-submit-bar>
	<van-overlay :show="that.phoneShow"  z-index="999">
		<div style="text-align: center;position: absolute;bottom: 10px;width: 94%;padding-left: 3%;">
			<div class="block" @click.stop style="color: #0099ff">
				<van-icon name="phone-o" size="24" style="color: #999999;margin-top: 3px;margin-right: 10px" />
				呼叫 <a style="color:#0099ff " href="tel:13148528214">{{that.cartList[0].businessPhone}}</a>
			</div>
			<div class="block" @click="that.phoneShow = false" style="margin-top: 10px">
				取消
			</div>
		</div>
	</van-overlay>
	<van-popup v-model:show="that.popupAddress" position="right"
		     :style="{ width: '100%', height: '100%' }">
		<address-component :addrId="that.addressObj.addrId" @change="onAddressChange"
					 @cancel="that.popupAddress = false" />
	</van-popup>
</template>

<script setup lang="ts">
    import api from "@/api";
    import AddressComponent from '@/pages/my/address.vue'
    import {log} from 'console';
    import {Dialog, SubmitBar, Toast} from 'vant';
    import {onMounted, reactive, getCurrentInstance} from 'vue';

    const that = reactive({
        payType:'',
        total: 0,
        totalOrderMoney: 0,
        temIndexRemark: 0,
        cartList: [],
        phoneShow: false,
        loading: false,
        isGood: false,
        temRemarks: '',
        checked: '1',
        show: false,
        actIndex: 4,
        params: {
            goodRemarks: '',
            orderRemarks: ''
        },
        addressObj: {},
        good: {
            loading: false,
            finished: false,
            fail: false,
            page: 0,
            list: [] as any
        },
        popupAddress: false
    })
    onMounted(() => {
        that.payType=window.__wxjs_environment === 'miniprogram'?'微信':'支付宝'
        let carts = getCurrentInstance().ctx.$page.options || ''
        settleInfo(JSON.parse(decodeURIComponent(carts.list)))
        receiveList()
    });

    function receiveList() {
        api.receiveList().then((data: any) => {
            if(data.list){
                that.addressObj = data.list[0]||{}
		}
        }).finally(() => {
        })
    }

    function settleInfo(carts) {
        api.settleInfo(
            {
                "carts": carts,
                "domain": uni.getStorageSync("subdomain")
            }
        ).then((res: any) => {
            that.total = res.total
            that.totalOrderMoney = res.totalOrderMoney
            that.cartList = res.orderList
        })
    }

    function orderAdd(carList) {
        api.orderAdd(
            {
                "addressId": that.addressObj.addrId,
                "carts": carList,
                "domain": uni.getStorageSync("subdomain")
            }
        ).then((res: any) => {
            let idList = []
            res.orderList.forEach(item => {
                idList.push(item.orderId)
            })
            const isWxjs_environment  = uni.getStorageSync("isWxjs_environment") || false;
            if(isWxjs_environment) {
                window._wx.miniProgram.redirectTo({url: "/pages/pay/pay?orderid="+idList[0]})
            }else {
                orderPay(idList)
		}
        })
    }

    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 is_weixn() {
        let ua = navigator.userAgent.toLowerCase()
        if(ua.match(/MicroMessenger/i)=='micromessenger'){
            return true
        }else {
            return false
        }
    }
    function onSubmit() {
        if(!that.cartList[0].hasAlipayAccount){
            Dialog.confirm({
                title: '提示',
                confirmButtonText:'马上联系',
                cancelButtonText:'稍等一会',
                confirmButtonColor: '#ff6800',
                message:
                    '商家未绑定支付宝收付款，无法提交订单，马上联系商家？',
            })
                .then(() => {
                    that.phoneShow=true
                })
                .catch(() => {
                    // on cancel
                });
            return;
	  }
        uni.setStorageSync('payMoney',that.totalOrderMoney)
        let carList = []
        that.cartList[0].orderDetails.forEach(item => {
            carList.push(
                {
                    "cartId": item.cartId,
                    "count": item.count,
                    "orderRemark": that.params.orderRemarks,
                    "remark": item.remark,
                    "skuId": item.skuId
                }
            )
        })
        orderAdd(carList)
    }

    function showRemark(isGood, e) {
        if (isGood) {
            that.isGood = true
        } else {
            that.isGood = false
        }
        that.temRemarks = e
        that.show = true
    }

    function saveRemark() {
        if (that.isGood) {
            that.cartList[0].orderDetails[that.temIndexRemark].remark = that.temRemarks
        } else {
            that.params.orderRemarks = that.temRemarks
        }
    }

    function sure() {
        Dialog.confirm({
            title: '提示',
            confirmButtonColor: '#ff6800',
            message:
                '确认收货',
        })
            .then(() => {
                // on confirm
            })
            .catch(() => {
                // on cancel
            });
    }

    function gotoAddress() {
        that.popupAddress = true
    }

    function onceBuy() {
        Dialog.confirm({
            title: '提示',
            confirmButtonColor: '#ff6800',
            message:
                '是否添加到购物车？',
        })
            .then(() => {
                // on confirm
            })
            .catch(() => {
                // on cancel
            });
    }

    function onClickLeft() {
        history.back()
    }

    function onAddressChange(item: any) {
        // Toast('返回参数见console')
        // console.log('提示：<address-component/>组件调用那里传一个addrId给我', item)
        // console.log('地址信息', item)
        that.addressObj = item
        that.popupAddress = false
    }
</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;
	}
	}
	.block {
		border-radius: 3px;
		color: #52b4ff;
		height: 50px;
		line-height: 50px;
		background-color: #fff;
	}

	.pro_account {
		display: inline-block;
		border-left: 2px solid #f1f5f8;
		height: 0.3rem;
		line-height: .3rem;
		font-size: .14rem;
		color: #bbb;
		margin-top: 0.15rem;
		margin-left: 0.2rem;
		text-indent: 0.2rem;
	}

	.border_address {
		border: 1px solid;
		border-image-source: linear-gradient(to right, #f8e07e, #f88f7e);
		border-image-slice: 1;
	}
</style>