<!-- 搜索表单 -->
<template>
  <a-space :size="10" style="flex-wrap: wrap">
    <a-button type="primary" class="ele-btn-icon" @click="add">
      <template #icon>
        <PlusOutlined />
      </template>
      <span>添加</span>
    </a-button>
    <a-button
      danger
      type="primary"
      class="ele-btn-icon"
      :disabled="selection?.length === 0"
      @click="removeBatch"
    >
      <template #icon>
        <DeleteOutlined/>
      </template>
      <span>批量删除</span>
    </a-button>
    <a-input-search
      allow-clear
      placeholder="请输入关键词搜索"
      style="width: 240px"
      v-model:value="where.keywords"
      @search="reload"
    />
    <a-button type="text" @click="reset">重置</a-button>
    <a-button type="text" @click="handleExport">导出xls</a-button>
    <a-button type="text" @click="openImport">导入xls</a-button>
  </a-space>

  <!-- 导入弹窗 -->
  <import v-model:visible="showImport" @done="reload"/>
</template>

<script lang="ts" setup>
import {DeleteOutlined, PlusOutlined} from '@ant-design/icons-vue';
import {ref} from 'vue';
import {message} from 'ant-design-vue';
import {utils, writeFile} from 'xlsx';
import {listShopDealerUser} from '@/api/shop/shopDealerUser';
import type {ShopDealerUser, ShopDealerUserParam} from '@/api/shop/shopDealerUser/model';
import useSearch from '@/utils/use-search';
import dayjs from 'dayjs';
import Import from "./Import.vue";

const props = withDefaults(
  defineProps<{
    // 选中的数据
    selection?: ShopDealerUser[];
  }>(),
  {}
);

// 请求状态
const loading = ref(false);
const dealerUserList = ref<ShopDealerUser[]>([]);
// 是否显示导入弹窗
const showImport = ref(false);

// 表单数据
const {where, resetFields} = useSearch<ShopDealerUserParam>({
  id: undefined,
  keywords: ''
});

const emit = defineEmits<{
  (e: 'search', where?: ShopDealerUserParam): void;
  (e: 'add'): void;
  (e: 'remove'): void;
  (e: 'batchMove'): void;
}>();

// 新增
const add = () => {
  emit('add');
};

// 批量删除
const removeBatch = () => {
  emit('remove');
};

// 批量更新
const updateBatch = () => {
  emit('batchMove');
}

/* 打开导入弹窗 */
const openImport = () => {
  showImport.value = true;
};

const reload = () => {
  emit('search', where);
};

// 导出
const handleExport = async () => {
  if (loading.value) {
    return;
  }

  loading.value = true;
  message.loading('正在准备导出数据...', 0);

  try {
    const array: (string | number)[][] = [
      [
        '用户ID',
        '姓名',
        '手机号',
        '可提现佣金',
        '冻结佣金',
        '累计提现',
        '推荐人ID',
        '一级成员数',
        '二级成员数',
        '三级成员数',
        '专属二维码',
        '状态',
        '创建时间',
        '更新时间'
      ]
    ];

    // 按搜索结果导出
    const list = await listShopDealerUser(where);
    dealerUserList.value = list;

    if (!list || list.length === 0) {
      message.warning('没有数据可以导出');
      loading.value = false;
      return;
    }

    list.forEach((d: ShopDealerUser) => {
      array.push([
        `${d.userId || ''}`,
        `${d.realName || ''}`,
        `${d.mobile || ''}`,
        `${d.money || '0'}`,
        `${d.freezeMoney || '0'}`,
        `${d.totalMoney || '0'}`,
        `${d.refereeId || ''}`,
        `${d.firstNum || 0}`,
        `${d.secondNum || 0}`,
        `${d.thirdNum || 0}`,
        `${d.qrcode || ''}`,
        `${d.isDelete === 1 ? '已删除' : '正常'}`,
        `${d.createTime || ''}`,
        `${d.updateTime || ''}`
      ]);
    });

    const sheetName = `导出分销商用户列表${dayjs(new Date()).format('YYYYMMDD')}`;
    const workbook = {
      SheetNames: [sheetName],
      Sheets: {}
    };
    const sheet = utils.aoa_to_sheet(array);
    workbook.Sheets[sheetName] = sheet;

    // 设置列宽
    sheet['!cols'] = [
      {wch: 10}, // 用户ID
      {wch: 15}, // 姓名
      {wch: 15}, // 手机号
      {wch: 12}, // 可提现佣金
      {wch: 12}, // 冻结佣金
      {wch: 12}, // 累计提现
      {wch: 10}, // 推荐人ID
      {wch: 10}, // 一级成员数
      {wch: 10}, // 二级成员数
      {wch: 10}, // 三级成员数
      {wch: 20}, // 专属二维码
      {wch: 8},  // 状态
      {wch: 20}, // 创建时间
      {wch: 20}  // 更新时间
    ];

    message.destroy();
    message.loading('正在生成Excel文件...', 0);

    setTimeout(() => {
      writeFile(workbook, `${sheetName}.xlsx`);
      loading.value = false;
      message.destroy();
      message.success(`成功导出 ${list.length} 条记录`);
    }, 1000);

  } catch (error: any) {
    loading.value = false;
    message.destroy();
    message.error(error.message || '导出失败，请重试');
  }
};

/*  重置 */
const reset = () => {
  resetFields();
  reload();
};
</script>
