<script setup lang="ts">
import '@vant/touch-emulator'
import { getDict, usePay } from '@/hooks'
import { debounce } from 'lodash-es'
import orderApi from '@/api/order'
import { px2vh } from '@/utils'
import sass from '@/utils/sass'

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits(['update:modelValue'])
const value = computed({
  get: () => props.modelValue,
  set: val => {
    emit('update:modelValue', val)

    if (!val) {
      end()
    }
  },
})

const title = ref('选择续费时长')
const step = ref(1)
const durationList = [
  Array(12)
    .fill('')
    .map((_i, idx) => ({
      text: idx + 1,
      value: idx + 1,
    })),
  [
    { text: '月', value: 'month' },
    { text: '年', value: 'year' },
  ],
]
const duration = ref<any[]>([1, 'month'])

const dict = getDict('vip_renew_dict', true).enum
const monthPrice = dict?.every_month_cost || 99
const yearPrice = dict?.every_year_cost || 960
// const months = computed(() => {
//   let months = 0
//   if (duration.value[1] === 'year') {
//     months = duration.value[0] * 12
//   } else {
//     months = duration.value[0]
//   }
//   return months
// })
const totalPrice = computed(() => {
  const size = duration.value[0]
  if (duration.value[1] === 'year') {
    return size * yearPrice
  } else if (size === 12) {
    // 12个月，就是1年
    return yearPrice
  } else {
    return size * monthPrice
  }
})
const showTime = computed(() =>
  duration.value[1] === 'month' ? `${duration.value[0]}个月` : `${duration.value[0]}年`,
)

function onOpen() {
  step.value = 1
  title.value = '选择续费时长'
}

const { qrCode, status, reqRes, loading, start, end } = usePay()

const createOrder = () =>
  orderApi.createVipRenewPrepayOrder({
    money: totalPrice.value,
    renewMonth: duration.value[1] === 'month' ? duration.value[0] : undefined,
    renewYear: duration.value[1] === 'year' ? duration.value[0] : undefined,
    orderType: 0,
  })

const btnLoading = ref(false)
const onOk = debounce(
  async () => {
    try {
      btnLoading.value = true
      await start(createOrder)
      step.value = 2
      title.value = '支付'
    } finally {
      btnLoading.value = false
    }
    // 返回true让弹框不要马上关闭
    return true
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 刷新二维码
const onRefresh = debounce(
  () => {
    if (status.value !== -1) return
    start(createOrder)
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

const optionHeight = px2vh(98)
</script>

<template>
  <mj-dialog
    v-model="value"
    :class="{
      'x-pay-dia': true,
      'pay-dia': step !== 1,
    }"
    :title="title"
    :hide-footer="step !== 1"
    :open="onOpen"
    :ok="onOk"
  >
    <div
      :class="{
        'dia-content': true,
        'pay-content': step !== 1,
      }"
    >
      <van-picker
        v-if="step === 1"
        v-model="duration"
        :show-toolbar="false"
        :columns="durationList"
        :option-height="optionHeight"
      />
      <div v-if="step === 2 && status !== 1" class="pay">
        <div class="pay-text">
          {{ sass.platform.appName }}VIP帐号续费
          <span class="hl">{{ showTime }}</span>
        </div>
        <div
          v-loading="loading"
          :class="{
            'pay-qr': true,
            'is-expired': status === -1,
          }"
          @click="onRefresh"
        >
          <img class="qr" :src="qrCode" />
          <Icon v-if="status === -1" name="order_refresh" size="96" />
        </div>
        <div class="pay-info">请使用微信扫码支付</div>
        <div class="pay-price">¥{{ totalPrice }}</div>
      </div>
      <div v-if="step === 2 && status === 1" class="pay pay-susses">
        <div class="pay-text">支付成功</div>
        <div class="pay-text">会员到期时间为</div>
        <div class="pay-text">
          <span class="hl">{{ reqRes.vipExpiredTime || '' }}</span>
        </div>
      </div>
    </div>
  </mj-dialog>
</template>

<style lang="scss">
.x-pay-dia {
  .dia-content {
    height: 23.33vh;
    position: relative;
    overflow: hidden;
    font-family: $font-cn;
    margin-bottom: 1.67vh;
    &.pay-content {
      height: 46.67vh;
    }

    .van-picker {
      width: 100%;
      position: absolute;
      top: -60%;
      background: transparent;
      .van-picker-column__item {
        .van-ellipsis {
          height: 8.17vh;
          line-height: 8.17vh;
          font-size: 2.67vh;
          color: $font-minor-color;
          width: 240px;
          text-align: center;
          border-bottom: 0.08vh solid #ccc;
        }

        &.van-picker-column__item--selected {
          .van-ellipsis {
            color: $font-tag-color;
          }
        }

        &:last-child {
          .van-ellipsis {
            border: none;
          }
        }
      }
      .van-picker__mask {
        background: transparent;
      }
    }

    .pay {
      height: 100%;
      text-align: center;
      padding-top: $space-5_h;

      &.pay-susses {
        display: flex;
        flex-direction: column;
        flex-wrap: wrap;
        align-items: center;
        justify-content: center;
        div {
          font-size: 3.33vh;
          width: 100%;
          margin-bottom: $space-3_h;
        }
      }

      &-text {
        font-family: $font-special;
        color: $font-tag-color;
        font-size: 2.67vh;
        line-height: 1.5em;
        margin-bottom: $space-1_h;
        .hl {
          color: #99d609;
        }
      }
      &-qr {
        width: 320px;
        height: 26.67vh;
        display: flex;
        justify-content: center;
        margin: $space-1_h auto;

        .qr {
          width: 320px;
          height: 26.67vh;
        }

        &.is-expired {
          font-family: $font-special;
          position: relative;
          .qr {
            background: lightgray -208.066px -254.815px / 230.041% 313.58% no-repeat;
            filter: blur(8px);
          }
        }
        .x-icon {
          position: absolute;
          top: 40%;
          left: 50%;
          transform: translate(-50%, -50%);
          &::after {
            position: absolute;
            bottom: -4.67vh;
            left: -110px;
            width: 320px;
            height: 3vh;
            content: '二维码过期，请重新刷新';
            display: block;
            color: #fff;
            font-size: 2vh;
            line-height: 1.5em;
          }
        }
      }
      &-info {
        color: $font-tag-color;
        font-size: 2vh;
        line-height: 1.5em;
        margin-bottom: $space-1_h;
      }
      &-price {
        color: #fc4444;
        font-size: 3.33vh;
        line-height: 1.5em;
      }
    }
  }
}

.pay-dia {
  .el-dialog__body {
    padding: 0;
    .body {
      height: 46.67vh;
    }
  }
}
</style>
