import { apiClient } from '@/api';
import type {
  KamiApiCardInfoWalmartV1CardRedeemAccountSummary,
  ApiCardInfoWalmartAccountDailySummaryGetPageSizeEnum,
  KamiApiSysUserV1UserGetAllSimpleUser,
  ApiCardInfoWalmartAccountSummaryDownloadGetPageSizeEnum
} from '@/api/generated';
import { handleDownLoadFile } from '@/api/utils';
import type { Pagination } from '@/types/global';
import {
  Button,
  Col,
  DatePicker,
  Divider,
  Form,
  FormItem,
  Input,
  Message,
  Row,
  Select,
  Option,
  Space,
  Table,
  type TableColumnData
} from '@arco-design/web-vue';
import { defineComponent, onMounted, reactive, ref } from 'vue';

interface IformData {
  accountId: string;
  username: string;
  date: string;
  userId: string | null;
  accountName: string | null;
}

export default defineComponent({
  name: 'walmartSummary',
  setup() {
    const generateFormModel = (): IformData => {
      return {
        username: '',
        accountName: null,
        accountId: '',
        date: null,
        userId: null
      };
    };

    const formModel = ref(generateFormModel());
    const basePagination: Pagination = {
      current: 1,
      pageSize: 50
    };
    const pagination = reactive({
      ...basePagination,
      pageSizeOptions: [10, 20, 50, 100],
      showPageSize: true
    });
    const columns: TableColumnData[] = [
      {
        title: '序号',
        render(data) {
          return data.rowIndex + 1;
        }
      },
      {
        title: '分组',
        dataIndex: 'groupName'
      },
      {
        title: '用户名',
        dataIndex: 'accountInfo.name'
      },
      {
        title: '余额',
        dataIndex: 'accountInfo.balance'
      },
      {
        title: '今日充值金额',
        dataIndex: 'amountTodaySum'
      },
      {
        title: '今日充值次数',
        dataIndex: 'amountTodayCount'
      },
      {
        title: '累计充值金额',
        dataIndex: 'amountTotalSum'
      },
      {
        title: '累计充值次数',
        dataIndex: 'amountTotalCount'
      },
      {
        title: '上传人',
        dataIndex: 'accountInfo.uploadUser.username'
      },
      {
        title: '日期',
        dataIndex: 'date',
        render({ record }) {
          return new Date(record.date).toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
          });
        }
      },
      {
        title: '是否还在',
        dataIndex: 'accountInfo.isActive',
        render({ record }) {
          return record.deletedAt ? '❌' : '✅';
        }
      }
    ];
    const tableData = ref<KamiApiCardInfoWalmartV1CardRedeemAccountSummary[]>(
      []
    );

    const downloadExcel = () => {
      apiClient
        .apiCardInfoWalmartAccountSummaryDownloadGet(
          {
            current: pagination.current,
            pageSize:
              pagination.pageSize as ApiCardInfoWalmartAccountSummaryDownloadGetPageSizeEnum,
            username: formModel.value.username,
            date: formModel.value.date
          },
          {
            responseType: 'blob'
          }
        )
        .then(res => {
          // 判断是不是blob类型
          if (!res.data) {
            Message.error('下载账户统计明细失败');
            return;
          }
          handleDownLoadFile(res.data as any, '沃尔玛账户统计明细.xlsx');
        });
    };
    const fetchData = (
      page: Pagination = pagination,
      params: IformData = formModel.value
    ) => {
      apiClient
        .apiCardInfoWalmartAccountDailySummaryGet({
          current: page.current,
          pageSize:
            page.pageSize as ApiCardInfoWalmartAccountDailySummaryGetPageSizeEnum,
          username: params.username,
          date: params.date,
          userId: params.userId
        })
        .then(res => {
          tableData.value = res.data.list;
          pagination.total = res.data.total;
        });
    };
    const reset = () => {
      formModel.value = generateFormModel();
    };
    const userList = ref<KamiApiSysUserV1UserGetAllSimpleUser[]>([]);

    // 获取所有分组
    const getAllUserList = () => {
      apiClient.apiUserGetSimpleAllGet().then(res => {
        userList.value = res.data.list;
      });
    };

    onMounted(() => {
      fetchData();
      getAllUserList();
    });

    return () => (
      <>
        <Space direction='vertical' fill>
          <Row>
            <Col flex={1}>
              <Form model={formModel}>
                <Row gutter={16}>
                  <Col span={8}>
                    <FormItem field='username' label='用户名'>
                      <Input
                        v-model={formModel.value.accountName}
                        placeholder='请输入用户名'
                      />
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem field='date' label='查询日期'>
                      <DatePicker v-model={formModel.value.date} />
                    </FormItem>
                  </Col>
                  <Col span={8}>
                    <FormItem field='userId' label='创建人'>
                      <Select v-model={formModel.value.userId} allow-clear>
                        {userList.value.map(item => (
                          <Option
                            key={item.id}
                            value={item.id}
                            label={item.userName}
                          />
                        ))}
                      </Select>
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Col>
            <Divider style='height: 42px' direction='vertical' />
            <Space direction='vertical' fill>
              <Row>
                <Col flex='172px' style='text-align: right'>
                  <Space direction='horizontal' size={18}>
                    <Button
                      type='primary'
                      onClick={() => fetchData()}
                      v-slots={{
                        icon: () => <icon-search />
                      }}
                    >
                      搜索
                    </Button>
                    <Button
                      onClick={reset}
                      v-slots={{
                        icon: () => <icon-refresh />
                      }}
                    >
                      重置
                    </Button>
                  </Space>
                </Col>
              </Row>
              <Row>
                <Col>
                  <Button
                    type='secondary'
                    status='warning'
                    onClick={() => downloadExcel()}
                    v-slots={{
                      icon: () => <icon-download />
                    }}
                  >
                    下载
                  </Button>
                </Col>
              </Row>
            </Space>
          </Row>
          <Divider style='margin-top: 0' />
          <Table
            columns={columns}
            data={tableData.value}
            pagination={pagination}
            onPageChange={(current: number) => {
              pagination.current = current;
              fetchData();
            }}
            onPageSizeChange={(pageSize: number) => {
              pagination.pageSize = pageSize;
              fetchData();
            }}
          />
        </Space>
      </>
    );
  }
});
