import OHeader from '@/components/o-header'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import {
  Button,
  Cell,
  CellGroup,
  Field,
  Image,
  Popup,
  Radio,
  RadioGroup,
  showConfirmDialog,
  showToast,
  Tag
} from 'vant'
import styles from './index.module.less'
import iconRefunding from './images/icon_refunding.png'
import icon_success from './images/icon_success.png'
import iconClose from './images/icon_close.png'
import iconTradeing from './images/icon_tradeing.png'
import request from '@/helpers/request'
import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router'
import { orderStatus } from '@/constant'
import { browser, moneyFormat } from '@/helpers/utils'
import { useEventListener, useWindowScroll } from '@vueuse/core'
import { useRect } from '@vant/use'

export default defineComponent({
  name: 'payment-result',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      refund: route.query.refund,
      orders: {} as any,
      goodsInfos: [] as any,
      background: 'transparent',
      color: '#fff',
      backIconColor: 'white' as any,
      timer: null as any,
      timerCount: 0 // 执行次数
    })
    const form = reactive({
      resionList: [] as any,
      refundStatus: false,
      resion: null,
      refundSelect: {} as any,
      checked: null as any
    })
    const getDetails = async () => {
      try {
        if (!route.query.orderNo) return
        const { data } = await request.post(
          '/api-student/open/userOrder/paymentStatus/' + route.query.orderNo
        )

        state.orders = data || {}
        // state.orders.status = 'REFUNDED'
        const tempGoods = data.goodsInfos || []
        tempGoods.forEach((item: any) => {
          const img = item.goodsUrl ? item.goodsUrl.split(',')[0] : ''
          item.goodsUrl = img
        })
        state.goodsInfos = tempGoods
      } catch {
        //
      }
    }

    // 定时任务
    const onTimeout = async () => {
      // 判断订单状态，如果未支付则刷新
      if (['WAIT_PAY', 'PAYING'].includes(state.orders.status) && state.timerCount <= 10) {
        state.timer = setTimeout(async () => {
          state.timerCount += 1
          await getDetails()
          onTimeout()
        }, 3000)
      } else {
        clearTimeout(state.timer)
      }
    }

    const onRefund = async () => {
      showConfirmDialog({
        message: '您是否确定撤销退费?'
      }).then(async () => {
        try {
          await request.post('/api-student/userPaymentOrder/cancelRefund/' + route.query.orderNo, {
            hideLoading: false
          })
          getDetails()
        } catch {
          //
        }
      })
    }

    const formatImg = (type: any) => {
      const template = {
        WAIT_PAY: iconTradeing,
        PAYING: iconTradeing,
        PAID: icon_success,
        TIMEOUT: iconClose,
        FAIL: iconClose,
        CLOSED: iconClose,
        REFUNDING: iconRefunding,
        REFUNDED: icon_success
      }
      return template[type] || icon_success
    }

    const formatOrderStatus = (status: string) => {
      const temp = {
        WAIT_PAY: '支付中',
        PAYING: '支付中',
        PAID: '支付成功',
        TIMEOUT: '订单超时',
        FAIL: '支付失败',
        CLOSED: '订单关闭',
        REFUNDING: '退款中',
        REFUNDED: '已退款'
      }
      return temp[status]
    }

    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', {
          hideLoading: false,
          data: {
            merOrderNo: route.query.orderNo,
            refundReason: form.checked === 999 ? form.resion : refundReason.text
          }
        })

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

    // const popStateEvent = () => {
    //   const ua = window.navigator.userAgent.toLowerCase()
    //   if (browser().weixin) {
    //     // 关闭微信
    //     ;(window as any).WeixinJSBridge.call('closeWindow')
    //   } else if (ua.indexOf('alipay') != -1) {
    //     // 关闭支付宝
    //     ;(window as any).AlipayJSBridge.call('closeWebview') // 支付宝浏览器
    //   } else {
    //     router.back()
    //   }
    // }

    // onBeforeRouteLeave((leaveGuard: any) => {
    //   // 判断是否是微信
    //   alert(leaveGuard.path)
    //   if (browser().weixin && !['/preApply'].includes(leaveGuard.path)) {
    //     popStateEvent()
    //   }
    // })

    onMounted(async () => {
      await getDetails()
      getDefaultParams()
      await onTimeout()
      useEventListener(document, 'scroll', () => {
        const { y } = useWindowScroll()
        if (y.value > 52) {
          state.background = '#fff'
          state.color = '#323333'
          state.backIconColor = 'black'
        } else {
          state.background = 'transparent'
          state.color = '#fff'
          state.backIconColor = 'white'
        }
      })
    })
    return () => (
      <div class={styles.paymentResult}>
        <div class={styles.paymentTitle}>
          {browser().isApp && (
            <OHeader
              border={false}
              background={state.background}
              color={state.color}
              backIconColor={state.backIconColor}
            />
          )}

          {state.orders.id && (
            <>
              <div class={styles.orderType}>
                <Image class={styles.img} src={formatImg(state.orders.status)} />
                <div class={styles.orderInfo}>
                  <span>{formatOrderStatus(state.orders.status)}</span>
                  {state.orders.status === 'PAID' || state.orders.status === 'REFUNDING' ? (
                    <div class={styles.orderPrice}>
                      实付金额：￥ {moneyFormat(state.orders.paymentCashAmount)}
                    </div>
                  ) : (
                    ''
                  )}

                  {state.orders.status === 'REFUNDED' && (
                    <div class={styles.orderPrice}>
                      退款金额：￥ {moneyFormat(state.orders.paymentCashAmount)}
                    </div>
                  )}
                </div>
              </div>
            </>
          )}
        </div>

        <CellGroup inset class={[styles.cellGroup, styles.mTop]}>
          <Cell>
            {{ title: () => '付款时间', value: () => <span>{state.orders.payTime || '--'}</span> }}
          </Cell>
          <Cell>
            {{ title: () => '订单编号', value: () => <span>{state.orders.orderNo}</span> }}
          </Cell>
        </CellGroup>

        <CellGroup inset class={styles.cellGroup}>
          <div class={styles.buyDetail}>
            <div class={styles.buyDetailTitle}>
              <i></i> 购买详情
            </div>
            {/* {state.orders.refundable && state.refund === 'refund' ? (
              <div
                class={styles.refundBtn}
                onClick={() => {
                  form.refundStatus = true
                }}
              >
                申请退费
              </div>
            ) : (
              ''
            )} */}
          </div>
          {state.goodsInfos.map((goods: any) => (
            <Cell>
              {{
                icon: () => <Image class={styles.buyImg} src={goods.goodsUrl} />,
                title: () => (
                  <div class={styles.buyContent}>
                    <p class={styles.goodsTitle}>{goods.goodsName}</p>
                    <Tag
                      color="linear-gradient(135deg, #FF8C4A 0%, #FF531C 100%)"
                      textColor="#fff"
                      class={styles.brandName}
                    >
                      {goods.brandName}
                    </Tag>
                  </div>
                ),
                value: () => <span>{goods.goodsType === 'VIP' ? '6个月' : 'x 1'}</span>
              }}
            </Cell>
          ))}
        </CellGroup>

        {state.orders.status === 'REFUNDING' && browser().isApp && (
          <div class={'btnGroup'}>
            <Button type="primary" round block onClick={onRefund}>
              撤销退费
            </Button>
          </div>
        )}

        <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>
      </div>
    )
  }
})
