import OEmpty from '@/components/o-empty'
import { orderStatus } from '@/constant'
import { moneyFormat } from '@/helpers/utils'
import {
  Button,
  Cell,
  CellGroup,
  Field,
  Grid,
  GridItem,
  Image,
  List,
  Popup,
  Radio,
  RadioGroup,
  showToast
} from 'vant'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '@/helpers/request'
import styles from '../index.module.less'

export default defineComponent({
  name: 'order',
  emits: ['next'],
  setup() {
    const router = useRouter()
    const route = useRoute()
    const form = reactive({
      isClick: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      params: {
        page: 1,
        rows: 20
      },
      resionList: [] as any,
      refundStatus: false,
      resion: null,
      refundSelect: {} as any,
      checked: null as any
    })

    // userPaymentOrder/page
    const getList = async () => {
      try {
        if (form.isClick) return
        form.isClick = true
        const res = await request.post('/api-student/userPaymentOrder/page', {
          data: {
            ...form.params,
            bizId: route.query.id,
            goodsQuery: true
          }
        })
        form.listState.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (form.list.length > 0 && result.current === 1) {
          return
        }
        const rows = result.rows || []
        rows.goodsInfos &&
          rows.goodsInfos.forEach((item: any) => {
            const img = item.goodsUrl ? item.goodsUrl.split(',')[0] : ''
            item.goodsUrl = img
          })
        form.list = form.list.concat(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 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)
        console.log({
          merOrderNo: form.refundSelect.orderNo,
          refundReason: form.checked === 999 ? form.resion : refundReason.text
        })
        // return
        await request.post('/api-student/userPaymentOrder/refundPayment', {
          data: {
            merOrderNo: form.refundSelect.orderNo,
            refundReason: refundReason.text
          }
        })
        form.refundStatus = false
        onSearch()
      } catch {
        //
      }
    }

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

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

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

    return () => (
      <div style={{ paddingTop: '20px' }}>
        {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.orderCellGroup} onClick={() => onDetails(item)}>
                <Cell
                  title={item.createTime}
                  titleClass={styles.payTime}
                  value={orderStatus[item.status]}
                  valueClass={
                    item.status === 'WAIT_PAY'
                      ? styles.payStatus
                      : item.status === 'PAID'
                      ? styles.paySuccess
                      : ''
                  }
                ></Cell>
                <Cell border={false} class={styles.imgGroup}>
                  {{
                    title: () => (
                      <Grid border={false}>
                        {item.goodsInfos &&
                          item.goodsInfos.map((goods: any) => (
                            <GridItem>
                              <Image class={styles.img} src={goods.goodsUrl} />
                            </GridItem>
                          ))}
                      </Grid>
                    )
                  }}
                </Cell>
                <Cell class={styles.btnGroup} center>
                  {{
                    title: () => (
                      <span class={styles.btnPrice}>¥{moneyFormat(item.currentPrice)}</span>
                    ),
                    value: () => (
                      <div class={styles.btns}>
                        {/* {item.status === 'WAIT_PAY' && (
                          <>
                            <Button round plain color="#AAAAAA">
                              修改订单
                            </Button>
                            <Button round plain color="#FF8057">
                              继续支付
                            </Button>
                          </>
                        )} */}
                        {/* 订单成功 订单金额大于0 */}
                        {item.refundable && (
                          <Button
                            round
                            plain
                            color="#AAAAAA"
                            onClick={(e: any) => {
                              e.stopPropagation()
                              form.refundSelect = item
                              form.refundStatus = true
                            }}
                          >
                            申请退款
                          </Button>
                        )}
                      </div>
                    )
                  }}
                </Cell>
              </CellGroup>
            ))}
          </List>
        ) : (
          <OEmpty btnStatus={false} classImgSize="SMALL" tips="暂无订单" />
        )}

        <Popup v-model:show={form.refundStatus} round style={{ width: '90%' }}>
          <div class={styles.container}>
            <div class={[styles.dialogTitle, styles.dialogRefund]}>
              <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>
      </div>
    )
  }
})
