import request from '@/helpers/request'
import { state } from '@/state'
import { Cell, Popup } from 'vant'
import { defineComponent } from 'vue'
import ChoiceCoupon from './choice-coupon'
import styles from './index.module.less'

export default defineComponent({
  name: 'use-conpon',
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    orderAmount: {
      type: Number,
      default: 0
    },
    orderType: {
      type: String,
      default: ''
    },
    discountPrice: {
      // 优惠券使用金额
      type: Number,
      default: 0
    },
    useSystem: {
      type: String,
      default: 'MEC'
    },
    typeDetail: {
      type: String,
      default: ''
    }
  },
  emits: ['couponSelect'],
  data() {
    return {
      popupStatus: false,
      popupLoading: false,
      useCouponList: [] as any,
      useCouponLoading: false,
      useCouponCount: 0,
      dataLoading: false,
      list: [] as any
    }
  },
  computed: {
    couponCount() {
      const limitCount = this.useCouponList.map((list: any) => {
        return Number(list.faceValue || 0)
      })
      let count = 0
      if (this.disabled) {
        count = this.discountPrice
      } else {
        count =
          limitCount.length > 0
            ? limitCount.reduce((sum: any, list: any) => {
                return sum + list
              })
            : 0
      }
      return count
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    async getList() {
      console.log(this.orderAmount)
      if (this.dataLoading) return
      this.dataLoading = true
      try {
        const res = await request.get(
          `${state.platformApi}/sysCouponCode/queryPage`,
          {
            params: {
              useSystem: this.useSystem,
              typeDetail: this.typeDetail,
              usageStatus: 0,
              page: 1,
              rows: 100
            }
          }
        )
        this.dataLoading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (this.list.length > 0 && result.pageNo === 1) return
        this.list = result.rows || []

        // 处理可用优惠券是否支付使用
        this.list.forEach((item: any) => {
          item.checked = false
          // 如果使用金额大于订单金额则优惠券不可用
          if (item.fullAmount > this.orderAmount) {
            item.disabled = true
          } else {
            item.disabled = false
          }
        })

        let count = 0
        this.list.forEach((item: any) => {
          if (!item.disabled) {
            count++
          }
        })
        console.log(this.list, 'list')
        this.useCouponCount = count
      } catch {
        //
      }
    },
    // async getUseableCoupon() {
    //   try {
    //     this.useCouponLoading = true
    //     // 判断是哪个端
    //     const url =
    //       state.platformType === 'STUDENT' ? '/api-student' : '/api-teacher'
    //     const res = await request.get(`${url}/couponInfo/statInfo`)
    //     this.useCouponLoading = false
    //     const result = (res.data || []).find(
    //       result => result.useState === 'USABLE'
    //     )
    //     this.useCouponCount = result.total || 0
    //   } catch {
    //     // TODO: handle
    //   }
    // },
    onSubmit(item: any) {
      // useCouponList
      this.useCouponList = item
      this.$emit('couponSelect', item)
      this.popupStatus = false
      this.popupLoading = false
    }
  },
  render() {
    return (
      <>
        <Cell
          title="优惠券"
          class={styles.useCoupon}
          style={{ borderRadius: '8px' }}
          isLink={!this.disabled}
          clickable={false}
          v-slots={{
            value: () =>
              !this.useCouponLoading && (
                <>
                  {/* 判断是否有选择优惠券 */}
                  {this.couponCount > 0 ? (
                    <span class={styles.couponCount}>
                      <i>-￥</i>
                      {this.couponCount}
                    </span>
                  ) : (
                    <>
                      {/* 判断是否有可以的优惠券 */}
                      {this.useCouponCount > 0
                        ? `${this.useCouponCount}张可使用`
                        : '暂无可使用优惠券'}
                    </>
                  )}
                </>
              )
          }}
          onClick={() => {
            if (this.disabled) return
            this.popupStatus = true
            this.popupLoading = true
          }}
        ></Cell>

        <Popup
          v-model:show={this.popupStatus}
          position="bottom"
          round
          safeAreaInsetBottom={true}
          style={{ height: '75%' }}
          onClosed={() => {
            this.popupLoading = false
          }}
        >
          {/* 优化体验 */}
          {this.popupLoading && (
            <ChoiceCoupon
              useCoupon={this.useCouponList}
              orderAmount={this.orderAmount}
              couponList={this.list}
              onClose={() => (this.popupStatus = false)}
              onSubmit={(item: any) => this.onSubmit(item)}
            />
          )}
        </Popup>
      </>
    )
  }
})
