import dayjs from 'dayjs'
import {
  Button,
  Cell,
  CellGroup,
  DatePicker,
  Dialog,
  Field,
  Icon,
  Image,
  List,
  Picker,
  Popup,
  Radio,
  RadioGroup,
  showToast,
  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 ODialog from '@/components/o-dialog'
import { forms } from '@/school/train-planning/create'
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,
      resionList: [] as any,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        paymentStatus: ['PAID', 'TIMEOUT', 'FAIL', 'CLOSED'],
        page: 1,
        rows: 20
      },
      refundStatus: false,
      resion: null,
      refundSelect: {} as any,
      checked: null as any
    })

    // WAIT_PAY: '待支付',
    // PAYING: '支付中',
    // PAID: '已付款',
    // TIMEOUT: '订单超时',
    // FAIL: '支付失败',
    // CLOSED: '订单关闭',
    // REFUNDING: '退款中',
    // REFUNDED: '已退款'

    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 getDefaultParams = async () => {
      try {
        const { data } = await request.get('/api-student/sysParamConfig/queryByParamName', {
          params: {
            paramName: 'refund_reason'
          }
        })
        const temp = data.paramValue.split('\n') || []
        temp.forEach((item: any, index: number) => {
          form.resionList.push({
            text: item,
            value: index + 1
          })
        })
        form.resionList.push({
          text: '其它原因',
          value: 999
        })
        console.log(form.resionList, 'resionList')
      } catch {
        //
      }
    }

    // 确认退费
    const onConfirmRefund = async () => {
      try {
        const status = form.checked === 999 && !form.resion
        console.log(form.checked)
        if (!form.checked) {
          showToast('请选择原因')
          return
        } else if (status) {
          showToast('请输入原因')
          return
        }

        const refundReason = form.resionList.find((item: any) => item.value === form.checked)

        await request.post('/api-student/userPaymentOrder/refundPayment', {
          data: {
            merOrderNo: form.refundSelect.orderNo,
            refundReason: form.checked === 999 ? form.resion : refundReason.text
          }
        })

        form.refundStatus = false
        onSearch()
      } catch {
        //
      }
    }

    const onDetails = (item: any) => {
      router.push({
        path: 'payment-result',
        query: {
          orderNo: item.orderNo
        }
      })
    }

    onMounted(() => {
      getList()
      getDefaultParams()

      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 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 style={'padding: 0'}>
                  {{
                    title: () =>
                      item.refundable && (
                        <Button
                          block
                          class={styles.refundBtn}
                          onClick={(e: any) => {
                            e.stopPropagation()
                            form.refundSelect = item
                            form.refundStatus = true
                          }}
                        >
                          申请退费
                        </Button>
                      )
                  }}
                </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>

        <Popup v-model:show={form.refundStatus} round style={{ width: '90%' }}>
          <div class={styles.container}>
            <div class={styles.dialogTitle}>
              <i></i>
              申请退款
            </div>

            <div class={styles.refundContent}>
              <div class={styles.tips}>
                您将要发起退款，退款需承担千分之六的手续费，确认退款后款项将原路返还到您的付款账户中。
              </div>

              <div class={styles.refundTitle}>
                <span>*</span>请选择您的退款原因
              </div>

              <RadioGroup v-model={form.checked}>
                {form.resionList &&
                  form.resionList.map((item: any) => (
                    <Cell style="padding: 16px 0;" onClick={() => (form.checked = item.value)}>
                      {{
                        icon: () => <Radio name={item.value} />,
                        title: () => <span style={'padding-left: 6px'}>{item.text}</span>
                      }}
                    </Cell>
                  ))}
              </RadioGroup>
              {form.checked === 999 && (
                <Field
                  class={styles.phoneName}
                  v-model={form.resion}
                  placeholder="请输入原因"
                  maxlength={50}
                  type="textarea"
                  rows={2}
                />
              )}
            </div>

            <div class={['van-hairline--top van-dialog__footer']}>
              <Button
                onClick={onConfirmRefund}
                class={['van-button van-button--default van-button--large van-dialog__cancel']}
              >
                确认退款
              </Button>
              <Button
                onClick={() => (form.refundStatus = false)}
                class={[
                  'van-button van-button--default van-button--large van-dialog__confirm van-hairline--left'
                ]}
              >
                取消
              </Button>
            </div>
          </div>
        </Popup>
      </>
    )
  }
})
