import MHeader from '@/components/m-header';
import { defineComponent, onMounted, reactive } from 'vue';
import { Button, Cell, CellGroup, Image, 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 iconTips from './images/icon-tips.png';
import request from '@/helpers/request';
import { useRoute, useRouter } from 'vue-router';
import { browser, moneyFormat } from '@/helpers/utils';
import { useEventListener, useWindowScroll } from '@vueuse/core';

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(
          '/edu-app/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 formatImg = (type: any) => {
      const template: any = {
        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: any = {
        WAIT_PAY: '支付中',
        PAYING: '支付中',
        PAID: '支付成功',
        TIMEOUT: '订单超时',
        FAIL: '支付失败',
        CLOSED: '订单关闭',
        REFUNDING: '退款中',
        REFUNDED: '已退款'
      };
      return temp[status];
    };

    onMounted(async () => {
      await getDetails();
      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 && (
            <MHeader
              border={false}
              background={state.background}
              color={state.color}
            />
          )}

          {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>

        {state.orders.orderType === 'SCHOOL_REGISTER' ? (
          <CellGroup inset class={[styles.cellGroup, styles.mTop]}>
            <div class={styles.tips}>
              <img src={iconTips} class={styles.iconTips} />
              <span>
                请下载“<i>音乐数字课堂APP</i>”，按提示登录即可
              </span>
              <Button
                plain
                class={styles.btnDownload}
                onClick={() => {
                  router.push('/download');
                }}>
                去下载
              </Button>
            </div>
          </CellGroup>
        ) : (
          ''
        )}

        <CellGroup
          inset
          class={[
            styles.cellGroup,
            state.orders.orderType !== 'SCHOOL_REGISTER' ? 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>
          </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 class={styles.brandName}>
                      {state.orders.orderType === 'VIP' ||
                      goods.goodsType === 'VIP'
                        ? '12个月'
                        : goods.brandName}
                    </Tag>
                  </div>
                ),
                value: () => <span>x {goods.goodsNum}</span>
              }}
            </Cell>
          ))}
        </CellGroup>
      </div>
    );
  }
});
