import { defineComponent, PropType } from 'vue'
import styles from './index.module.less'
import {
  ActionSheet,
  Cell,
  CellGroup,
  DatetimePicker,
  Icon,
  Popup,
  Sticky,
  Image,
  List,
  Button,
  Dialog,
  Toast
} from 'vant'
import { formatterDate } from '@/helpers/utils'
import { goodsType, orderType, returnType } from '@/constant'

import iconTeacher from '@common/images/icon_teacher.png'
import request from '@/helpers/request'
import dayjs from 'dayjs'
import ColResult from '@/components/col-result'
import { orderStatus } from '@/views/order-detail/orderStatus'
import { tradeOrder } from '../tradeOrder'

export default defineComponent({
  name: 'list',
  props: {
    type: {
      type: String as PropType<'buy' | 'refund'>,
      default: 'buy'
    },
    height: {
      type: Number,
      default: 44
    }
  },
  data() {
    return {
      timeStatus: false,
      currentDate: new Date(),
      typeStatus: false,
      // 订单状态 WAIT_PAY 待支付 PAYING 支付中 PAID 已付款 CLOSE 已关闭 FAIL 支付失败 （多选用,分割）
      actions: [
        { name: '全部' },
        { name: '待支付', status: 'WAIT_PAY' },
        { name: '支付中', status: 'PAYING' },
        { name: '已付款', status: 'PAID' },
        { name: '已关闭', status: 'CLOSE' },
        { name: '支付失败', status: 'FAIL' }
      ],
      list: [],
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      searchName: '全部',
      params: {
        status: '',
        page: 1,
        rows: 20
      }
    }
  },
  methods: {
    async getList() {
      if (this.loading) return
      this.loading = true
      try {
        const params = {
          ...this.params,
          searchDate: dayjs(this.currentDate).format('YYYY-MM')
        }

        const url =
          this.type === 'buy'
            ? '/api-student/userOrder/page'
            : '/api-student/userOrderRefunds/page'
        const { code, data } = await request.post(url, {
          data: {
            ...params,
            dateTime: this.type === 'refund' ? params.searchDate : undefined,
            timeType: this.type === 'refund' ? 'MONTH' : undefined
          }
        })
        if (code === 200) {
          const result = data || {}
          this.list = this.list.concat(result.rows || [])
          this.finished = result.pageNo >= result.totalPage
          this.params.page = result.pageNo + 1
          this.dataShow = this.list.length > 0
        }
      } catch {
        this.dataShow = false
        this.finished = true
      }
      this.loading = false
    },
    onDetail(item: any) {
      if (this.type === 'refund') return
      this.$router.push({
        path: '/tradeDetail',
        query: {
          orderNo: item.orderNo,
          path: 'tradeRecord'
        }
      })
    },
    onConfirm(date: Date) {
      this.currentDate = date
      this.timeStatus = false
      this.onSearch()
    },
    onSelect(item: any) {
      this.params.status = item.status
      this.searchName = item.name
      this.onSearch()
    },
    onSearch() {
      this.dataShow = true
      this.loading = false
      this.finished = false
      this.list = []
      this.params.page = 1
      this.getList()
    },
    async onCancelPay(item: any) {
      // orderPay: {
      //   cancelUrl: '/api-student/userOrder/orderCancel',
      //   payUrl: '/api-student/userOrder/orderPay'
      // }
      Dialog.confirm({
        message: '是否取消订单？',
        confirmButtonText: '确定',
        confirmButtonColor: 'var(--van-primary)',
        cancelButtonText: '取消'
      }).then(async () => {
        try {
          await request.post('/api-student/userOrder/orderCancel', {
            data: {
              orderNo: item.orderNo
            }
          })
          // Toast('取消成功')
          this.onSearch()
        } catch {}
      })
    },
    async onPay(item: any) {
      try {
        const res = await request.get(
          `/api-student/userOrder/detailByOrderNo/${item.orderNo}`
        )
        const result = res.data
        tradeOrder(result, () => {
          this.$router.push({
            path: '/orderDetail',
            query: {
              orderType: result.orderType
            }
          })
        })
      } catch {}
    }
  },
  render() {
    return (
      <div class={styles.tradeList}>
        <Sticky position="top" offsetTop={this.height}>
          <Cell
            center
            style={{ backgroundColor: '#F7F8F9' }}
            v-slots={{
              title: () => (
                <div
                  class={styles.searchTime}
                  onClick={() => {
                    this.timeStatus = true
                  }}
                >
                  <span>
                    {(this as any).$filters.dateFormat(
                      this.currentDate,
                      'YYYY-MM'
                    )}
                  </span>
                  <Icon
                    classPrefix="iconfont"
                    name="down"
                    size={12}
                    color="var(--van-primary)"
                  />
                </div>
              ),
              value: () => {
                if (this.type === 'buy') {
                  return (
                    <div
                      class={styles.searchType}
                      onClick={() => {
                        this.typeStatus = true
                      }}
                    >
                      <span>{this.searchName}</span>
                      <Icon
                        classPrefix="iconfont"
                        name="down"
                        size={12}
                        color="var(--van-primary)"
                      />
                    </div>
                  )
                }
                return null
              }
            }}
          ></Cell>
        </Sticky>
        {this.dataShow ? (
          <List
            loading={this.loading}
            finished={this.finished}
            finishedText=" "
            class={[styles.list]}
            onLoad={this.getList}
          >
            {this.list.map((item: any) => (
              <CellGroup
                border={false}
                onClick={() => {
                  this.onDetail(item)
                }}
              >
                <Cell
                  title={dayjs(item.createTime).format('YYYY-MM-DD HH:mm')}
                  value={
                    this.type === 'buy'
                      ? orderType[item.status]
                      : item.operateReason
                  }
                  valueClass={styles.tradeType}
                />
                <Cell
                  border={false}
                  v-slots={{
                    title: () => (
                      <div class={styles.title}>
                        <span>{item.orderName}</span>
                        <span class={styles.desc}>
                          {goodsType[item.orderType]}
                        </span>
                      </div>
                    ),
                    default: () => (
                      <div class={styles.content}>
                        <span class={styles.price}>
                          ￥
                          {this.type === 'buy'
                            ? (this as any).$filters.moneyFormat(
                                item.actualPrice
                              )
                            : (this as any).$filters.moneyFormat(
                                item.actualAmount
                              )}
                        </span>
                      </div>
                    )
                  }}
                />
                {item.status === 'PAYING' || item.status === 'WAIT_PAY' ? (
                  <div class={styles.btnList}>
                    <Button
                      size="small"
                      round
                      onClick={(e: any) => {
                        e.stopPropagation()
                        this.onCancelPay(item)
                      }}
                    >
                      取消订单
                    </Button>
                    <Button
                      size="small"
                      round
                      type="primary"
                      onClick={(e: any) => {
                        e.stopPropagation()
                        this.onPay(item)
                      }}
                    >
                      继续支付
                    </Button>
                  </div>
                ) : null}
              </CellGroup>
            ))}
          </List>
        ) : (
          <ColResult
            btnStatus={false}
            classImgSize="SMALL"
            tips={this.type === 'buy' ? '暂无购买记录' : '暂无退款记录'}
          />
        )}

        <Popup
          v-model:show={this.timeStatus}
          position="bottom"
          round
          closeOnPopstate
        >
          <DatetimePicker
            type="year-month"
            v-model={this.currentDate}
            formatter={formatterDate}
            onCancel={() => {
              this.timeStatus = false
            }}
            onConfirm={this.onConfirm}
          />
        </Popup>

        <ActionSheet
          v-model:show={this.typeStatus}
          actions={this.actions}
          closeOnClickAction
          cancelText="取消"
          onSelect={this.onSelect}
          onCancel={() => {
            this.typeStatus = false
          }}
        />
      </div>
    )
  }
})
