<script lang="ts" setup>
import type { PaymentRowType } from './types';

import type { VbenFormProps } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { ref, watch } from 'vue';

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

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

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

import Manual from './modules/Manual.vue';

const sysStore = useSysStore();

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  // 设置每行最多显示4个表单项
  wrapperClass: 'grid-cols-6',
  schema: [
    {
      component: 'DatePicker',
      componentProps: {
        allowClear: false,
        picker: 'month',
        valueFormat: 'YYYY-MM',
      },
      defaultValue: dayjs().format('YYYY-MM'),
      fieldName: 'date',
      label: '日期',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: sysStore.getDictList('payment'),
        placeholder: '请选择',
      },
      fieldName: 'type',
      label: '支付方式',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        optionType: 'button',
        options: [
          {
            label: '全部',
            value: '',
          },
          ...sysStore.getDictList('checkoff'),
        ],
        placeholder: '请选择',
      },
      defaultValue: '',
      fieldName: 'checkoff',
      label: '核对状态',
      formItemClass: 'col-span-2',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  // 是否在字段值改变时提交表单
  submitOnChange: true,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

const gridOptions: VxeTableGridOptions<PaymentRowType> = {
  columns: [
    { type: 'checkbox', width: 60 },
    {
      field: 'type',
      title: '支付方式',
      minWidth: 80,
      formatter: ({ cellValue }) => {
        return sysStore.getDictMap('payment', cellValue);
      },
    },
    { field: 'fee', title: '金额', minWidth: 100 },
    { field: 'ctime', title: '时间', minWidth: 100, formatter: 'formatDateTime' },
    { field: 'transactionSn', title: '业务流水号', minWidth: 150 },
    { field: 'financeSn', title: '财务流水号', minWidth: 150 },
    { field: 'relationSn', title: '关联sn号', minWidth: 160 },
    { field: 'remark', title: '备注', minWidth: 120 },
    {
      field: 'checkoff',
      title: '状态',
      minWidth: 100,
      slots: { default: 'status' },
    },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '操作',
      width: 120,
    },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  rowConfig: {
    isHover: true,
  },
  pagerConfig: {
    enabled: true,
  },
  proxyConfig: {
    response: {
      result: 'records',
      total: 'total',
      list: 'records',
    },
    ajax: {
      query: async ({ page }, formValues) => {
        const date = formValues.date.split('-');
        delete formValues.date;
        return await reconciliateBillsApi.getReconciliationList({
          page: page.currentPage,
          limit: page.pageSize,
          year: date[0],
          month: date[1],
          type: formValues.type ?? '',
          ...formValues,
        });
      },
    },
  },
};

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

async function onStartSysCheck() {
  // 获取表单值
  const formValues = await gridApi?.formApi?.getValues();

  // 处理日期格式
  if (formValues?.date) {
    const date = formValues.date.split('-');
    const params = {
      year: date[0],
      month: date[1],
    };
    // 调用自动核对接口
    await reconciliateBillsApi.autoCheck(params);
    gridApi?.query();
    notification.success({
      message: '完成',
      description: '系统自动核对完成,核对失败的单据请人工核对。',
    });
  }
}

const selectData = ref<PaymentRowType[]>([]);
const manualDialogVisible = ref(false);

// 监听弹框关闭，刷新列表数据
watch(manualDialogVisible, (newVal) => {
  if (!newVal) {
    // 弹框关闭时刷新列表（保持在当前页）
    gridApi?.query();
  }
});
async function onManualCheck(data?: PaymentRowType) {
  // 如果没有传入数据，则获取选中的行
  if (data) {
    selectData.value = [data];
  } else {
    const selectedRows = await gridApi?.grid?.getCheckboxRecords();
    if (selectedRows.length === 0) {
      message.error('请先选择数据');
      return;
    }
    selectData.value = selectedRows;
  }
  // 处理selectData，checkoff状态为1才需要人工核对
  const originalLength = selectData.value.length;
  selectData.value = selectData.value.filter((item: PaymentRowType) => item.checkoff === 1);
  const filteredCount = originalLength - selectData.value.length;

  // 如果有数据被过滤掉，显示警告
  if (filteredCount > 0) {
    message.warning(`已过滤掉 ${filteredCount} 条不符合条件的数据`);
  }

  if (selectData.value.length === 0) {
    message.error('选择的数据中没有可进行人工对账的数据');
  } else {
    manualDialogVisible.value = true;
  }
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <div class="flex gap-2">
          <SubmitButton theme="ant-design" :submit="onStartSysCheck" text="启动系统自动对账" />
          <Button type="primary" @click="onManualCheck()">人工对账</Button>
        </div>
      </template>
      <template #action="{ row }">
        <Button v-if="row.checkoff === 1" type="primary" size="small" @click="onManualCheck(row)">
          人工对账
        </Button>
      </template>
      <template #status="{ row }">
        <Tag :color="sysStore.getDictByList('checkoff', row.checkoff).color || 'info'">
          {{ sysStore.getDictMap('checkoff', row.checkoff) }}
        </Tag>
      </template>
    </Grid>
    <Manual v-if="manualDialogVisible" v-model:show="manualDialogVisible" :data="selectData" />
  </Page>
</template>
