<template>
  <view class="common-page">
    <!-- 地址选择区域，点击可触发地址选择 -->
    <view class="common-card-box">
      <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">
      <view class="goods-list display-flex-center" v-for="(item, index) in goodsList" :key="index">
        <!-- 商品图片 -->
        <image class="mr20" style="width: 176rpx; height: 176rpx; border-radius: 12rpx;flex-shrink: 0;"
               :src="item.goods_cover" mode="aspectFill">
        </image>
        <!-- 商品名称、规格和数量 -->
        <view class="list-info">
          <view class="fs14 fw400 color-333">{{item.goods_name}}</view>
          <view class="fw400 color-888 fs12 mt8 mb8">{{item.sku.goods_spec}}</view>
          <view class="display-flex-between">
            <text class="fw400 color-888  fs12 mb8">￥<text class="fw700 color-333  fs16 mb8">{{item.price_selling}}</text></text>
            <text>×{{ item.stock_sales }}</text>
          </view>
        </view>
      </view>
      <!-- 商品总价区域 -->
      <view class="goods-total display-flex-center">
        <view class="fs12 color-333 fw400">
          共{{ orderData.number_goods }}件商品&nbsp;&nbsp; 总计：<text class=" fs12 fw400">￥</text><text class="fw700 fs20">{{orderData.amount_goods }}</text>
        </view>
      </view>
    </view>
    <!-- 运费显示区域 -->
    <view class="common-card good-card display-flex-between">
      <view>运费</view>
      <view>￥{{ orderData.amount_express || 0 }}</view>
    </view>
    <!-- 优惠券和积分使用区域 -->
    <template v-if="pageOptions.isGift != '1' && pageOptions.type != 'msGoods'">
      <view class="common-card good-card ">
        <!-- 优惠券选择 -->
        <view class="display-flex-between" @click="choseCoupon">
          <view>优惠券</view>
          <view class="display-flex">
            <view v-if="checkedCoupon.coupon_id" > 已选：{{ checkedCoupon.coupon_price }}元优惠券</view>
            <view class=" ml10">
              <u-icon name="arrow-right"  color="#AEAEAE" size="34rpx"></u-icon>
            </view>
          </view>
        </view>
        <!-- 使用积分抵扣 -->
        <view class="display-flex-between  mt15"  v-if="usePointsFlag" >
          <view class="display-flex">使用 {{ pointsShowData.points }} 积分抵扣 <view class="color-556 ml5 mr5"> {{ pointsShowData.price }}</view>元</view>
          <u-checkbox-group v-model="usePoints" size="20" >
            <u-checkbox :disabled="pointsDisabled" activeColor="#C29556" name="points" shape="circle" label=" "></u-checkbox>
          </u-checkbox-group>
        </view>
      </view>

    </template>
    <!-- 留言区域 -->
    <view class="common-card good-card">
      <view class="fs14 mb10">留言</view>
      <u--textarea height="110" v-model="order_remark" placeholder="100字以内" maxlength="100" count></u--textarea>
    </view>
    <!-- 底部支付区域 -->
    <view class="bottom-box display-flex-end">
      <view>应付：<text class="color-556 fs12 fw400">￥</text><text class="fw700 fs20 color-556">{{payTotal}}</text></view>
      <view class="settle-center-btn" @click="toPay">去支付</view>
    </view>
    <!-- 优惠券选择弹窗 -->
    <u-popup :show="showCoupon" :round="10" mode="bottom" @close="showCoupon = false">
      <view class="coupon-list">
        <view class="popop-title text-center mb30">
          <text class="color-3 fw700 fs18">选择优惠券</text>
          <view class="float-right" @click="showCoupon = false">
            <u-icon name="close" bold="true" color="#8E8E8E" size="18"></u-icon>
          </view>
        </view>
        <!-- 优惠券列表 -->
        <couponItem v-for="item in couponList" :key="item.id" :data="item" :config="getItemConfig(item)"
                    @on-click="handleItem(item)"/>
      </view>
    </u-popup>
  </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},
      // 购物车商品ID列表
      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)
    },
    // 计算使用的积分数量
    integral() {
      return this.usePoints.length
    },
    // 计算用户可用积分
    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
    },

  },
  watch: {
    // 监听积分使用变化
    integral(nv) {
      if (this.pageOptions.type != 'cart') {
        this.$api.orderUserPoints({order_no: this.orderNo, integral: nv})
      }
    },
    // 监听商品总价变化
    'orderData.amount_goods'(nv) {
      if (nv) {
        if (this.pageOptions.type != 'cart') {
          this.$nextTick(() => {
            this.getPoints()
          })
        }
      }
    }
  },
  onLoad(options) {
    // 页面加载时获取订单编号和页面选项
    this.orderNo = options.orderNo
    this.pageOptions = options
  },
  onShow() {
    // 页面显示时根据类型获取数据
    const {type} = this.pageOptions
    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.getSelectAddress("cart")
      }
    } else {
      this.getCouponList()
      this.getOrderDetail()
    }
  },
  methods: {
    /**
     * 获取优惠券配置
     * @param {Object} item - 优惠券对象
     * @returns {Object} - 优惠券配置对象
     */
    getSelectAddress(type=""){
      this.$api.getAddressList().then(res => {
        // uni.hideLoading()
        let addressList = res.data || []
        for (let item of addressList) {
          if (item.type === 1) {
            uni.setStorageSync('selectAddress', JSON.stringify(item))
            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
                if (type==="cart"){
                  this.getExpressFee()
                }else{
                  this.addressConfirm()
                }
              }
              uni.removeStorageSync('selectAddress')
            }
            break
          }
        }
      })

    },
    getItemConfig(item) {
      let itemConfig = {
        btnText: '去使用',
        disabled: false,
        btnPlain: true
      }
      if (item.coupon_id == this.checkedCoupon.coupon_id) {
        itemConfig = {
          btnText: '取消使用',
          disabled: false,
          btnPlain: true
        }
      }
      return itemConfig
    },
    /**
     * 获取积分使用数据
     */
    getPoints() {
      this.$api.getPointsUseData().then(res => {
        if (!res.data.ratio) {
          this.usePointsFlag = false
          return
        } else {
          this.usePointsFlag = true
        }
        this.pointsData = res.data
        const {min_money, ratio, to_money} = this.pointsData
        const amount = this.orderData.amount_goods
        if (this.orderData.integral) {
          this.usePoints = ['points']
          let price = this.orderData.integral_price
          this.pointsShowData = {
            price: price.toFixed(2),
            points: Math.floor(price / to_money)
          }
        } else {
          let userPoints = 1000
          let price = Math.floor(amount * ratio / 100)
          let points = price * to_money
          points = this.userPoints > points ? points : this.userPoints
          price = points / to_money
          this.pointsShowData = {
            points: Math.floor(points),
            price: price.toFixed(2)
          }
        }
      })
    },
    /**
     * 获取购物车数据
     */
    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
        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/paySuccess?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/paySuccess?orderNo=${this.orderNo}`})
        this.$toWechatPay(this.orderNo, this.order_remark)
      }
    },
    /**
     * 地址确认
     */
    addressConfirm() {
      this.$api.submitOrderByAdress({order_no: this.orderNo, code: this.mAddress.code}).then(res => {
        this.orderData.amount_express = res.data.amount
      })
    },
    /**
     * 选择优惠券
     */
    choseCoupon() {
      if (this.couponList.length) {
        this.showCoupon = true
      } else {
        uni.showToast({
          title: '暂无可使用优惠券',
          icon: 'none'
        })
      }
    },
    /**
     * 获取优惠券列表
     */
    getCouponList() {
      this.$api.getCouponByOrder({order_no: this.orderNo}).then(res => {
        this.couponList = res.data
      })
    },
    /**
     * 处理优惠券选择
     * @param {Object} item - 优惠券对象
     */
    handleItem(item) {
      this.showCoupon = false

      if (Number(item.coupon_price) > Number(this.orderData.amount_goods)) {
        uni.showToast({
          title: '无法使用该优惠券!',
          icon: 'none'
        })
        return;
      }
      if (item.coupon_id == this.checkedCoupon.coupon_id) {
        this.checkedCoupon = {id: 0, coupon_id: 0}
      } else {
        this.checkedCoupon = item
      }
      if (this.pageOptions.type != 'cart') {
        this.$api.submitOrderByCoupon({order_no: this.orderNo, id: this.checkedCoupon.id})
      }
    },
    /**
     * 获取订单详情
     */
    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)) {
            this.mAddress = tempAddress
            this.addressConfirm()
          }
          uni.removeStorageSync('selectAddress')
        }else{
          this.getSelectAddress()
        }
      })
    },
    /**
     * 选择地址
     */
    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;
}
.bottom-box {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 170rpx;
  left: 0;
  right: 0;
  box-sizing: border-box;
  padding: 27rpx 30rpx;
  background-color: #fff;
  z-index: 1000;
  border-radius: 24rpx 24rpx 0rpx 0rpx;
}
.settle-center-btn {
  height: 76rpx;
  line-height: 78rpx;
  width: 170rpx;
  padding: 0 29rpx;
  color: #fff;
  background: linear-gradient( 315deg, #CA9359 0%, #E2B98E 100%);
  border-radius: 292rpx 292rpx 292rpx 292rpx;
  font-size: 32rpx;
  text-align: center;
  margin-left: 30rpx;
}
.good-card {
  padding: 38rpx 22rpx;
  color: #7A7A7A;

  ::v-deep {
    .u-textarea {
      background: #F6F6F6;
      border-radius: 12rpx 12rpx 12rpx 12rpx;
      border: none;
      padding: 18rpx;

      .u-textarea__count {
        background-color: transparent !important;
      }
    }
    .u-checkbox__icon-wrap{
      margin-right: 0!important;
    }
  }
}

.goods-list {
  margin: 0 30rpx;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #F5F5F5;
  .list-info {
    width: 100%;
  }
}

.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;
    }
  }
}
</style>
