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

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

import dayjs from 'dayjs';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { importBillsApi } from '#/api/posting';

import FileBox from './components/FileBox.vue';

interface RowType {
  year: string;
  month: string;
  id: string;
  wechatFile: string;
  alipayFile: string;
  bankFile: string;
}

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  wrapperClass: 'grid-cols-6',
  schema: [
    {
      component: 'DatePicker',
      componentProps: {
        allowClear: false,
        picker: 'year',
        valueFormat: 'YYYY',
      },
      defaultValue: `${dayjs().year()}`,
      fieldName: 'year',
      label: '年份',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: Array.from({ length: 12 }, (_, i) => ({
          label: `${i + 1}月`,
          value: `${i + 1}`,
        })),
        placeholder: '请选择',
      },
      fieldName: 'month',
      label: '月份',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  // 是否在字段值改变时提交表单
  submitOnChange: true,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

const gridOptions: VxeTableGridOptions<RowType> = {
  columns: [
    {
      title: '日期',
      slots: {
        default: 'date',
      },
    },
    {
      field: 'wechatFile',
      title: '微信',
      slots: {
        default: 'wechat-file',
      },
    },
    {
      field: 'alipayFile',
      title: '支付宝',
      slots: {
        default: 'alipay-file',
      },
    },
    {
      field: 'bankFile',
      title: '银行',
      slots: {
        default: 'bank-file',
      },
    },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  rowConfig: {
    isHover: true,
  },
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    response: {
      result: 'importList',
      list: 'importList',
    },
    ajax: {
      query: async (_, formValues) => {
        return await importBillsApi.getImportFileList({
          ...formValues,
        });
      },
    },
  },
};

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

// 处理上传成功事件，刷新列表
function handleUploadSuccess() {
  gridApi?.query();
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #date="{ row }"> {{ row.year }}年{{ row.month }}月 </template>
      <template #wechat-file="{ row }">
        <FileBox :row="row" field="wechatFile" type="0" @upload-success="handleUploadSuccess" />
      </template>
      <template #alipay-file="{ row }">
        <FileBox :row="row" field="alipayFile" type="1" @upload-success="handleUploadSuccess" />
      </template>
      <template #bank-file="{ row }">
        <FileBox :row="row" field="bankFile" type="2" @upload-success="handleUploadSuccess" />
      </template>
    </Grid>
  </Page>
</template>
