<template>
  <view class="confirm-page">
    <view class="wanl-order">
      <view class="address cu-list menu-avatar margin-bj radius-bock" @tap="chooseAddress">
        <view class="cu-item">
          <view class="cu-avatar round wanl-bg-orange">
            <text class="wlIcon wlIcon-weizhi1"></text>
          </view>
          <view class="content" v-if="addressData.address">
            <view>
              <text class="wanl-pip margin-right-sm">{{ addressData.name }}</text>
              <text class="wanl-gray-light text-sm">{{ addressData.mobile }}</text>
            </view>
            <view class="text-sm wanl-pip text-cut">
              {{ addressData.province }} {{ addressData.city }} {{ addressData.district }} {{ addressData.address }}
            </view>
          </view>
          <view class="content" v-else>
            <view class="text-sm wanl-pip text-cut">{{ $t('orderConfirm.addAddress') }}</view>
          </view>
          <view class="action">
            <text class="wlIcon wlIcon-fanhui2 text-lg"></text>
          </view>
        </view>
      </view>

      <view v-for="(shop, index) in orderData.lists" :key="index" class="lists bg-white margin-bj radius-bock">
        <view class="shopname">
          <text class="wlIcon wlIcon-dianpu2 text-orange margin-right-sm"></text>
          <text class="wanl-pip text-df">{{ shop.shop_name }}</text>
        </view>
        <view class="cu-list menu-avatar">
          <view class="cu-item margin-bottom" v-for="(goods, key) in shop.products" :key="key">
            <image class="goods-img radius" :src="$appKit.oss(goods.sku.thumbnail, 140, 140, 1)" mode="aspectFill"
              lazy-load></image>
            <view class="content">
              <view class="text-sm text-cut-2">{{ goods.title }}</view>
              <view class="wanl_sku text-sm sku-full">
                <text v-for="(item, skey) in goods.sku.difference" :key="skey">
                  <block v-if="skey != 0">-</block>{{ item }}
                </text>
              </view>
            </view>
            <view class="action">
              <view class="wanl-pip text-sm text-price">{{ goods.sku.price }}</view>
              <view class="wanl-gray-light text-sm">x{{ goods.number }}</view>
            </view>
          </view>
        </view>
        <form>
          <view class="cu-form-group">
            <view class="wanl-gray-light title">{{ $t('orderConfirm.freight') }}</view>
            <view class="picker">
              {{ shop.freight.name }}
              <text class="text-price margin-left-xs">{{ shop.freight.price }}</text>
            </view>
          </view>
          <view class="cu-form-group" @tap="queryCoupon(index)">
            <view class="wanl-gray-light title">{{ $t('orderConfirm.coupon') }}</view>
            <view class="picker">
              <block v-if="couponData[index]">
                <text class="wlIcon wlIcon-youhuiquantuangou text-red margin-right-xs"></text>
                <!-- 滿減優惠券 -->
                <block
                  v-if="couponData[index].type == 'reduction' || (couponData[index].type == 'vip' && couponData[index].usertype == 'reduction')">
                  {{ $t('orderConfirm.couponFullReduction', { limit: Number(couponData[index].limit), price: Number(couponData[index].price) }) }}
                </block>
                <!-- 折扣優惠券 -->
                <block
                  v-if="couponData[index].type == 'discount' || (couponData[index].type == 'vip' && couponData[index].usertype == 'discount')">
                  {{ $t('orderConfirm.couponDiscount', { limit: Number(couponData[index].limit), discount: Number(couponData[index].discount) }) }}
                </block>
                <!-- 包郵優惠券 -->
                <block v-if="couponData[index].type == 'shipping'">
                  {{ $t('orderConfirm.couponFreeShipping', { limit: Number(couponData[index].limit) }) }}
                </block>
              </block>
              <!-- 请选择 -->
              <block v-else>
                <text class="text-gray">{{ $t('orderConfirm.select') }}</text>
              </block>
              <text class="wlIcon wlIcon-fanhui2 margin-left"></text>
            </view>
          </view>
          <view class="cu-form-group align-start">
            <view class="wanl-gray-light title">{{ $t('orderConfirm.remark') }}</view>
            <textarea maxlength="-1" v-model="shop.remarks" :placeholder="$t('orderConfirm.remarkPlaceholder')"></textarea>
          </view>
        </form>
        <view class="text-right margin-bj text-sm">
          <text class="wanl-gray">{{ $t('orderConfirm.totalItems', { count: shop.number }) }}</text>
          {{ $t('orderConfirm.subtotal') }}
          <text class="text-price text-orange">{{ shop.sub_price }}</text>
        </view>
      </view>

      <view class="safeAreaBottom"></view>
    </view>

    <view class="cu-modal bottom-modal" :class="modalName == 'coupon' ? 'show' : ''" @tap="hideModal">
      <view class="cu-dialog bg-bgcolor" @tap.stop="">
        <view class="wanl-modal">
          <view class="head padding-bj">
            <view class="content">
              <view class="text-lg">{{ $t('orderConfirm.couponTitle') }}</view>
            </view>
            <view class="close wlIcon wlIcon-31guanbi" @tap="hideModal"></view>
          </view>
          <scroll-view class="wanl-coupon scroll-y" scroll-y="true" v-if="couponIndex != null">
            <view v-for="(coupon, index) in orderData.lists[couponIndex].coupon" :key="index" :class="coupon.type"
              class="item margin-bottom-bj radius-bock">
              <view class="item-left">
                <block v-if="coupon.type == 'reduction' || (coupon.type == 'vip' && coupon.usertype == 'reduction')">
                  <view class="colour">
                    <text class="text-price"></text>
                    <text class="prices">{{ Number(coupon.price) }}</text>
                  </view>
                  <view class="cu-tag wanl-gray-dark radius text-sm bg-white">
                    {{ $t('orderConfirm.couponFullReduction', { limit: Number(coupon.limit), price: Number(coupon.price) }) }}
                  </view>
                </block>
                <block v-if="coupon.type == 'discount' || (coupon.type == 'vip' && coupon.usertype == 'discount')">
                  <view class="colour">
                    <text class="prices">{{ Number(coupon.discount) }}</text>
                    <text class="discount">{{ $t('orderConfirm.discount') }}</text>
                  </view>
                  <view class="cu-tag wanl-gray-dark radius text-sm bg-white">
                    {{ $t('orderConfirm.couponDiscount', { limit: Number(coupon.limit), discount: Number(coupon.discount) }) }}
                  </view>
                </block>
                <block v-if="coupon.type == 'shipping'">
                  <view class="colour">
                    <text class="prices">{{ $t('orderConfirm.freeShipping') }}</text>
                  </view>
                  <view class="cu-tag wanl-gray-dark radius text-sm bg-white">
                    {{ $t('orderConfirm.couponFreeShipping', { limit: Number(coupon.limit) }) }}
                  </view>
                </block>
              </view>
              <view class="item-right padding-bj">
                <view class="title">
                  <view class="cu-tag sm radius margin-right-xs tagstyle">{{ coupon.type_text }}</view>
                  <text class="text-cut wanl-gray text-min">{{ coupon.name }}</text>
                </view>
                <view class="content text-min">
                  <view class="wanl-gray">
                    <view v-if="coupon.grant != '-1'">
                      <text class="wlIcon wlIcon-dot"></text>{{ $t('orderConfirm.couponRemaining', { count: coupon.surplus }) }}
                    </view>
                    <view v-if="coupon.drawlimit != 0">
                      <text class="wlIcon wlIcon-dot"></text>{{ $t('orderConfirm.couponLimit', { count: coupon.drawlimit }) }}
                    </view>
                  </view>
                  <view class="cu-btn sm round line-colour" @tap="onCoupons(index)" v-if="coupon.state">
                    <text v-if="coupon.choice">{{ $t('orderConfirm.couponSelected') }}</text>
                    <text v-else>{{ $t('orderConfirm.couponUse') }}</text>
                  </view>
                  <view class="cu-btn sm round" @tap="onReceive(index)" v-else>
                    {{ $t('orderConfirm.couponReceive') }}
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
          <view class="foot padding-lr-bj">
            <button class="cu-btn bg-gradual-orange round text-bold complete" @tap="hideModal">{{ $t('orderConfirm.complete') }}</button>
          </view>
        </view>
      </view>
    </view>
    <!-- 訂單確認 -->
    <view class="wanlian cu-bar tabbar solid-top foot text-df">
      <view>
        <text class="wanl-gray">{{ $t('orderConfirm.totalItems', { count: orderData.statis.allnum }) }}</text>
        {{ $t('orderConfirm.total') }}
        <text class="text-price text-orange">{{ orderData.statis.allsub }}</text>
      </view>
      <button v-if="loading" class="cu-btn round lg bg-gradual-orange margin-lr-bj">
        <text class="wlIcon wlIcon-jiazai wlIconfont-spin margin-right-xs"></text>{{ $t('orderConfirm.submitting') }}
      </button>
      <button v-else @tap="addOrder" class="cu-btn round lg bg-gradual-orange margin-lr-bj">{{ $t('orderConfirm.submitOrder') }}</button>
    </view>
  </view>
</template>

<script>
import {
  postOrderGetGoodsList,
  postOrderAddOrder,
  pullMallCouponQuery,
  pullMallCouponReceive,
  pullAddressList
} from '@/features/mall/mall-gateway'
import { decimalAdd, decimalSub, decimalMul, decimalDiv } from '@/core/infra/runtime-bridge'
export default {
  data() {
    return {
      loading: false,
      reload: false,
      token: '',
      optionData: {},
      addressData: {},
      modalName: null,
      cartType: null,
      couponData: {},
      couponIndex: null,
      selectedAddressId: null,//選擇的收貨地址id
      orderData: {
        lists: [],
        statis: {
          allnum: 0,
          allsub: 0
        }
      }
    }
  },
  onLoad(option) {
    if (option.data) {
      this.optionData = JSON.parse(option.data)
    }
    if (option.type) {
      this.cartType = option.type
    }
  },
  onShow() {
    this.loading = false
    // 監聽地址刷新事件（當用戶添加/修改地址時觸發）
    uni.$on('addressRefresh', (newAddressId) => {
      if (newAddressId) {
        // 直接使用後端返回的新地址 ID
        this.selectedAddressId = newAddressId
      } else {
        this.selectedAddressId = null
      }
      // 延遲 500ms 再加載訂單數據
      setTimeout(() => {
        this.loadData()
      }, 500)
    })
    if (!this.selectedAddressId) {//如果没有选择收货地址
      setTimeout(() => {
        this.loadData()
      }, 100)
    }
  },
  onUnload() {
    // 移除地址刷新事件監聽，防止內存漏
    uni.$off('addressRefresh')
  },
  methods: {
    // 加載訂單商品列表
    async loadData(address_id) {
      try {
        if (address_id) {                    // ← 新增：保存地址 ID
          this.selectedAddressId = address_id
        }
        const data = await postOrderGetGoodsList({
          data: this.optionData,
          address_id: this.selectedAddressId || 0
        })
        this.token = data.token
        this.orderData = data.orderData
        this.addressData = data.addressData
      } catch (e) {
        if (e && (e.msg === '請添加收貨地址' || e.msg === '请添加收货地址')) {
          this.reload = true
          this.addAddress('newadd')
        } else {
          uni.showToast({ title: this.$t('orderConfirm.loadFailed'), icon: 'none' })
        }
      }
    },
    // 提交訂單
    async addOrder() {
      if (this.orderData.statis.allnum === 0) {
        uni.showToast({ title: this.$t('orderConfirm.selectProduct'), icon: 'none' })
        return
      }
      let address_id = this.addressData.id
      if (!address_id) {
        uni.showToast({ title: this.$t('orderConfirm.fillAddress'), icon: 'none' })
        return
      }
      let data = { lists: [], address_id: address_id }
      let cart = []
      this.orderData.lists.forEach((item, index) => {
        data.lists.push({
          shop_id: item.shop_id,
          remarks: item.remarks,
          products: [],
          coupon_id: this.couponData[index] ? this.couponData[index].id : 0
        })
        item.products.forEach(goods => {
          cart.push({
            goods_id: goods.id,
            sku_id: goods.sku.id
          })
          data.lists[index].products.push({
            goods_id: goods.id,
            number: goods.number,
            sku_id: goods.sku.id,
            freight_id: goods.freight_id
          })
        })
      })
      this.loading = true
      try {
        const resData = await postOrderAddOrder({ order: data, token: this.token })
        this.$store.commit('statistics/order', {
          pay: this.$store.state.statistics.order.pay + resData.list.length,
          whole: this.$store.state.statistics.order.whole + resData.list.length
        })
        let couponCount = Object.keys(this.couponData).length
        if (couponCount != 0) {
          this.$store.commit('statistics/dynamic', {
            coupon: this.$store.state.statistics.dynamic.coupon - couponCount
          })
        }
        if (this.cartType == 'cart') {
          this.$store.dispatch('cart/del')
        }
        uni.redirectTo({
          url: `/pages/user/money/pay?token=${resData.token}&data=${JSON.stringify(resData.list)}`
        })
      } catch (e) {
        uni.showToast({ title: e.message, icon: 'none' })
        this.loading = false
      }
    },
    // 查詢優惠券
    async queryCoupon(index) {
      let data = this.orderData.lists[index]
      if (data.coupon.length == 0) {
        let goods_id = []
        let shop_category_id = []
        for (var i = 0; i < data.products.length; i++) {
          goods_id.push(data.products[i]['id'])
          shop_category_id.push(data.products[i]['shop_category_id'])
        }
        try {
          const resData = await pullMallCouponQuery({
            shop_id: data.shop_id,
            goods_id: this.unique(goods_id),
            shop_category_id: this.unique(shop_category_id),
            price: data.order_price
          })
          data.coupon = resData
        } catch (e) {
          uni.showToast({ title: this.$t('orderConfirm.queryCouponFailed'), icon: 'none' })
        }
      }
      this.couponIndex = index
      this.modalName = 'coupon'
    },
    // 获取優惠券
    async onReceive(index) {
      let coupon = this.orderData.lists[this.couponIndex].coupon[index]
      try {
        const data = await pullMallCouponReceive({ id: coupon.id })
        coupon.id = data.id
        coupon.state = true
        uni.showToast({ title: data.msg || this.$t('mall.receiveSuccess'), icon: 'none' })
        this.$store.commit('statistics/dynamic', {
          coupon: this.$store.state.statistics.dynamic.coupon + 1
        })
      } catch (e) {
        uni.showToast({ title: this.$t('orderConfirm.receiveFailed'), icon: 'none' })
      }
    },
    // 選擇優惠券
    onCoupons(index) {
      let order = this.orderData.lists[this.couponIndex]
      let data = this.orderData.lists[this.couponIndex].coupon
      data[index].choice = !data[index].choice
      if (data[index].choice) {
        for (var i = 0; i < data.length; i++) {
          if (i != index) {
            data[i].choice = false
          }
        }
        this.couponData[this.couponIndex] = data[index]
        if (data[index].type == 'reduction' || (data[index].type == 'vip' && data[index].usertype == 'reduction')) {
          order.freight.price = order.freight_price_bak
          order.sub_price = decimalSub(decimalAdd(order.order_price, order.freight.price), data[index].price)
          if (order.sub_price < 0) {
            order.sub_price = 0.01
          }
        }
        if (data[index].type == 'discount' || (data[index].type == 'vip' && data[index].usertype == 'discount')) {
          let discount = data[index].discount > 10 ? decimalDiv(data[index].discount, 100) : decimalDiv(data[index].discount, 10)
          order.freight.price = order.freight_price_bak
          order.sub_price = decimalAdd(decimalMul(order.order_price, discount), order.freight.price)
        }
        if (data[index].type == 'shipping') {
          order.freight.price = 0
          order.sub_price = order.order_price
        }
      } else {
        this.couponData = {}
        if (data[index].type == 'shipping') {
          order.freight.price = order.freight_price_bak
        }
        order.sub_price = decimalAdd(order.order_price, order.freight.price)
      }
      this.orderData.statis.allsub = 0
      for (var i = 0; i < this.orderData.lists.length; i++) {
        this.orderData.statis.allsub = decimalAdd(this.orderData.statis.allsub, this.orderData.lists[i].sub_price)
      }
      this.modalName = null
    },
    // 新增地址
    addAddress(type) {
      uni.navigateTo({ url: `/pages/user/address/addressManage?type=${type}` })
    },
    // 選擇地址
    chooseAddress() {
      if (this.addressData.address) {
        uni.navigateTo({ url: '/pages/user/address/address?source=1' })
      } else {
        this.addAddress('newadd')
      }
    },
    // 隱藏弹窗
    hideModal() {
      this.modalName = null
    },
    // 去重
    unique(arr) {
      return Array.from(new Set(arr)).join(',')
    },
  }
}
</script>

<style scoped>
.confirm-page {
  min-height: 100vh;
  background: #f3f5f7;
  padding-bottom: 120rpx;
}

.cu-bar.fixed {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 20rpx;
  background: #fff;
}

.cu-bar.fixed .action:first-child {
  margin-left: 0;
}

.cu-bar.fixed .action:last-child {
  margin-right: 0;
}

.cu-bar .action text {
  font-size: 40rpx;
  color: #333;
}

.wanl-order .address,
.wanl-order .lists {
  box-shadow: 0 8rpx 28rpx rgba(17, 24, 39, 0.06);
  border-radius: 18rpx !important;
}

.wanl-order .lists {
  overflow: hidden;
}

.wanl-order .shopname {
  padding: 18rpx 22rpx 0;
}

.wanlian.cu-bar.tabbar.foot {
  background: rgba(255, 255, 255, 0.96) !important;
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(0, 0, 0, 0.06);

  &>view:first-child {
    padding-left: 20rpx;
  }
}

.wanlian.cu-bar.tabbar .cu-btn.round.lg {
  background: linear-gradient(135deg, #ff6b35, #ff3d2e) !important;
  color: #fff !important;
}

.sku-full {
  overflow: visible !important;
  text-overflow: clip !important;
  white-space: normal !important;
  display: block !important;
  -webkit-line-clamp: unset !important;
  line-clamp: unset !important;
  word-wrap: break-word;
  word-break: break-all;
  margin-bottom: 10rpx;
}

.goods-img {
  position: absolute;
  left: 25rpx;
  width: 140rpx;
  height: 140rpx;
}

.wanl-order .lists .cu-list.menu-avatar>.cu-item {
  height: auto !important;
  min-height: 160rpx;
  padding-top: 20rpx;
  padding-bottom: 20rpx;
  align-items: flex-start;
  margin-bottom: 50rpx !important;
}

.wanl-order .lists .cu-list.menu-avatar>.cu-item .content {
  padding-bottom: 10rpx;
}

.wanl-order form {
  margin-top: 20rpx;
  padding-top: 10rpx;
}

.wanl-order form .cu-form-group:first-child {
  margin-top: 0;
  padding-top: 20rpx;
}

.wanl-coupon {
  max-height: 60vh;
}

.wanl-coupon .item {
  display: flex;
  overflow: hidden;
}

.wanl-coupon .item-left {
  width: 240rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30rpx 20rpx;
}

.wanl-coupon .item-left .prices {
  font-size: 56rpx;
  font-weight: bold;
  color: #ff6b35;
}

.wanl-coupon .item-left .discount {
  font-size: 24rpx;
  color: #ff6b35;
}

.wanl-coupon .item-left .cu-tag {
  margin-top: 10rpx;
}

.wanl-coupon .item-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.wanl-coupon .item-right .title {
  display: flex;
  align-items: center;
}

.wanl-coupon .item-right .content {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.wanl-modal .head {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.wanl-modal .head .close {
  font-size: 36rpx;
  color: #999;
}

.wanl-modal .foot .complete {
  width: 100%;
}
</style>