import MHeader from '@/components/m-header';
import { defineComponent, onMounted, reactive } from 'vue';
import {
  Button,
  Cell,
  CellGroup,
  Field,
  Image,
  Popup,
  Radio,
  RadioGroup,
  Tag,
  showToast
} from 'vant';
import styles from './index.module.less';
import iconRefunding from './images/icon_refunding.svg';
import icon_success from './images/icon_success.svg';
import iconClose from './images/icon_close.svg';
import iconTradeing from './images/icon_tradeing.svg';
import { useRoute, useRouter } from 'vue-router';
import { browser, moneyFormat } from '@/helpers/utils';
import { useEventListener, useWindowScroll } from '@vueuse/core';
import {
  api_userPaymentOrderCancelRefund,
  api_userPaymentOrderDetail,
  api_userPaymentOrderRefundDetail,
  api_userPaymentOrderRefundPayment
} from '../collection-record/api';
import * as detailState from '@/state';

export default defineComponent({
  name: 'collection-record-detail',
  setup() {
    const route = useRoute();
    const router = useRouter();
    // 判断是否是退款详情
    const isRefund = route.query.userRefundOrderId ? true : false;
    const state = reactive({
      refundAudit: '' as any, // 退款审核状态
      refundOrderId: '', // 退款订单id
      orders: {} as any,
      goodsInfos: [] as any,
      background: 'transparent',
      color: '#fff',
      backIconColor: 'white' as any,
      timer: null as any,
      timerCount: 0 // 执行次数
    });
    const getDetails = async () => {
      let res = null as any;
      try {
        // 退款详情
        if (isRefund) {
          res = await api_userPaymentOrderRefundDetail(
            route.query.userRefundOrderId
          );
        } else {
          // 订单详情
          res = await api_userPaymentOrderDetail(route.query.orderNo);
        }
      } catch {}
      if (res?.code !== 200) return;
      state.orders = res.data || {};
      const tempGoods =
        (isRefund ? res.data.studentRefundOrderDetails : res.data.goodsInfos) ||
        [];
      tempGoods.forEach((item: any) => {
        const img = item.goodsUrl ? item.goodsUrl.split(',')[0] : '';
        item.goodsUrl = img;
        item.brandName = item.brandName
          ? item.brandName
          : goodsType[item.goodsType];
      });
      state.goodsInfos = tempGoods;
      if (isRefund) {
        state.refundAudit = res.data.refundAudit || '';
        state.refundOrderId = res.data.userRefundOrderId || '';
        state.orders.status = state.refundAudit;
      }
    };

    // 定时任务
    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,
        ING: iconRefunding,
        REFUNDING: iconRefunding,
        REFUNDED: icon_success
      };
      return template[type] || icon_success;
    };

    const formatOrderStatus = (status: string) => {
      const temp: any = {
        WAIT_PAY: '支付中',
        PAYING: '支付中',
        PAID: '支付成功',
        TIMEOUT: '订单超时',
        FAIL: '支付失败',
        CLOSED: '已关闭',
        ING: '退款申请中',
        PASS: '已退款',
        REJECT: '退款失败',
        REFUNDING: '退款中',
        REFUNDED: '已退款'
      };
      return temp[status];
    };
    const goodsType: any = {
      VIP: '数字化乐器学练工具',
      INSTRUMENTS: '乐器购买',
      TEXTBOOK: '教材'
    };

    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';
        }
      });
    });

    /** 取消退款申请 */
    const handleBack = async () => {
      await api_userPaymentOrderCancelRefund(state.refundOrderId);
      showToast('撤销退款成功');
      await getDetails();
    };
    return () => (
      <div class={styles.paymentResult}>
        <div class={[styles.paymentTitle]}>
          <MHeader
            title={isRefund ? '申请退款' : '订单详情'}
            background="transparent"
          />

          {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' ? (
                    <div class={styles.orderPrice}>
                      实付金额：￥ {moneyFormat(state.orders.paymentCashAmount)}
                    </div>
                  ) : null}

                  {['ING', 'PASS', 'REJECT', 'REFUNDED'].includes(
                    state.orders.status
                  ) && (
                    <div class={styles.orderPrice}>
                      退款金额：￥ {moneyFormat(state.orders.paymentCashAmount)}
                    </div>
                  )}
                  {['CLOSED'].includes(state.orders.status) && (
                    <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 || state.orders.refundTime || '--'}
                </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'
                        ? '12个月'
                        : goods.brandName}
                    </Tag>
                  </div>
                ),
                value: () => <span>x {goods.goodsNum}</span>
              }}
            </Cell>
          ))}
        </CellGroup>

        {state.refundAudit === 'ING' && (
          <Button
            class={styles.cancelBtn}
            block
            round
            type="primary"
            onClick={() => handleBack()}>
            撤销退款
          </Button>
        )}
      </div>
    );
  }
});
