<template>
  <view class="page__view">
		<navbar title="确认订单" leftClick @leftClick="$utils.navigateBack" color="#191919" bgColor="#F3F2F7" />

    <view class="main">

      <view class="flex address" @click="jumpToSelectAddress">
        <addressView :data="addressData" :showIcon="true"></addressView>
        <uv-icon name="arrow-right" color="#C6C6C6" size="32rpx"></uv-icon>
      </view>

      <view class="card" v-for="(item, index) in productList" :key="item.id">
        <productCard :data="item" @change="onChange(index, $event)"></productCard>
      </view>

      <view class="order" v-if="orderData">
        <view class="order-header">
          订单信息
        </view>
        <view class="flex row">
          <view class="row-label">订单编号</view>
          <view class="row-content">{{ orderData.number }}</view>
        </view>
        <view class="flex row">
          <view class="row-label">下单时间</view>
          <view class="row-content">{{ $dayjs(orderData.createTime).format('YYYY-MM-DD HH:mm') }}</view>
        </view>
      </view>
      
      <view class="notice">
        <view class="notice-header">下单须知</view>
        <view class="notice-content">
					<!-- todo: 替换配置项key -->
				  <uv-parse :content="configList['config_agreement']"></uv-parse>
        </view>
      </view>

    </view>
  
		<view class="bottom">
      <view class="agreement">
				<uv-checkbox-group
					v-model="checkboxValue"
					shape="circle"
				>
					<uv-checkbox
						size="40rpx"
						icon-size="40rpx"
						activeColor="#7451DE"
						:name="1"
					></uv-checkbox>
				</uv-checkbox-group>
				<view class="desc">
          我已阅读并同意
					<!-- todo: 替换配置项key -->
					<text class="highlight" @click="$refs.modal.open('config_agreement', '用户协议')">《用户协议》</text>
					<!-- todo: 替换配置项key -->
					<text class="highlight" @click="$refs.modal.open('config_privacy', '隐私协议')">《隐私协议》</text>
					<!-- todo: 替换配置项key -->
					<text class="highlight" @click="$refs.modal.open('config_privacy', '消费者告知')">《消费者告知》</text>
				</view>
			</view>
      <view class="flex bar">
        <view class="flex col price">
          <view class="price-label">合计</view>
          <view class="price-unit">¥</view><view class="price-value">{{ totalPrice }}</view>
        </view>
        <button class="col btn" @click="onPay">立即支付</button>
      </view>
    </view>

		<agreementModal ref="modal" @confirm="onConfirmAgreement"></agreementModal>

    <payPopup ref="payPopup" @submitted="onPaySuccess"></payPopup>

  </view>
</template>

<script>
	import { mapState } from 'vuex'

  import addressView from '@/pages_order/address/addressView.vue'
  import productCard from './productCard.vue'
	import agreementModal from '@/pages_order/components/agreementModal.vue'
  import payPopup from '@/pages_order/order/payPopup.vue'

  export default {
    components: {
      addressView,
      productCard,
      agreementModal,
      payPopup,
    },
    data() {
      return {
        id: null,
        defaultAddressInfo: null,
        orderData: null,
        productList: [],
        checkboxValue: [],
      }
    },
    computed: {
			...mapState(['configList', 'userInfo', 'payOrderProduct', 'addressInfo']),
			totalPrice() {
				return this.productList.reduce((price, item) => {
					// return price + item.price * (item.count || 1)
					return price + item.currentPrice
				}, 0)
			},
      addressData() {
        return this.addressInfo || this.defaultAddressInfo || null
      },
    },
    async onShow() {
      console.log('onShow')
      console.log('address', this.addressInfo)

      this.fetchDefaultAddress()
    },
    onLoad(arg) {
      console.log('onLoad')

      console.log('payOrderProduct', this.payOrderProduct)
      this.productList = JSON.parse(JSON.stringify(this.payOrderProduct))
      
      // todo: check include Overseas Product ?
			// this.$utils.navigateTo('/pages_order/order/userInfo/infoFill')

      return
      this.orderData = {
        id: '001',
        number: 'BH872381728321983929',
        createTime: '2025-04-28 08:14',
      }

      console.log('orderData', this.orderData)

    },
    onUnload() {
      this.$store.commit('setAddressInfo', null)
    },
    methods: {
      async fetchDefaultAddress() {
        try {
          const params = {
            pageNo: 1,
            pageSize: 1,
            userId: this.userInfo.id,
            defaultFlag: 1,
          }
          let { records, total } = await this.$fetch('getAddressList', params)

          this.defaultAddressInfo = total ? records[0] : null
        } catch (err) {
          this.defaultAddressInfo = null
        }
      },
      jumpToSelectAddress() {
        this.$utils.navigateTo('/pages_order/address/addressList')
      },
      onChange(index, obj) {
        console.log('onChange', index, obj)

        // todo: check skuId? currentPrice ?
        this.list[index].skuId = obj.id
        this.list[index].specName = obj.specName
      },
      onConfirmAgreement(confirm) {
        if (confirm) {
          this.checkboxValue = [1]
        } else {
          this.checkboxValue = []
        }
      },
      async onPay() {
        if(!this.checkboxValue.length){
          return uni.showToast({
            title: '请先同意《用户协议》《隐私协议》《消费者告知》',
            icon:'none'
          })
        }

        if (!this.addressData?.id) {
          return uni.showToast({
            title: '请选择地址',
            icon:'none'
          })
        }

        // const  { id } = this.orderData

        const obj = {
          // todo: check title
          title: '营养套餐消费', 
          // orderId: id,
          list: this.productList,
          addressId: this.addressData.id,
          amount: this.totalPrice,
        }

        this.$refs.payPopup.open(obj)
      },
      onPaySuccess() {
        uni.reLaunch({
          url: '/pages/order/orderList/index'
        })
      },
    },
  }
</script>

<style scoped lang="scss">

	.page__view {
		width: 100vw;
		min-height: 100vh;
		background-color: $uni-bg-color;
		position: relative;

    /deep/ .nav-bar__view {
      position: fixed;
      top: 0;
      left: 0;
    }
  }

  .main {
    padding: calc(var(--status-bar-height) + 144rpx) 32rpx 310rpx 32rpx;
  }

  .address {
    margin-bottom: 40rpx;
    justify-content: space-between;

    padding: 24rpx 32rpx;
    background: #FFFFFF;
    border-radius: 24rpx;
  }

  .card {
    & + & {
      margin-top: 32rpx;
    }
  }

  .order {
    margin-top: 40rpx;
    padding: 32rpx;
    background: #FAFAFF;
    border: 2rpx solid #FFFFFF;
    border-radius: 32rpx;

    &-header {
      font-family: PingFang SC;
      font-weight: 500;
      font-size: 36rpx;
      line-height: 1.4;
      color: #252545;
    }
    
    .row {
      margin-top: 32rpx;
      justify-content: space-between;
      font-family: PingFang SC;
      font-weight: 400;
      line-height: 1.4;

      &-label {
        font-size: 26rpx;
        color: #8B8B8B;
      }
      
      &-content {
        font-size: 28rpx;
        color: #393939;
      }
    }
  }

  .notice {
    margin-top: 40rpx;
    font-family: PingFang SC;
    font-weight: 400;

    &-header {
      font-size: 28rpx;
      line-height: 1.4;
      color: #393939;
    }

    &-content {
      margin-top: 24rpx;
      font-size: 24rpx;
      line-height: 1.3;
      color: #BABABA;
    }
  }

  .bottom {
		position: fixed;
		left: 0;
		bottom: 0;

		width: 100vw;
		height: 270rpx;
		background: #FFFFFF;
		box-sizing: border-box;
    
    .agreement {
      display: flex;
      padding: 16rpx 40rpx;
      background: #EFEAFF;
      box-sizing: border-box;

      /deep/ .uv-checkbox-group {
        flex: none;
      }

      .desc {
        flex: 1;
        font-family: PingFang SC;
        font-size: 24rpx;
        font-weight: 400;
        line-height: 40rpx;
        color: #8B8B8B;
      }

      .highlight {
        color: $uni-color;
      }
    }

    .bar {
      padding: 24rpx 40rpx;
      box-sizing: border-box;
      column-gap: 30rpx;

      .col {
        flex: 1;
      }

      .price {
        justify-content: flex-start;

        &-label {
          font-family: PingFang SC;
          font-weight: 400;
          font-size: 24rpx;
          line-height: 1.4;
          color: #626262;
        }

        &-unit {
          margin: 0 8rpx;
          font-family: PingFang SC;
          font-weight: 500;
          font-size: 24rpx;
          line-height: 1.4;
          color: #7451DE;
        }

        &-value {
          font-family: PingFang SC;
          font-weight: 500;
          font-size: 40rpx;
          line-height: 1.4;
          color: #7451DE;
        }
      }

      .btn {
        width: 100%;
        padding: 16rpx 0;
        box-sizing: border-box;
        font-family: PingFang SC;
        font-weight: 500;
        font-size: 36rpx;
        line-height: 1;
        color: #FFFFFF;
        background-image: linear-gradient(to right, #4B348F, #845CFA);
        border-radius: 41rpx;
      }

    }

	}

</style>