import {
  PropType,
  computed,
  defineComponent,
  onMounted,
  reactive,
  watch
} from 'vue';
import {
  IApiUserPaymentOrderPage,
  api_userPaymentOrderPage,
  api_userPaymentOrderStudentRefundOrderPage,
  type_OrderStatus
} from '../api';
import Item from './item';
import MFullRefresh from '@/components/m-full-refresh';
import { Button, DatePicker, List, Popup, showToast } from 'vant';
import MEmpty from '@/components/m-empty';
import ItemSkelete from './item-skelete';
import icon_arrow from '../image/icon_arrow.svg';
import styles from './list.module.less';
import { usePageVisibility } from '@vant/use';
import { listenerMessage } from '@/helpers/native-message';

export default defineComponent({
  name: 'collection-record-list',
  props: {
    orderStatus: {
      type: String,
      default: ''
    },
    refundIndex: {
      type: Number,
      default: 0
    }
  },
  emits: ['refund'],
  setup(props, { emit }) {
    const time = new Date();
    const data = reactive({
      page: 1,
      dateTime: [
        time.getFullYear().toString(),
        (time.getMonth() + 1).toString().padStart(2, '0')
      ],
      minDate: new Date(time.getFullYear(), 0, 1),
      maxDate: new Date(time.getFullYear() + 10, 5, 1),

      list: [],
      skelete: true,
      refreshing: false,
      finished: false,
      loading: false,

      dataOpen: false
    });
    const statusTypes: { [_: string]: string } = {
      WAIT_PAY: '待领取',
      PAYING: '待领取',
      PAID: '领取成功',
      CLOSED: '已关闭',
      REFUNDED: '退回成功'
    };
    const statusColors: { [_: string]: string } = {
      WAIT_PAY: 'rgba(64, 196, 203, 1)',
      PAYING: 'rgba(64, 196, 203, 1)',
      PAID: 'rgba(28, 172, 241, 1)',
      CLOSED: 'rgba(170, 170, 170, 1)',
      ING: 'rgba(153, 153, 153, 1)',
      REJECT: 'rgba(255, 90, 86, 1)',
      PASS: 'rgba(255, 162, 68, 1)',
      REFUNDED: 'rgba(255, 162, 68, 1)'
    };
    const refundTypes: { [_: string]: string } = {
      ING: '退回申请中',
      REJECT: '退回失败',
      PASS: '退回成功',
      CLOSED: '退回关闭'
    };
    const getList = async () => {
      data.loading = true;
      let res = {} as any;
      if (props.orderStatus === 'REFUNDED') {
        res = await api_userPaymentOrderStudentRefundOrderPage({
          page: data.page,
          rows: 10,
          refundMonth: data.dateTime.join('-')
        });
        if (res?.code === 200 && Array.isArray(res?.data?.rows)) {
          data.list = res.data.rows.map((item: any) => {
            return {
              ...item,
              paymentCashAmount: item.paymentCashAmount?.toFixed(2) || '0.00',
              createTime: item.refundTime,
              statusName: refundTypes[item.refundAudit],
              statusColor: statusColors[item.refundAudit],
              isRefund: true // 是退款列表
            };
          });
          data.finished = !res.data.next;
          data.page = data.page + 1;
        }
      } else {
        try {
          res = await api_userPaymentOrderPage({
            page: data.page,
            rows: 10,
            orderStatus: props.orderStatus as any,
            payMonth: data.dateTime.join('-')
          });
        } catch (error) {}

        if (res?.code === 200 && Array.isArray(res?.data?.rows)) {
          data.list = res.data.rows.map((item: any) => {
            return {
              ...item,
              paymentCashAmount: item.paymentCashAmount?.toFixed(2) || '0.00',
              createTime: item.payTime,
              statusName: statusTypes[item.status],
              statusColor: statusColors[item.status]
            };
          });
          data.finished = !res.data.next;
          data.page = data.page + 1;
        }
      }

      setTimeout(() => {
        data.refreshing = false;
      }, 500);
      data.loading = false;
      data.skelete = false;
    };

    watch(
      () => props.refundIndex,
      () => handlStart()
    );
    onMounted(() => {
      getList();
      listenerMessage('webViewOnResume', () => handlStart());
    });

    const handlStart = () => {
      data.finished = false;
      data.page = 1;
      getList();
    };

    const timeName = computed(() => {
      return `${data.dateTime[0]}年${data.dateTime[1]}月`;
    });
    return () => (
      <>
        <MFullRefresh
          modelValue={data.refreshing}
          onRefresh={() => {
            data.refreshing = true;
            console.log('下拉');
            handlStart();
          }}>
          <Button
            class={styles.downBtn}
            size="small"
            round
            onClick={() => (data.dataOpen = true)}>
            <div>{timeName.value}</div>
            {/* <img
              class={[styles.downIcon, data.dataOpen ? styles.upIcon : '']}
              src={icon_arrow}
            /> */}

            <svg
              class={[styles.downIcon, data.dataOpen ? styles.upIcon : '']}
              width="9px"
              height="5px"
              viewBox="0 0 9 5"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg">
              <title>三角形</title>
              <g
                id="页面-1"
                stroke="currentColor"
                stroke-width="1"
                fill="currentColor"
                fill-rule="evenodd">
                <g
                  id="领取记录-待领取"
                  transform="translate(-99.000000, -155.000000)"
                  fill="currentColor">
                  <g id="编组-2" transform="translate(13.000000, 144.000000)">
                    <g
                      id="筛选目录备份"
                      transform="translate(12.000000, 3.000000)">
                      <path
                        d="M78.8716471,8.41294119 L82.2489659,12.1655176 C82.4336954,12.3707726 82.4170562,12.6869176 82.2118012,12.8716471 C82.1199888,12.9542782 82.0008397,13 81.8773188,13 L75.1226812,13 C74.8465388,13 74.6226812,12.7761424 74.6226812,12.5 C74.6226812,12.3764791 74.668403,12.25733 74.7510341,12.1655176 L78.1283529,8.41294119 C78.3130824,8.20768618 78.6292274,8.19104698 78.8344824,8.37577649 C78.8475136,8.38750459 78.859919,8.39990996 78.8716471,8.41294119 Z"
                        id="三角形"
                        transform="translate(78.500000, 10.500000) rotate(-180.000000) translate(-78.500000, -10.500000) "></path>
                    </g>
                  </g>
                </g>
              </g>
            </svg>
          </Button>
          {data.skelete && new Array(5).fill(1).map(i => <ItemSkelete />)}

          {data.list.length !== 0 && (
            <List
              loading={data.loading}
              finished={data.finished}
              finishedText=" ">
              {data.list.map(item => {
                return (
                  <Item
                    item={item}
                    onClose={() => handlStart()}
                    onRefund={() => emit('refund')}
                  />
                );
              })}
            </List>
          )}

          {!data.skelete && data.list.length === 0 && (
            <MEmpty description="暂无记录" />
          )}
        </MFullRefresh>
        <Popup
          teleport="body"
          v-model:show={data.dataOpen}
          position="bottom"
          round>
          <DatePicker
            v-model={data.dateTime}
            columnsType={['year', 'month']}
            minDate={data.minDate}
            maxDate={data.maxDate}
            onConfirm={() => {
              data.dataOpen = false;
              console.log(data.dateTime);
              handlStart();
            }}
            onCancel={() => (data.dataOpen = false)}
          />
        </Popup>
      </>
    );
  }
});
