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

/*
 * 订单类型对应优惠券类型
 */
export const couponEnum = {
  UNIVERSAL: 'UNIVERSAL',
  VIP: 'VIP',
  SVIP: 'SVIP',
  PIANO_ROOM: 'PIANO',
  GOODS: 'MALL',
  MUSIC: 'MUSIC',
  VIP_COURSE: 'VIP_COURSE',
  DISCOUNT: 'DISCOUNT',
  PRACTICE: 'SPARRING',
  LIVE: 'LIVE',
  VIDEO: 'VIDEO',
  ALBUM: 'ALBUM'
}

export default defineComponent({
  name: 'use-conpon',
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    orderAmount: {
      type: Number,
      default: 0
    },
    orderType: {
      type: String,
      default: ''
    },
    orderGoodsType: {
      type: Array,
      default: () => []
    },
    discountPrice: {
      // 优惠券使用金额
      type: Number,
      default: 0
    },
    // 选择的优惠券
    couponId: {
      type: String,
      default: ''
    },
    usedLength: {
      type: String as PropType<'SINGLE' | 'MULTIPLE'>,
      default: 'SINGLE'
    }
  },
  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.discountPrice || 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
    },
    couponCategory() {
      // 如果订单类型不在优惠券类型里面，则默认查询通用券
      const temp: any[] = []
      this.orderGoodsType.forEach((item: any) => {
        if(couponEnum[item.orderType]) {
          temp.push(couponEnum[item.orderType])
        }
      })
      return  temp.join(',') + (temp.length ? ',UNIVERSAL' : 'UNIVERSAL')
    }
  },
  watch: {
    couponId(val: any) {
      // 为
      const ids = val ? val.split(',').map(i => Number(i)) : []
      const selectCouponList: any[] = []
      this.useCouponList.forEach((item: any) => {
        if(ids.includes(item.couponIssueId)) {
          selectCouponList.push(item)
        }
      });
      this.useCouponList = selectCouponList
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    resetCouponList() {
      this.list = []
      this.getList()
    },
    async getList() {
      if (this.dataLoading) return
      this.dataLoading = true
      try {
        const res = await request.post(`${state.platformApi}/couponInfo/page`, {
          data: {
            couponCategory: this.couponCategory,
            couponType: 'FULL_DISCOUNT',
            useState: 'USABLE',
            orderUse: 1,
            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.couponCategory === 'UNIVERSAL') {
            let disabled = true;
            this.orderGoodsType.forEach((goods: any) => {
              if(item.useLimit <= goods.price && disabled) {
                disabled = false
              }
            })
            item.disabled = disabled
          } else {
            const disItem: any = this.orderGoodsType.find((goods: any) => couponEnum[goods.orderType] === item.couponCategory)
            const useLastAmount = disItem.price || 0
            // 如果使用金额大于订单金额则优惠券不可用
            if (item.useLimit > useLastAmount) {
              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}
          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
              usedLength={this.usedLength}
              couponCategory={this.couponCategory}
              useCoupon={this.useCouponList}
              orderAmount={this.orderAmount}
              orderGoodsType={this.orderGoodsType}
              couponList={this.list}
              onClose={() => (this.popupStatus = false)}
              onSubmit={(item: any) => this.onSubmit(item)}
            />
          )}
        </Popup>
      </>
    )
  }
})
