<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { Page, SubmitButton } from '@vben/common-ui';

import { Button, message, notification } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { tianyibiApi } from '#/api/posting';
import { useSysStore } from '#/store';

const sysStore = useSysStore();

interface RowType {
  id: number;
  source: number;
  orderSn: string;
  orderOldId: string;
  tel: string;
  fee: number;
  type: number;
  orderTime: string;
  useFlag: string;
}

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  wrapperClass: 'grid-cols-6',
  schema: [
    {
      component: 'RadioGroup',
      componentProps: {
        options: [
          {
            label: '未使用',
            value: '0',
          },
          {
            label: '已使用',
            value: '1',
          },
        ],
        optionType: 'button',
      },
      defaultValue: '0',
      fieldName: 'useFlag',
      label: '状态',
    },
    {
      component: 'Input',
      componentProps: {
        allowClear: true,
      },
      fieldName: 'tel',
      label: '手机号',
      defaultValue: '',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: sysStore.getDictList('source'),
      },
      fieldName: 'source',
      label: '来源',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: sysStore.getDictList('orderType').filter((item) => item.value !== '0'),
      },
      fieldName: 'type',
      label: '订单类型',
    },

    {
      component: 'RangePicker',
      componentProps: {
        allowClear: true,
        placeholder: ['开始时间', '结束时间'],
        valueFormat: 'YYYY-MM-DD',
      },
      fieldName: 'orderTime',
      label: '订单时间',
      formItemClass: 'col-span-2',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  // 是否在字段值改变时提交表单
  submitOnChange: true,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

// 处理订单时间范围
const handleFormValues = (values: any) => {
  const { orderTime, ...rest } = values;
  return orderTime && orderTime.length === 2
    ? {
        ...rest,
        startTime: orderTime[0],
        endTime: orderTime[1],
      }
    : {
        ...rest,
        startTime: '',
        endTime: '',
      };
};

const gridOptions: VxeTableGridOptions<RowType> = {
  columns: [
    { field: 'orderSn', title: '订单编号', width: 250 },
    {
      field: 'source',
      title: '来源',
      formatter: ({ cellValue }) => {
        return sysStore.getDictMap('source', cellValue);
      },
    },
    { field: 'tel', title: '手机号' },
    { field: 'fee', title: '金额' },
    {
      field: 'type',
      title: '类型',
      formatter: ({ cellValue }) => {
        return sysStore.getDictMap('orderType', cellValue);
      },
    },
    { field: 'orderTime', title: '订单时间', formatter: 'formatDateTime', minWidth: 160 },
    {
      title: '操作',
      slots: {
        default: 'action',
      },
    },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  rowConfig: {
    isHover: true,
  },
  pagerConfig: {
    enabled: true,
  },
  proxyConfig: {
    response: {
      result: 'records',
      list: 'records',
      total: 'total',
    },
    ajax: {
      query: async ({ page }, formValues) => {
        const params = handleFormValues(formValues);
        return await tianyibiApi.getPointOrdersList({
          page: page.currentPage,
          limit: page.pageSize,
          source: params.source || '',
          type: params.type || '',
          ...params,
        });
      },
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

async function onStartAutoMatch() {
  const hide = message.loading('系统自动匹配天医币消耗中...', 0);
  await tianyibiApi.autoConsumeTianyibi();
  hide();
  notification.success({
    message: '自动匹配天医币消耗成功',
  });
  // 刷新表格数据
  gridApi?.query();
}

async function onConsumption(row: RowType, code: number) {
  const api = code === 1 ? tianyibiApi.manualConsumeTianyibi : tianyibiApi.cancelConsumeTianyibi;
  await api({ orderId: row.id });
  notification.success({
    message: code === 1 ? '确认消耗成功' : '取消消耗成功',
  });
  // 刷新表格数据
  gridApi?.query();
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <div class="flex gap-2">
          <!-- <Button type="primary" @click="onStartAutoMatch()">启动自动匹配消耗</Button> -->
          <SubmitButton theme="ant-design" :submit="onStartAutoMatch" text="启动自动匹配消耗" />
        </div>
      </template>
      <template #action="{ row }">
        <Button v-if="!row.useFlag" type="primary" size="small" @click="onConsumption(row, 1)">
          确认消耗
        </Button>
        <Button v-else type="primary" danger ghost size="small" @click="onConsumption(row, 0)">
          取消消耗
        </Button>
      </template>
    </Grid>
  </Page>
</template>
