import dayjs from 'dayjs'
import { Button, Cell, CellGroup, DatePicker, Icon, Image, List, Picker, Popup, Sticky } from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import styles from '../index.module.less'
import iconOrder from '../images/icon_order.png'
import request from '@/helpers/request'
import OEmpty from '@/components/o-empty'
import { orderStatus, orderType } from '@/constant'
import { moneyFormat } from '@/helpers/utils'
import { useRouter } from 'vue-router'

export default defineComponent({
  name: 'wait_pay',
  props: {
    height: {
      type: Number,
      default: 50
    }
  },
  setup(props) {
    const router = useRouter()
    const form = reactive({
      isClick: false,
      timeShow: false,
      currentData: [dayjs().year() + ''],
      typeShow: false,
      currentType: 'ALL',
      typeArray: [{ text: '全部', value: 'ALL' }] as any,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        paymentStatus: ['REFUNDING', 'REFUNDED'],
        page: 1,
        rows: 20
      }
    })

    const getList = async () => {
      try {
        if (form.isClick) return
        form.isClick = true
        const res = await request.post('/api-student/userPaymentOrder/page', {
          data: {
            ...form.params,
            orderType: form.currentType === 'ALL' ? null : form.currentType,
            paymentYear: form.currentData[0]
          }
        })
        form.listState.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (form.list.length > 0 && result.current === 1) {
          return
        }
        form.list = form.list.concat(result.rows || [])
        form.listState.finished = result.current >= result.pages
        form.params.page = result.current + 1
        form.listState.dataShow = form.list.length > 0
        form.isClick = false
      } catch {
        form.listState.dataShow = false
        form.listState.finished = true
        form.isClick = false
      }
    }

    const onSearch = () => {
      form.params.page = 1
      form.list = []
      form.listState.dataShow = true // 判断是否有数据
      form.listState.loading = false
      form.listState.finished = false
      getList()
    }

    const formatOrderType = (orderType: string) => {
      let select = {} as any
      form.typeArray.forEach((item: any) => {
        if (item.value === orderType) {
          select = item
        }
      })
      return select.text
    }
    const onDetails = (item: any) => {
      router.push({
        path: 'payment-result',
        query: {
          orderNo: item.orderNo
        }
      })
    }

    onMounted(() => {
      getList()

      Object.keys(orderType).forEach((key) => {
        form.typeArray.push({
          text: orderType[key],
          value: key
        })
      })
    })
    return () => (
      <>
        <Sticky position="top" offsetTop={props.height}>
          <div style={{ padding: '12px 13px 16px', background: '#F8F8F8' }}>
            <div class={styles.searchBand} onClick={() => (form.timeShow = true)}>
              {form.currentData[0]}年 <Icon name={form.timeShow ? 'arrow-up' : 'arrow-down'} />
            </div>
            <div
              class={styles.searchBand}
              onClick={() => (form.typeShow = true)}
              style="margin-left: 16px"
            >
              {formatOrderType(form.currentType)}
              <Icon name={form.typeShow ? 'arrow-up' : 'arrow-down'} />
            </div>
          </div>
        </Sticky>

        {form.listState.dataShow ? (
          <List
            v-model:loading={form.listState.loading}
            finished={form.listState.finished}
            finishedText=" "
            class={[styles.liveList]}
            onLoad={getList}
            immediateCheck={false}
          >
            {form.list.map((item: any) => (
              <CellGroup inset class={styles.cellGroup} onClick={() => onDetails(item)}>
                <Cell center titleClass={styles.times}>
                  {{
                    title: () => <span class={styles.times}>{item.createTime}</span>,
                    value: () => <span class={styles.status}>{orderStatus[item.status]}</span>
                  }}
                </Cell>
                <Cell isLink clickable={false} center titleStyle={{ flex: '0 auto' }}>
                  {{
                    icon: () => <Image class={styles.img} src={iconOrder} />,
                    title: () => <span class={styles.name}>{orderType[item.orderType]}</span>,
                    value: () => (
                      <div class={styles.price}>
                        <span>¥</span>
                        {moneyFormat(item.paymentCashAmount)}
                      </div>
                    )
                  }}
                </Cell>
              </CellGroup>
            ))}
          </List>
        ) : (
          <OEmpty btnStatus={false} tips="暂无订单" />
        )}

        <Popup v-model:show={form.timeShow} position="bottom" round>
          <DatePicker
            v-model={form.currentData}
            columnsType={['year']}
            onConfirm={(date: any) => {
              form.currentData = date.selectedValues
              form.timeShow = false
              onSearch()
            }}
            onCancel={() => (form.timeShow = false)}
          />
        </Popup>

        <Popup v-model:show={form.typeShow} position="bottom" round>
          <Picker
            columns={form.typeArray}
            onCancel={() => (form.typeShow = false)}
            onConfirm={(val: any) => {
              form.currentType = val.selectedValues[0]
              form.typeShow = false
              onSearch()
            }}
          />
        </Popup>
      </>
    )
  }
})
