import dayjs from 'dayjs'
import {
  ActionSheet,
  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 { formatterDatePicker, moneyFormat } from '@/helpers/utils'
import { useRouter } from 'vue-router'
import OFullRefresh from '@/components/o-full-refresh'
import OActionSheet from '@/components/o-action-sheet'

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: [{ name: '全部', value: 'ALL', selected: true }] as any,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false,
        refreshing: false,
        height: props.height || 0 // 页面头部高度，为了处理下拉刷新用的
      },
      params: {
        paymentStatus: ['REFUNDING', 'REFUNDED'],
        page: 1,
        rows: 20
      }
    })

    const getList = async (hideLoading = false) => {
      try {
        if (form.isClick) return
        form.isClick = true
        const res = await request.post('/api-student/userPaymentOrder/page', {
          // hideLoading: hideLoading,
          data: {
            ...form.params,
            orderType: form.currentType === 'ALL' ? null : form.currentType,
            paymentYear: form.currentData[0]
          }
        })
        form.listState.loading = false
        form.listState.refreshing = 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.refreshing = false
        form.listState.finished = true
        form.isClick = false
      }
    }

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

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

    onMounted(() => {
      getList()

      Object.keys(orderType).forEach((key) => {
        form.typeArray.push({
          name: orderType[key],
          value: key
        })
      })
    })
    return () => (
      <div>
        {/* <div class={styles.searchGroup}>
          <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> */}
        <div class={'searchGroup'}>
          <div
            class={['searchItem', form.timeShow && 'searchItem-active']}
            onClick={() => (form.timeShow = true)}
          >
            <span>{form.currentData[0]}年</span>
            <i class="arrow"></i>
          </div>
          <div
            class={['searchItem', form.typeShow && 'searchItem-active']}
            onClick={() => (form.typeShow = true)}
          >
            <span>{formatOrderType(form.currentType)}</span>
            <i class="arrow"></i>
          </div>
        </div>

        <div
          style={{
            height:
              'calc(100vh -  var(--van-tabs-line-height) - var(--header-height) - 1.17333rem)',
            overflow: 'hidden',
            overflowY: 'auto'
          }}
        >
          {form.listState.dataShow ? (
            <OFullRefresh
              v-model:modelValue={form.listState.refreshing}
              onRefresh={() => onSearch(true)}
              style={{
                minHeight:
                  'calc(100vh -  var(--van-tabs-line-height) - var(--header-height) - 1.17333rem)'
              }}
            >
              <List
                // v-model:loading={form.listState.loading}
                finished={form.listState.finished}
                finishedText=" "
                class={[styles.liveList]}
                onLoad={getList}
                style={{ paddingTop: '12px' }}
                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>
            </OFullRefresh>
          ) : (
            <OEmpty btnStatus={false} tips="暂无订单" />
          )}
        </div>

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

        <OActionSheet
          v-model:show={form.typeShow}
          actions={form.typeArray}
          teleport={'body'}
          onSelect={(val: any) => {
            form.typeArray.forEach((child: any) => {
              child.selected = false
            })
            val.selected = true
            form.currentType = val.value
            form.typeShow = false
            onSearch()
          }}
        />
      </div>
    )
  }
})
