import ColHeader from '@/components/col-header'
import { Button, Cell, CellGroup, Col, Image, Popup, Row } from 'vant'
import { defineComponent } from 'vue'
import styles from './trade-detail.module.less'
import { goodsType } from '@/constant'

import iconTeacher from '@common/images/icon_teacher.png'
import request from '@/helpers/request'
import Payment from '../order-detail/payment'
import { orderStatus } from '../order-detail/orderStatus'
import { state } from '@/state'

export const getAssetsHomeFile = (fileName: string) => {
  const path = `./images/${fileName}`
  const modules = import.meta.globEager('./images/*')
  return modules[path].default
}

// WAIT_PAY 待支付 PAYING 支付中 PAID 已付款 CLOSE 已关闭 FAIL 支付失败
type orderType = 'WAIT_PAY' | 'PAYING' | 'PAID' | 'CLOSE' | 'FAIL'

export default defineComponent({
  name: 'tradeDetail',
  data() {
    const query = this.$route.query
    return {
      type: (query.type as string) || 'ING',
      path: query.path, // 来源
      orderNo: query.orderNo || '',
      paymentStatus: false,
      order: {
        ING: {
          img: getAssetsHomeFile('icon_paying.png'),
          background: '#FF802C',
          title: '支付中'
        },
        SUCCESS: {
          img: getAssetsHomeFile('icon_success.png'),
          background:
            state.projectType === 'tenant' ? '#FF5461' : 'var(--van-primary)',
          title: '支付成功'
        },
        FAILED: {
          img: getAssetsHomeFile('icon_close.png'),
          background: '#BDBDBD',
          title: '支付失败'
        },
        CLOSE: {
          img: getAssetsHomeFile('icon_close.png'),
          background: '#BDBDBD',
          title: '订单关闭'
        }
      },
      result: {} as any,
      loading: true,
      timerOut: null as any,
      timer: 3
    }
  },
  computed: {
    orderDetailList() {
      const result: any = this.result
      const orderDetailList = result.orderDetailList || []
      orderDetailList.forEach((item: any) => {
        let tempPrice = item?.expectPrice || item.actualPrice
        if (item?.couponAmount) {
          tempPrice = Number((tempPrice / item.goodNum).toFixed(2))
        } else {
          tempPrice = Number(tempPrice / item.goodNum).toFixed(2)
        }

        item.showPrice = tempPrice || 0
      })

      return orderDetailList || []
    }
  },
  async mounted() {
    setTimeout(async () => {
      this.loading = true
      this.orderNo && (await this.getOrder())
      this.loading = false

      this.type === 'ING' && this.path !== 'tradeRecord' && this.interval()
    }, 0)
  },
  unmounted() {
    clearInterval(this.timerOut)
  },
  methods: {
    onRePay() {
      orderStatus.orderInfo = {
        orderNo: this.result.orderNo,
        actualPrice: this.result.actualPrice,
        payStatus: true
      }
      this.paymentStatus = true
      this.interval()
    },
    interval() {
      let countTime = 0
      this.timerOut = setInterval(async () => {
        countTime === 25 && clearInterval(this.timerOut)
        await this.getOrder(true)
        countTime++
      }, 5000)
    },
    async getOrder(status?: true) {
      try {
        const urlFix =
          state.platformType === 'TEACHER' ? '/api-teacher' : '/api-student'
        const res = await request.get(
          `${urlFix}/open/userOrder/detailByOrderNo/${this.orderNo}`,
          {
            hideLoading: status
          }
        )
        this.result = res.data
        // WAIT_PAY 待支付 PAYING 支付中 PAID 已付款 CLOSE 已关闭 FAIL 支付失败
        this.type = this.formatType(this.result.status)
        this.type !== 'ING' && clearInterval(this.timerOut)
      } catch {}
    },
    formatType(type: orderType) {
      let str = 'PAYING'
      switch (type) {
        case 'WAIT_PAY':
        case 'PAYING':
          str = 'ING'
          break
        case 'PAID':
          str = 'SUCCESS'
          break
        case 'CLOSE':
          str = 'CLOSE'
          break
        case 'FAIL':
          str = 'FAILED'
          break
        default:
          str = 'ING'
          break
      }
      return str
    }
  },
  render() {
    return (
      <div class={[styles.tradeDetail, styles[this.type]]}>
        {!this.loading && (
          <>
            <ColHeader
              background={this.order[this.type].background}
              color="#fff"
              title="交易详情"
              backIconColor="white"
              border={false}
            />

            <div
              class={[
                styles.orderType,
                state.projectType === 'tenant' && styles.orderTypeTenant
              ]}
            >
              <p>
                <Image
                  class={styles.orderImg}
                  src={this.order[this.type].img}
                  fit="cover"
                />
                <span>{this.order[this.type].title}</span>
              </p>
            </div>

            <CellGroup
              border={false}
              class={[
                styles.orderContent,
                state.projectType === 'tenant' && styles.orderContentTenant,
                'mb12'
              ]}
            >
              <Cell
                v-slots={{
                  title: () => (
                    <div class={styles.payPrice}>
                      <span>￥</span>
                      {(this as any).$filters.moneyFormat(
                        this.result.actualPrice
                      )}
                    </div>
                  )
                }}
              />

              {this.orderDetailList.map((item: any) => (
                <Cell
                  border={false}
                  style={{ paddingBottom: '15px' }}
                  class={styles.goodsItem}
                  v-slots={{
                    icon: () => (
                      <Image
                        class={styles.tradeLogo}
                        src={item.goodUrl || iconTeacher}
                        fit="contain"
                      />
                    ),
                    title: () => (
                      <div class={styles.title}>
                        <span>{item.goodName}</span>
                        <span class={styles.desc}>
                          {goodsType[item.goodType]}
                        </span>
                      </div>
                    ),
                    default: () => (
                      <div class={styles.content}>
                        {item.giftFlag ? (
                          <span class={styles.price}>赠送</span>
                        ) : (
                          <span class={styles.price}>
                            ￥
                            {(this as any).$filters.moneyFormat(item.showPrice)}
                          </span>
                        )}

                        <span class={styles.num}>x{item.goodNum}</span>
                      </div>
                    )
                  }}
                />
              ))}

              {this.result.couponAmount > 0 && (
                <Row class={styles.optionRow}>
                  <Col span="8" offset={1}>
                    优惠金额:
                  </Col>
                  <Col span="14">
                    ￥
                    {(this as any).$filters.moneyFormat(
                      this.result.couponAmount
                    )}
                  </Col>
                  <Col span="1"> </Col>
                </Row>
              )}

              <Row class={styles.optionRow}>
                <Col span="8" offset={1}>
                  订单号:
                </Col>
                <Col span="14">{this.result.orderNo}</Col>
                <Col span="1"> </Col>
              </Row>
              <Row class={styles.optionRow}>
                <Col span="8" offset={1}>
                  交易流水号:
                </Col>
                <Col span="14">{this.result.transNo}</Col>
                <Col span="1"> </Col>
              </Row>
              <Row class={styles.optionRow}>
                <Col span="8" offset={1}>
                  创建时间:
                </Col>
                <Col span="14">{this.result.createTime}</Col>
                <Col span="1"> </Col>
              </Row>
              <Row class={styles.optionRow}>
                <Col span="8" offset={1}>
                  付款时间:
                </Col>
                <Col span="14">{this.result.payTime}</Col>
                <Col span="1"> </Col>
              </Row>
            </CellGroup>

            {/* {this.type === 'ING' && this.path === 'tradeRecord' && (
              <div class="btnGroup">
                <Button type="primary" round block onClick={this.onRePay}>
                  重新支付
                </Button>
              </div>
            )}

            <Popup
              show={this.paymentStatus}
              closeOnClickOverlay={false}
              position="bottom"
              round
              closeOnPopstate
              safeAreaInsetBottom
              style={{ minHeight: '30%' }}
            >
              <Payment
                v-model={this.paymentStatus}
                orderInfo={orderStatus.orderInfo}
              />
            </Popup> */}
          </>
        )}
      </div>
    )
  }
})
