<template>
  <view>
    <view class="common-page">
      <!-- 地址 -->
      <view class="common-card-box yuanjiao24">
        <view class="address-box" @click="selectAddress">
          <view v-if="!mAddress || !mAddress.code" class="address-view">
            <view style="display: flex; align-items: center;">
              <van-image
                  height="36rpx"
                  src="/static/hd-if-b.png"
                  width="36rpx"
              />
              <text class="t1" style="margin-top: 0; margin-left: 20rpx ;font-family: PingFang SC-Medium;">请明确买家信息</text>
            </view>
          </view>
          <view v-if="mAddress && mAddress.code" class="address-view">
            <view style="display: flex; align-items: center;">
              <van-image
                  height="36rpx"
                  src="/static/hd-if-b.png"
                  width="36rpx"
              />
              <view   style="margin-top: 0; margin-left: 34rpx ;font-family: PingFang SC-Medium;">
                <view class="t1" space="ensp">
                  {{ mAddress.name }} {{ mAddress.phone }}
                </view>
                <br />
                <view class="t2" space="emsp">
                  {{ mAddress.province }} {{ mAddress.city }}{{ mAddress.area }}{{ mAddress.address }}
                </view>
              </view>
            </view>
          </view>
          <u-icon name="arrow-right" color="#AEAEAE" size="34rpx"></u-icon>
        </view>
      </view>
      <!-- 已选商品 -->
      <view class="common-card-box yuanjiao24">
        <view class="goods-list display-flex-center" v-for="(item, index) in goodsList" :key="index">
          <image style="width: 155rpx; height: 155rpx; border-radius: 10rpx;margin-right: 30rpx;flex-shrink: 0;"
                 :src="item.goods_cover" mode="aspectFill">
          </image>
          <view style="width: 100%;">
            <view class="display-flex-between ">
              <text class="goods-name">{{item.goods_name}}</text>
            </view>
            <view class="display-flex-between " style="margin-top: 30rpx">
              <text class="goods-price">￥<text style="font-family: D-DIN-Bold;font-weight: 700;   font-size: 36rpx;">{{item.price_selling}}</text></text>
            </view>
          </view>
        </view>
      </view>
      <!-- 留言 -->
      <view class="common-card good-card yuanjiao24">
        <view class="fs14 mb10 good-card-text"> <view style="width: 6rpx;height: 28rpx;background: #C29556;border-radius: 0rpx 0rpx 0rpx 0rpx;margin-right: 20rpx"></view>留言</view>
        <u--textarea height="176rpx" v-model="order_remark" placeholder="请输入(100字以内)"    class="custom-textarea" maxlength="100" count></u--textarea>
      </view>
      <van-toast id="van-toast"/>

    </view>
    <view class="bottom-navigation">
      <view class="bottom-navigation-div">
        <span>应付:<span  class="space" >￥<span>{{payTotal}}</span></span></span>
      </view>
      <button  class="course-button" @click="toPay">去支付</button>
    </view>
  </view>
</template>

<script>
	import couponItem from '@/subPages/coupon/couponItem.vue'
	export default {
		components: { couponItem },
		data() {
			return {
				orderNo: '',
				pageOptions: {},
				showCoupon: false,
				couponList: [],

				mAddress: {},
				usePoints: [],
				order_remark: '',
				checkedCoupon: {},
				goodsList: [],
				orderData: { amount_goods: 0, amount_express: 0 },
				cartIds: [],
				pointsData: {},
				pointsShowData: { price: 0, points: 0 },
				usePointsFlag: true,
			}
		},
		computed: {
			payTotal() {
				const { amount_goods = 0, amount_express = 0 } = this.orderData
				let result = Number(amount_goods) + Number(amount_express)
				if (this.checkedCoupon.coupon_id) {
					result = result - Number(this.checkedCoupon.coupon_price)
				}
				if (this.integral == 1) {
					result = result - Number(this.pointsShowData.price)
				}
				return result.toFixed(2)
			},

			userPoints() {
				const { integral_total = 0, integral_used = 0 } = JSON.parse(uni.getStorageSync('userInfo')||"{}");
				return integral_total - integral_used
			},
			pointsDisabled() {
				const { min_money, ratio, to_money } = this.pointsData
				return min_money > this.orderData.amount_goods
			},

		},

		onLoad(options) {
			this.orderNo = options.orderNo
			this.pageOptions = options
			// const mData = uni.getStorageSync('selectTaskData') || undefined
		},
		onShow() {
			const { type } = this.pageOptions
			// this.getPoints()
			if (type == 'cart') {
				// 购物车下单
				this.getCartData()
				const selectAddress = uni.getStorageSync('selectAddress') || undefined
				if (selectAddress) {
					const tempAddress = JSON.parse(selectAddress)
					if (!this.mAddress.code || (this.mAddress && this.mAddress.code != tempAddress.code)) {
						this.mAddress = tempAddress
						this.getExpressFee()
					}
					uni.removeStorageSync('selectAddress')
				}
			} else {
				this.getOrderDetail()
			}
		},
		methods: {

			getCartData() {
				this.cartIds = this.pageOptions.ids.split('_')
				this.$api.createPrevOrderByCart({ id: this.cartIds }).then(res => {
					const { items, coupons, count_total, amount_total, integral = {} } = res.data
					this.goodsList = items.map(item => {
						const { goods_spec, price_selling } = item.sku
						item.stock_sales = item.num
						item = {
							goods_spec,
							price_selling,
							...item
						}
						return item
					})
					this.couponList = coupons
					// 计算付款信息等
					this.orderData.number_goods = count_total
					this.orderData.amount_goods = amount_total
					// const  {min_money, ratio, to_money} = integral
					// let points = Math.floor(amount_total * ratio / 100)
					// points = this.userPoints > points ? points : this.usePoints
					if (res.data.integral_use && res.data.integral_price) {
						this.usePointsFlag = true
						this.pointsShowData = {
							points: res.data.integral_use,
							price: (res.data.integral_price).toFixed(2)
						}
					} else {
						this.usePointsFlag = false
					}
				})
			},
			getExpressFee() {
				this.$api.getPrevCartExpress({ id: this.cartIds, addr_code: this.mAddress.code }).then(res => {
					this.orderData.amount_express = res.data
				})
			},
			toPay() {
				if (!this.mAddress.code) {
					uni.showToast({
						title: '请选择收货地址'
					})
					return
				}
				if (this.pageOptions.type == 'cart') {
					const sendData = {
						id: this.cartIds,
						addr_code: this.mAddress.code,
						coupon_id: this.checkedCoupon.id,
						order_remark: this.order_remark,
						integral: this.integral
					}
					this.$api.createOrderByCart(sendData).then(res => {
						const { appId, nonceStr, paySign, signType, timeStamp } = res.data.param
						uni.requestPayment({
							provider: 'wxpay',
							nonceStr,
							package: res.data.param.package,
							paySign,
							signType,
							timeStamp,
							success: function(success) {
								uni.navigateTo({ url: `/subPages/paySuccess/payCourseSuccess?orderNo=${res.data.order.order_no}` })
							},
							fail: function(err) {
								uni.navigateTo({ url: `/subPages/orderDetail/orderDetail?orderNo=${res.data.order.order_no}` })
							}
						})
					})
				} else {

          // uni.navigateTo({ url: `/subPages/paySuccess/payCourseSuccess?orderNo=${this.orderNo}` })
					// 获取支付参数
					this.$toWechatPay(this.orderNo, this.order_remark,2)
				}
			},
			addressConfirm() {
				// 选择地址确认
				this.$api.submitOrderByAdress({ order_no: this.orderNo, code: this.mAddress.code }).then(res => {
					this.orderData.amount_express = res.data.amount
				})
			},
			getOrderDetail() {
				this.$api.orderDetail({ order_no: this.orderNo }).then(res => {
					this.goodsList = res.data.items || []
					this.orderData = res.data
					this.checkedCoupon = res.data.coupon || {}
					if (res.data.addr_code) {
						// 已选地址
						const {
							address_area,
							address_city,
							address_province,
							address_content,
							address_name,
							address_phone
						} = res.data.truck || {}
						this.mAddress = {
							code: res.data.addr_code,
							area: address_area,
							city: address_city,
							province: address_province,
							address: address_content,
							name: address_name,
							phone: address_phone
						}
					}
					const selectAddress = uni.getStorageSync('selectAddress') || undefined
					if (selectAddress) {
						const tempAddress = JSON.parse(selectAddress)
						if (!this.mAddress.code || (this.mAddress && this.mAddress.code != tempAddress.code)) {
							console.log(99999)
							this.mAddress = tempAddress
							this.addressConfirm()
						}
						// this.mAddress = tempAddress
						console.log(23333, this.mAddress);
						uni.removeStorageSync('selectAddress')
					}
				})
			},
			selectAddress() {
				uni.navigateTo({
					url: '/subPages/addressMg/addressMg?isBack=true'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.coupon-list {
		padding: 40rpx 20rpx;
	}

	.common-page {
		height: 100vh;
		overflow-y: auto;
		padding: 20rpx;
		color: #2C2C2C;
		padding-bottom: 188rpx;
		box-sizing: border-box;
	}

	.good-card {
		padding: 30rpx 20rpx 20rpx 20rpx;
		color: #7A7A7A;

    &-text{
      display: flex;
      align-items: center;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 28rpx;
      color: #333333;
      line-height: 40rpx;
      text-align: left;
      font-style: normal;
      text-transform: none;
      // 加粗
      font-weight: bold;
    }
		::v-deep {
			.u-textarea {
				background: #F6F6F6;
        border-radius: 24rpx 24rpx 24rpx 24rpx!important;
				border: none;
				padding: 18rpx;

				.u-textarea__count {
					background-color: transparent !important;
				}
			}
		}
	}

	.goods-list {
		margin: 0 30rpx;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #F5F5F5;
    .goods-name{
      font-family: PingFang SC-Bold;
      font-weight: 400;
      font-size: 28rpx;
      color: #333333;
      line-height: 40rpx;
      text-align: left;
      font-style: normal;
      text-transform: none;
      // 加粗
      font-weight: bold;
    }
    .goods-price{
      font-family: D-DIN-Regular;
      font-weight: 400;
      font-size: 24rpx;
      color: #333333;
      line-height: 30rpx;
      text-align: left;
      font-style: normal;
      text-transform: none;
    }
	}

	.goods-total {
		justify-content: flex-end;
		margin: 27rpx 20rpx;
	}


	.address-box {
		// width: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 30rpx 22rpx;
		.address-view {
			flex: 1;
			display: flex;
			flex-direction: column;

      .t1 {
        font-size: 28rpx;
        margin-top: 10rpx;
        font-family: PingFang SC-Medium, PingFang SC;
        font-weight: 400;
        color: #333333;
      }

      .t2 {
        font-size: 28rpx;
        font-family: PingFang SC-Heavy, PingFang SC;
        font-weight: 600;
        color: #333333;
        margin-top: 20rpx;
      }
		}
	}
  .bottom-navigation{
    position: fixed;
    // 文字垂直居中
    display: flex;
    align-items: center;
    justify-content: center;
    bottom: 0;
    height: 100rpx;
    width: calc(100% - 40rpx);
    background: #FFFFFF;
    box-shadow: 0rpx -2rpx 0rpx 0rpx #F1F3F6;
    border-radius: 24rpx 24rpx 0rpx 0rpx;
    border: 0rpx solid #979797;
    padding: 20rpx 20rpx 68rpx 20rpx ;
    &-div{
      height: 76rpx;
      width: 404rpx;
      // 文字垂直居中
      display: flex;
      align-items: center;
      padding-left: 30rpx;
      span{
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 28rpx;
        color: #333333;
        line-height: 40rpx;
        text-align: left;
        font-style: normal;
        text-transform: none;
        span{
          font-family: D-DIN-Regular;
          font-size: 24rpx;
          color: #C29556;
          span{
            font-family: D-DIN-Bold;
            font-size: 40rpx;
          }
        }
      }

    }

    .course-button {
      width: 264rpx;
      height: 80rpx;
      background: linear-gradient(315deg, #CA9359 0%, #E2B98E 100%);
      border-radius: 292rpx 292rpx 292rpx 292rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 28rpx;
      color: #FFFFFF;
      line-height: 36rpx;
      text-align: center;
      font-style: normal;
      text-transform: none;
      // 文字垂直居中
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .yuanjiao24{
    border-radius: 24rpx 24rpx 24rpx 24rpx!important;
  }
  .space::before {
    content: '\00A0'; /* 这是 &nbsp; 的 Unicode 码 */
  }
</style>
