import dayjs from 'dayjs'
import {
  ActionSheet,
  Button,
  Cell,
  CellGroup,
  DatePicker,
  Icon,
  Image,
  List,
  Picker,
  Popup,
  showConfirmDialog,
  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'
import OFullRefresh from '@/components/o-full-refresh'

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' }] as any,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false,
        refreshing: false,
        height: props.height || 0 // 页面头部高度，为了处理下拉刷新用的
      },
      params: {
        paymentStatus: ['WAIT_PAY', 'PAYING'],
        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 onCancelOrder = async (item: any) => {
      showConfirmDialog({
        message: '您是否关闭该订单',
        cancelButtonText: '取消',
        confirmButtonText: '确定'
      }).then(async () => {
        try {
          await request.post('/api-student/userPaymentOrder/cancelPayment/' + item.orderNo, {
            hideLoading: false
          })
          onSearch()
        } catch {
          //
        }
      })
    }

    const onConfirmOrder = async (item: any) => {
      try {
        const { data } = await request.get('/api-student/userPaymentOrder/unpaid', {
          hideLoading: false,
          params: {
            orderNo: item.orderNo,
            paymentType: item.orderType
          }
        })

        const paymentConfig = data.paymentConfig
        router.push({
          path: '/orderDetail',
          query: {
            config: JSON.stringify(paymentConfig.paymentConfig),
            orderNo: paymentConfig.orderNo
          }
        })
      } catch {
        //
      }
    }

    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) - 1.17333rem)',
            overflow: 'hidden',
            overflowY: 'auto'
          }}
        >
          {form.listState.dataShow ? (
            <OFullRefresh
              v-model:modelValue={form.listState.refreshing}
              onRefresh={() => onSearch(false)}
              style={{
                minHeight: 'calc(100vh -  var(--van-tabs-line-height) - 1.17333rem)'
              }}
            >
              <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 center clickable={false} 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>
                    <Cell>
                      {{
                        value: () => (
                          <div class={styles.btnGroup}>
                            <Button
                              plain
                              round
                              size="small"
                              color="#777777"
                              class={styles.smallBtn}
                              onClick={(e: any) => {
                                e.stopPropagation()
                                onCancelOrder(item)
                              }}
                            >
                              取消订单
                            </Button>
                            <Button
                              plain
                              round
                              size="small"
                              type="primary"
                              class={styles.smallBtn}
                              onClick={(e: any) => {
                                e.stopPropagation()
                                onConfirmOrder(item)
                              }}
                            >
                              继续支付
                            </Button>
                          </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']}
            onConfirm={(date: any) => {
              form.currentData = date.selectedValues
              form.timeShow = false
              onSearch()
            }}
            onCancel={() => (form.timeShow = false)}
          />
        </Popup>

        <ActionSheet
          v-model:show={form.typeShow}
          actions={form.typeArray}
          cancelText="取消"
          teleport={'body'}
          onSelect={(val: any) => {
            form.currentType = val.value
            form.typeShow = false
            onSearch()
          }}
        />
      </div>
    )
  }
})
