import { apiClient } from '@/api';
import type {
  ApiCardInfoWalmartGroupExportGetPageSizeEnum,
  ApiCardInfoWalmartGroupStatGetPageSizeEnum,
  KamiApiCardInfoWalmartV1V1CardRedeemAccountGroupEntity,
  KamiApiSysUserV1UserGetAllSimpleUser
} 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,
  Space,
  Option,
  Table,
  Tag,
  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;
  name: string | null;
}

export default defineComponent({
  name: 'walmartGroupSummary',
  setup() {
    const generateFormModel = (): IformData => {
      return {
        name: null,
        username: '',
        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: 'createdUserName'
      },
      {
        title: '分组名称',
        dataIndex: 'groupName',
        render({ record }) {
          return record.groupName || '未分组';
        }
      },
      {
        title: '账户情况',
        dataIndex: 'account',
        render({ record }) {
          return (
            <>
              <Space size='small'>
                <span>
                  正常账户：
                  <Tag color='green' size='small'>
                    {record.account.normal || 0}
                  </Tag>
                </span>
                <span>
                  异常账户：
                  <Tag color='red' size='small'>
                    {record.account.unNormal || 0}
                  </Tag>
                </span>
                <span>
                  删除账户：
                  <Tag color='red' size='small'>
                    {record.account.deleted || 0}
                  </Tag>
                </span>
              </Space>
            </>
          );
        }
      },
      {
        title: '充值金额',
        dataIndex: 'sum'
      },
      {
        title: '充值笔数',
        dataIndex: 'count'
      },
      {
        title: '充值日期',
        dataIndex: 'orderDate',
        render({ record }) {
          return new Date(record.orderDate).toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
          });
        }
      }
    ];
    const tableData = ref<
      KamiApiCardInfoWalmartV1V1CardRedeemAccountGroupEntity[]
    >([]);

    const downloadExcel = () => {
      apiClient
        .apiCardInfoWalmartGroupExportGet(
          {
            current: pagination.current,
            pageSize:
              pagination.pageSize as ApiCardInfoWalmartGroupExportGetPageSizeEnum,
            username: formModel.value.username,
            date: formModel.value.date,
            userId: formModel.value.userId,
            name: formModel.value.name
          },
          {
            responseType: 'blob'
          }
        )
        .then(res => {
          // 判断是不是blob类型
          if (!res.data) {
            Message.error('下载账户统计明细失败');
            return;
          }
          handleDownLoadFile(res.data as any, '沃尔玛分组统计.xlsx');
        });
    };
    const fetchData = (page: Pagination = pagination) => {
      apiClient
        .apiCardInfoWalmartGroupStatGet({
          current: page.current,
          pageSize: page.pageSize as ApiCardInfoWalmartGroupStatGetPageSizeEnum,
          username: formModel.value.username,
          date: formModel.value.date,
          userId: formModel.value.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.name}
                        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>
      </>
    );
  }
});
