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: '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
      return result.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}/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}>
              <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, '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' }}
                  v-slots={{
                    icon: () => (
                      <Image
                        class={styles.tradeLogo}
                        src={item.goodUrl || iconTeacher}
                        fit="cover"
                      />
                    ),
                    title: () => (
                      <div class={styles.title}>
                        <span>{item.goodName}</span>
                        <span class={styles.desc}>
                          {goodsType[item.goodType]}
                        </span>
                      </div>
                    ),
                    default: () => (
                      <div class={styles.content}>
                        <span class={styles.price}>
                          ￥
                          {(this as any).$filters.moneyFormat(item.expectPrice)}
                        </span>
                        <span class={styles.num}>x{1}</span>
                      </div>
                    )
                  }}
                />
              ))}

              <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>
    )
  }
})
