import {
  type PaymentRecord,
  type PaymentLogRecord,
  queryUserPaymentRecordsList
} from '@/api/sys-user-payment';
import useLoading from '@/hooks/loading';
import type { Pagination } from '@/types/global';
import { getTokenFrom } from '@/utils/auth';
import {
  Drawer,
  Table,
  type TableData,
  type TableColumnData,
  Tag,
  Badge,
  RadioGroup,
  Radio,
  Space
} from '@arco-design/web-vue';
import {
  computed,
  defineComponent,
  onMounted,
  ref,
  type PropType,
  watch
} from 'vue';

const { loading, setLoading } = useLoading(false);
import style from './css/style.module.less';

export const PaymentRecordTable = defineComponent({
  name: 'userPaymentTable',
  props: {
    userId: {
      type: String,
      Default: ''
    },
    size: {
      type: String as PropType<'mini' | 'medium' | 'large' | 'small'>,
      Default: 'medium'
    },
    transactionType: {
      type: String,
      Default: ''
    }
  },
  setup(props) {
    const tableData = ref<PaymentLogRecord[]>([]);
    const pagination = ref<Pagination>({
      current: 1,
      pageSize: 10,
      total: 0
    });
    const columns: TableColumnData[] = [
      {
        title: '序号',
        render: (data: { rowIndex: number }) => {
          return data.rowIndex + 1;
        }
      },
      {
        title: '金额',
        dataIndex: 'amount'
        // render: (data: { record: TableData }) => {
        //   switch (data.record.transactionType) {
        //     case 'deposit':
        //       return `+${data.record.amount}`;
        //     case 'consumption':
        //       return `-${data.record.amount}`;
        //     case 'Manual Adjustment':
        //       return `${-data.record.amount}`;
        //     case 'deduction_return':
        //       return `+${data.record.amount}`;
        //     default:
        //       return `${data.record.amount}`;
        //   }
        // }
      },
      {
        title: '类型',
        dataIndex: 'transactionType',
        render: (data: { record: TableData; rowIndex: number }) => {
          switch (data.record.transactionType) {
            case 'deposit':
              return <Badge text='充值' color='green'></Badge>;
            case 'consumption':
              return <Badge text='消费' color='arcoblue'></Badge>;
            case 'Manual Adjustment':
              return <Badge text='扣除' color='orange'></Badge>;
            case 'deduction_return':
              return <Badge text='退款' color='orange'></Badge>;
            default:
              return <Badge text='未知' color='grey'></Badge>;
          }
        }
      },
      {
        title: '关联订单',
        dataIndex: 'orderNo'
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: (data: { record: TableData; rowIndex: number }) =>
          data.record.status === 'success' ? (
            <Tag size='small' color='green'>
              成功
            </Tag>
          ) : (
            <Tag size='small' color='red'>
              失败
            </Tag>
          )
      },
      {
        title: '分类',
        dataIndex: 'category',
        render: (data: { record: TableData }) => {
          switch (data.record.category) {
            case 'jd':
              return <Badge color='orangered' text='京东' />;
            case 'apple':
              return <Badge color='lime' text='苹果' />;
            case 'walmart':
              return <Badge color='lime' text='沃尔玛' />;
            default:
              return <Badge color='purple' text='' />;
          }
        }
      },
      {
        title: '备注',
        dataIndex: 'notes'
      },
      {
        title: '时间',
        dataIndex: 'createdAt'
      }
    ];
    const queryData = (userId: string, transactionType: string) => {
      queryUserPaymentRecordsList({
        userId: userId,
        current: pagination.value.current,
        pageSize: pagination.value.pageSize,
        transactionType: transactionType
      })
        .then(res => {
          setLoading(true);
          tableData.value = res.data.list;
          pagination.value.total = res.data.total;
        })
        .finally(() => setLoading(false));
    };
    watch(
      () => props.userId,
      () => {
        pagination.value.current = 1;
        queryData(props.userId, props.transactionType);
      }
    );
    watch(
      () => props.transactionType,
      () => {
        pagination.value.current = 1;
        queryData(props.userId, props.transactionType);
      }
    );
    onMounted(() => {
      if (getTokenFrom() === 'login') {
        queryData(props.userId, props.transactionType);
      }
    });
    return () => (
      <Table
        data={tableData.value}
        columns={columns}
        loading={loading.value}
        size={props.size}
        bordered={false}
        pagination={{
          pageSize: pagination.value.pageSize,
          current: pagination.value.current,
          total: pagination.value.total,
          showPageSize: true,
          pageSizeOptions: [10, 15, 20, 50, 100]
        }}
        onPageChange={(page: number) => {
          pagination.value.current = page;
          queryData(props.userId, props.transactionType);
        }}
        onPageSizeChange={(pageSize: number) => {
          pagination.value.pageSize = pageSize;
          queryData(props.userId, props.transactionType);
        }}
      />
    );
  }
});

export default defineComponent({
  name: 'userPaymentDrawer',
  props: {
    item: {
      type: Object as PropType<PaymentRecord>,
      Default: null
    },
    visible: {
      type: Boolean,
      Default: false
    }
  },
  emits: {
    'update:visible': (_visible: boolean) => true
  },
  setup(props, { emit }) {
    const visible = computed(() => props.visible);
    const state = ref({
      transcationType: ''
    });
    // 分页
    return () => (
      <div>
        <Drawer
          visible={visible.value}
          title='充值/消费流水'
          width='60%'
          footer={false}
          onCancel={() => emit('update:visible', false)}
        >
          <Space direction='vertical' size='medium' fill>
            <div class={style.radio}>
              <RadioGroup
                v-model={state.value.transcationType}
                size='small'
                type='button'
              >
                <Radio value=''>全部</Radio>
                <Radio value='deposit'>充值</Radio>
                <Radio value='consumption'>消费</Radio>
                <Radio value='Manual Adjustment'>扣除</Radio>
              </RadioGroup>
            </div>
            <PaymentRecordTable
              userId={props.item?.userId}
              transactionType={state.value.transcationType}
            />
          </Space>
        </Drawer>
      </div>
    );
  }
});
