import { defineComponent, onMounted, reactive, ref } from 'vue'
import styles from './index.module.less'
import { Cell, CellGroup, Checkbox, Icon, Image } from 'vant'
import activeButtonIcon from '@common/images/icon_checkbox.png'
import inactiveButtonIcon from '@common/images/icon_checkbox_default.png'
import iconDiscount from '@common/images/icon_discount.png'
import request from '@/helpers/request'
import { state } from '@/state'
import { moneyFormat } from '@/helpers/utils'
import dayjs from 'dayjs'

type DiscountDetail = {
  /** 编号 */
  id: number | null
  /** 销售金额 */
  salePrice: number
  /** 折扣 */
  discountRate: number
  /** 类型 */
  period: string
  /**　券类型 */
  vipType: string
}

export default defineComponent({
  name: 'add-discount',
  props: {
    /** 订单类型 */
    orderType: {
      type: String,
      default: ''
    },
    /** 实际需要支付金额 */
    actualPrice: {
      type: Number,
      default: 0
    }
  },
  emits: ['confirm'],
  setup(props, { emit }) {
    //
    const isDisplay = ref(false)
    const checked = ref(false)
    const params = reactive({
      discountPrice: 0 as any, // 优惠的金额,
      startTime: '' as string,
      endTime: '' as string
    })
    const discountDetail = ref<DiscountDetail>({
      id: null,
      salePrice: 0,
      discountRate: 0,
      period: 'YEAR',
      vipType: 'DISCOUNT'
    })

    // 格式化显示
    const formatShowTime = () => {
      console.log(props.actualPrice, 'actualPrice')
      if(checked.value) {
        params.discountPrice = (
          props.actualPrice -
          (props.actualPrice * discountDetail.value.discountRate / 100)
        ).toFixed(2)
        // discountEndTime
        const users = state.user.data
        const startTime = users.discountEndTime || new Date()
        let endTime = dayjs(new Date()).format('YYYY-MM-DD')
        if (discountDetail.value.period === 'MONTH') {
          endTime = dayjs(startTime).add(1, 'month').format('YYYY-MM-DD')
        } else if (discountDetail.value.period === 'QUARTERLY') {
          endTime = dayjs(startTime).add(3, 'month').format('YYYY-MM-DD')
        } else if (discountDetail.value.period === 'YEAR_HALF') {
          endTime = dayjs(startTime).add(6, 'month').format('YYYY-MM-DD')
        } else if (discountDetail.value.period === 'YEAR') {
          endTime = dayjs(startTime).add(1, 'year').format('YYYY-MM-DD')
        }
        params.startTime = dayjs(startTime).format('YYYY-MM-DD')
        params.endTime = endTime
      } else {
        params.discountPrice = 0
        params.startTime = ''
        params.endTime = ''
      }
    }

    const onDiscountChange = () => {
      checked.value = !checked.value

      formatShowTime()

      emit('confirm', {
        checked: checked.value,
        discountPrice: params.discountPrice,
        ...discountDetail.value
      })
    }

    const __init = async () => {
      const { data } = await request.get(
        `${state.platformApi}/memberPriceSettings/getDiscount`
      )
      discountDetail.value = {
        id: data.id,
        salePrice: data.salePrice,
        period: data.period,
        discountRate: (data.discountRate || 0) * 100,
        vipType: data.vipType
      }
      const productType = data.productType ? data.productType.split(',') : []
      // 判断是否需要购买畅学卡
      if (productType.includes(props.orderType)) {
        isDisplay.value = true
      } else {
        isDisplay.value = false
      }
    }

    __init()
    return () =>
      isDisplay.value ? (
        <div class={styles.addDiscount}>
          <CellGroup class={['mb12', styles.cellGroup]} border={false}>
            <Cell
              center
              class={styles.selectDiscount}
              titleClass={styles.titleClass}
              onClick={() => {
                onDiscountChange()
              }}
              v-slots={{
                icon: () => (
                  <Checkbox
                    modelValue={checked.value}
                    v-slots={{
                      icon: (props: any) => (
                        <Icon
                          class={styles.boxStyle}
                          name={
                            props.checked
                              ? activeButtonIcon
                              : inactiveButtonIcon
                          }
                          size="15"
                        />
                      )
                    }}
                  ></Checkbox>
                ),
                title: () => (
                  <div class={styles.container}>
                    <Image class={styles.memberLogo} src={iconDiscount} />
                    <div class={styles.info}>
                      <div class={styles.top}>
                        <div class={styles.title}>畅学卡</div>
                        <div class={styles.price}>
                          ¥{moneyFormat(discountDetail.value.salePrice)}/年
                        </div>
                      </div>
                      <div class={styles.center}>
                        <div class={styles.t}>
                          <span class={styles.dis}>
                            约课{discountDetail.value.discountRate}折
                          </span>
                          <span class={styles.text}>现在开通立即优惠</span>
                        </div>
                      </div>
                      <div class={styles.bottom}>x1</div>
                    </div>
                  </div>
                )
              }}
            />
          </CellGroup>

          {checked.value ? (
            <>
              <CellGroup class={['mb12', styles.cellGroup]} border={false}>
                <Cell
                  center
                  v-slots={{
                    title: () => (
                      <div class={styles.timerCell}>
                        <div class={styles.timerTitle}>
                          <span>畅学卡生效时间</span>
                        </div>
                        <div class={styles.timer}>
                          {params.startTime} 至 {params.endTime}
                        </div>
                      </div>
                    )
                  }}
                />
              </CellGroup>
              <CellGroup class={['mb12', styles.cellGroup]} border={false}>
                <Cell
                  center
                  v-slots={{
                    title: () => (
                      <div class={styles.timerCell}>
                        <div class={styles.timerTitle}>
                          <span>畅学卡优惠</span>
                        </div>
                        <div class={styles.timer}>-￥{params.discountPrice}</div>
                      </div>
                    )
                  }}
                />
              </CellGroup>
            </>
          ) : (
            ''
          )}
        </div>
      ) : (
        ''
      )
  }
})
