<template>
  <view class="page__view">
		<navbar leftClick @leftClick="$utils.navigateBack" >
      <view class="flex">
        <view>待支付</view>
        <template v-if="time">
          <uv-count-down 
            :time="time" 
            format="mm:ss" 
            autoStart 
            millisecond 
            @change="onChange">
            <view class="flex countdown">
              <text>剩余</text>
              <text>{{ `${timeData.minutes}:${timeData.seconds}` }}</text>
            </view>
          </uv-count-down>
          <view>后关闭</view>
        </template>
      </view>
    </navbar>

    <view class="main">

      <productCard :data="productCardData"></productCard>

      <orderInfoView :data="detail"></orderInfoView>

      <view class="notice">
        <view class="notice-header">下单须知</view>
        <view class="notice-content">
				  <uv-parse :content="configList['order_instructions']"></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="#00A9FF"
						:name="1"
					></uv-checkbox>
				</uv-checkbox-group>
				<view class="desc">
          我已阅读并同意
					<text class="highlight" @click="$refs.modal.open('unsubscribe_policy', '退订政策')">《退订政策》</text>
					<text class="highlight" @click="$refs.modal.open('model_contract', '合同范本')">《合同范本》</text>
					<text class="highlight" @click="$refs.modal.open('booking_instructions', '预订须知')">《预订须知》</text>
					<text class="highlight" @click="$refs.modal.open('safety_reminder', '安全提示')">《安全提示》</text>
				</view>
			</view>
      <view class="flex bar">
        <button plain class="flex flex-column btn btn-simple" open-type="contact">
          <image class="icon" src="@/pages_order/static/product/icon-service.png" mode="widthFix"></image>
          <view>联系客服</view>
        </button>
        <view class="col flex price">
          <view class="price-label">
            合计
          </view>
          <view class="price-unit">¥</view>
          <view class="price-value">
            {{ detail.payAmount }}
          </view>
        </view>
        <button class="col btn btn-primary" @click="onPay">立即支付</button>
      </view>
    </view>

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

  </view>
</template>

<script>
	import { mapState } from 'vuex'

  import productCard from '@/pages_order/order/components/productCard.vue'
  import orderInfoView from '@/pages_order/order/components/orderInfoView.vue'
	import agreementModal from '@/pages_order/components/agreementModal.vue'

  export default {
    components: {
      productCard,
      orderInfoView,
      agreementModal,
    },
    data() {
      return {
        id: null,
        detail: {},
        time: null,
        timeData: {},
        checkboxValue: [],
      }
    },
    computed: {
			...mapState(['configList', 'userInfo', 'orderInfo']),
      productCardData() {
        const { 
          activityId,
          activityTitle,  
          activityBrief,
          activityTag,
          startDate,
          endDate,
        } = this.detail

        return {
          time: 'time',
          product: {
            id: activityId,
            title: activityTitle,
            brief: activityBrief,
            tagDetails: activityTag,
            dateList: [
              {
                id: 'time',
                startDate,
                endDate,
              }
            ]
          }
        }
      },
    },
    async onLoad({ id }) {
      this.id = id

      await this.fetchOrderDetail()
      // todo
      // this.updateCountdown()
    },
    async onPullDownRefresh() {
      await this.fetchOrderDetail()
      uni.stopPullDownRefresh()
    },
    methods: {
      async fetchOrderDetail() {
        try {

          this.detail = await this.$fetch('queryOrderById', { orderId: this.id })
          console.log('orderInfo', this.detail)

        } catch (err) {

        }

        uni.stopPullDownRefresh()
      },
      onConfirmAgreement(confirm) {
        if (confirm) {
          this.checkboxValue = [1]
        } else {
          this.checkboxValue = []
        }
      },
      async onPay() {
        if(!this.checkboxValue.length){
          return uni.showToast({
            title: '请先同意《退订政策》《合同范本》《预订须知》《安全提示》',
            icon:'none'
          })
        }

        try {
     
          const result = await this.$fetch('payOrder', { orderId: this.id })
          
          await uni.requestPaymentWxPay({ result })
       
          uni.showToast({
            title: '支付成功',
            icon: 'none'
          })
          
          setTimeout(() => {
            // todo: check → jump to order list page ?
            uni.reLaunch({
              url: `/pages_order/order/orderList/index`
            });
          }, 700)
        } catch (err) {

        }
      },
      updateCountdown() {

        let current = dayjs()
        let startTime = dayjs(this.detail.createTime)

        if (startTime.isSameOrBefore(current)) {
          this.time = null
          return
        }

        this.time = startTime.diff(current, 'second')

      },
			onChange(e) {
				this.timeData = e
			},
    },
  }
</script>

<style scoped lang="scss">

  @import '../styles/style.scss';

  .bottom {
    .bar {
      .price {
        justify-content: flex-start;
        column-gap: 8rpx;
        
        &-label {
          font-size: 24rpx;
          color: #626262;
        }

        &-unit,
        &-value {
          font-weight: 500;
          color: #FF4800;
        }

        &-unit {
          font-size: 24rpx;
        }

        &-value {
          font-size: 40rpx;
        }
      }

      .btn-simple {
        flex: none;
        width: auto;
        font-family: PingFang SC;
        font-weight: 400;
        font-size: 22rpx;
        line-height: 1.1;
        color: #999999;
        border: none;
        border-radius: unset;

        .icon {
          width: 52rpx;
          height: auto;
          margin-bottom: 4rpx;
        }
      }
    }
  }
  
</style>