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 { orderStatus } from '../../order-detail/orderStatus'
import { orderState } from '../shop-mall'

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

// 0, 6 待支付 2 支付中 CLOSE 已关闭 FAIL 支付失败
type orderType = 0 | 1 | 2 | 3 | 4 | 5 | 6

export default defineComponent({
  name: 'tradeDetail',
  data() {
    const query = this.$route.query
    return {
      type: (query.type as string) || 'ING',
      path: query.path, // 来源
      orderNo: query.orderNo || '',
      orderId: query.id || '',
      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.orderItemList || []
    }
  },
  async mounted() {
    setTimeout(async () => {
      this.loading = true
      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) {
      const url = this.orderId ? `/api-mall-portal/order/detail/${this.orderId}` : `/api-mall-portal/order/detail/sn/${this.orderNo}`
      try {
        const res = await request.get(
          url,
          {
            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: number) {
      let str = 'PAYING'
      console.log(orderState[type], type)
      switch (type) {
        case 0:
        case 6:
          str = 'ING'
          break
        case 1:
        case 2:
        case 3:
          str = 'SUCCESS'
          break
        case 4:
          str = 'CLOSE'
          break
        case 5:
          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.payAmount
                      )}
                    </div>
                  )
                }}
              />

              {this.orderDetailList.map((item: any) => (
                <Cell
                  border={false}
                  style={{ paddingBottom: '15px' }}
                  v-slots={{
                    icon: () => (
                      <Image
                        class={styles.tradeLogo}
                        src={item.productPic || iconTeacher}
                        fit="cover"
                      />
                    ),
                    title: () => (
                      <div class={styles.title}>
                        <span>{item.productName}</span>
                        <span class={styles.desc}>商品购买
                        </span>
                      </div>
                    ),
                    default: () => (
                      <div class={styles.content}>
                        <span class={styles.price}>
                          ￥
                          {(this as any).$filters.moneyFormat(item.productPrice)}
                        </span>
                        <span class={styles.num}>x{item.productQuantity}</span>
                      </div>
                    )
                  }}
                />
              ))}

              <Row class={styles.optionRow}>
                <Col span="8" offset={1}>
                  订单号:
                </Col>
                <Col span="14">{this.result.orderSn}</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.paymentTime}</Col>
                <Col span="1"> </Col>
              </Row>
            </CellGroup>
          </>
        )}
      </div>
    )
  }
})
