<template>
  <a-page-header :title="getPageTitle()" @back="() => $router.go(-1)">
    <a-card :bordered="false">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="applyId"
        :columns="columns"
        :datasource="datasource"
        class="sys-org-table"
        :scroll="{ x: 1300 }"
        :where="defaultWhere"
        :customRow="customRow"
        cache-key="proSystemShopDealerApplyTable"
      >
        <template #toolbar>
          <a-space>
            <a-button type="primary" class="ele-btn-icon" @click="openEdit()">
              <template #icon>
                <plus-outlined/>
              </template>
              <span>添加</span>
            </a-button>
            <a-button class="ele-btn-icon" @click="openImport()">
              <template #icon>
                <cloud-upload-outlined/>
              </template>
              <span>导入</span>
            </a-button>
            <!--            <a-button class="ele-btn-icon" @click="exportData()" :loading="exportLoading">-->
            <!--              <template #icon>-->
            <!--                <download-outlined/>-->
            <!--              </template>-->
            <!--              <span>导出</span>-->
            <!--            </a-button>-->
            <a-input-search
              allow-clear
              v-model:value="searchText"
              placeholder="请输入关键词"
              @search="reload"
              @pressEnter="reload"
            />
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'applyStatus'">
            <span class="text-green-500" v-if="record.applyStatus == 20">已入市</span>
            <span class="text-gray-300" v-else>未入市</span>
          </template>
          <template v-if="column.key === 'action'">
            <div>
              <a @click="openEdit(record)">修改</a>
              <a-divider type="vertical"/>
              <a-popconfirm
                placement="topRight"
                title="确定要删除此用户吗？"
                @confirm="remove(record)"
              >
                <a class="ele-text-danger">删除</a>
              </a-popconfirm>
            </div>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 编辑弹窗 -->
    <ShopDealerApplyEdit
      v-model:visible="showEdit"
      :data="current"
      :organization-list="data"
      @done="reload"
    />
    <!-- 导入弹窗 -->
    <ShopDealerApplyImport v-model:visible="showImport" @done="reload"/>

  </a-page-header>
</template>

<script lang="ts" setup>
import {ref, reactive, watch} from 'vue';
import {message} from 'ant-design-vue/es';
import {
  PlusOutlined,
  CloudUploadOutlined,
} from '@ant-design/icons-vue';
import type {EleProTable} from 'ele-admin-pro/es';
import type {
  DatasourceFunction,
  ColumnItem
} from 'ele-admin-pro/es/ele-pro-table/types';
import {messageLoading} from 'ele-admin-pro/es';
import ShopDealerApplyEdit from './components/shopDealerApplyEdit.vue';
import ShopDealerApplyImport from './components/shop-dealer-apply-import.vue';
import {toDateString} from 'ele-admin-pro';
import {utils, writeFile} from 'xlsx';
import dayjs from 'dayjs';
import {Organization} from '@/api/system/organization/model';
import {getPageTitle} from "@/utils/common";
import router from "@/router";
import {listShopDealerApply, pageShopDealerApply, removeShopDealerApply} from "@/api/shop/shopDealerApply";
import {ShopDealerApply, ShopDealerApplyParam} from "@/api/shop/shopDealerApply/model";

// 加载状态
const loading = ref(true);
// 树形数据
const data = ref<Organization[]>([]);
// 树展开的key
const expandedRowKeys = ref<number[]>([]);
// 树选中的key
const selectedRowKeys = ref<number[]>([]);
// 表格选中数据
const selection = ref<ShopDealerApply[]>([]);
// 当前编辑数据
const current = ref<ShopDealerApply | null>(null);
// 是否显示编辑弹窗
const showEdit = ref(false);
// 是否显示用户导入弹窗
const showImport = ref(false);
// 导出加载状态
const exportLoading = ref(false);
const searchText = ref('');

// 表格实例
const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
// 表格列配置
const columns = ref<ColumnItem[]>([
  // {
  //   title: 'ID',
  //   dataIndex: 'userId',
  //   width: 90,
  //   showSorterTooltip: false
  // },
  {
    title: '企业名称',
    dataIndex: 'dealerName',
    align: 'dealerName',
    showSorterTooltip: false
  },
  {
    title: '入市情况',
    dataIndex: 'applyStatus',
    key: 'applyStatus',
    align: 'center',
    sorter: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    sorter: true,
    align: 'center',
    showSorterTooltip: false,
    ellipsis: true,
    customRender: ({text}) => toDateString(text, 'yyyy-MM-dd HH:mm:ss')
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    fixed: 'right',
    align: 'center'
  }
]);

// 默认搜索条件
const defaultWhere = reactive({
  username: '',
  nickname: ''
});

// 表格数据源
const datasource: DatasourceFunction = ({
                                          page,
                                          limit,
                                          where,
                                          orders
                                        }) => {
  where = {};
  where.keywords = searchText.value;
  where.type = 3;
  return pageShopDealerApply({page, limit, ...where, ...orders});
};

/* 搜索 */
const reload = (where?: ShopDealerApplyParam) => {
  selection.value = [];
  tableRef?.value?.reload({where});
};

/* 打开编辑弹窗 */
const openEdit = (row?: ShopDealerApply) => {
  current.value = row ?? null;
  showEdit.value = true;
};
/* 打开编辑弹窗 */
const openImport = () => {
  showImport.value = true;
};

/* 导出数据 */
const exportData = async () => {
  exportLoading.value = true;

  try {
    // 定义表头
    const array: (string | number)[][] = [
      [
        'ID',
        '企业名称',
        '联系方式',
        '入市状态',
        '创建时间'
      ]
    ];

    // 构建查询参数，使用当前搜索条件
    const params = {
      keywords: searchText.value,
      isAdmin: 0
    };

    // 获取用户列表数据
    const list = await listShopDealerApply(params);

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

    // 将数据转换为Excel行
    list.forEach((user: ShopDealerApply) => {
      array.push([
        `${user.applyId || ''}`,
        `${user.realName || ''}`,
        `${user.mobile || ''}`,
        `${user.applyStatus === 20 ? '通过' : '未通过'}`,
        `${user.createTime || ''}`
      ]);
    });

    // 生成Excel文件
    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'] = [
    ];

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

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

  } catch (error: any) {
    exportLoading.value = false;
    message.error(error.message || '导出失败');
  }
};

/* 删除单个 */
const remove = (row: ShopDealerApply) => {
  const hide = messageLoading('请求中..', 0);
  removeShopDealerApply(row.applyId)
    .then((msg) => {
      hide();
      message.success(msg);
      reload();
    })
    .catch((e) => {
      hide();
      message.error(e.message);
    });
};

/* 自定义行属性 */
const customRow = (record: ShopDealerApply) => {
  return {
    // 行点击事件
    onClick: () => {
      // console.log(record);
    },
    // 行双击事件
    onDblclick: () => {
      openEdit(record);
    }
  };
};

watch(
  () => router.currentRoute.value.query,
  () => {},
  {immediate: true}
);
</script>

<script lang="ts">
export default {
  name: 'ShopDealerApplyRs'
};
</script>

