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: '已关闭'
    };
    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)'
    };
    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,
              createTime: item.refundTime,
              statusName: refundTypes[item.refundAudit],
              statusColor: statusColors[item.status],
              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,
              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} src={icon_arrow} />
          </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">
          <DatePicker
            v-model={data.dateTime}
            title="选择年月"
            columnsType={['year', 'month']}
            minDate={data.minDate}
            maxDate={data.maxDate}
            onConfirm={() => {
              data.dataOpen = false;
              console.log(data.dateTime);
              handlStart();
            }}
          />
        </Popup>
      </>
    );
  }
});
