<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="orderId"
          :columns="columns"
          :datasource="datasource"
          :parse-data="parseData"
          v-model:selection="selection"
          :customRow="customRow"
          tool-class="ele-toolbar-form"
          :scroll="{ x: 1200 }"
          class="sys-org-table"
          :striped="true"
        >
          <template #toolbar>
            <search
              @search="reload"
              :selection="selection"
              :export-data="exportData"
              @remove="removeBatch"
              @done="handleExport"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'createTime'">
              {{ record.createTime }}
            </template>
            <template v-if="column.key === 'admin'"> 财务充值 </template>
            <template v-if="column.key === 'rechargeType'"> 管理员充值 </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a-button @click="openInfo(record)">详情</a-button>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
    <!-- 订单详情 -->
    <order-info v-model:visible="showInfo" :data="current" @done="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import Search from './components/search.vue';
  import OrderInfo from './components/order-info.vue';
  import {
    listRechargeOrder,
    removeBatchRechargeOrder
  } from '@/api/user/recharge/export';
  import type {
    RechargeOrder,
    RechargeOrderParam
  } from '@/api/user/recharge/export/model';
  import { utils, writeFile } from 'xlsx';

  defineProps<{
    activeKey?: boolean;
    data?: any;
  }>();

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      hideInTable: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '部门名称',
      dataIndex: 'organizationName',
      key: 'organizationName',
      align: 'center'
    },
    {
      title: '姓名',
      dataIndex: 'nickname',
      key: 'nickname',
      align: 'center'
    },
    {
      title: '充值金额',
      dataIndex: 'payPrice',
      align: 'center'
    },
    {
      title: '充值时间',
      dataIndex: 'createTime',
      align: 'center'
    },
    {
      title: '操作人',
      dataIndex: 'admin',
      key: 'admin',
      align: 'center'
    },
    {
      title: '备注',
      dataIndex: 'comments',
      align: 'center'
    },
    {
      title: '充值方式',
      dataIndex: 'rechargeType',
      key: 'rechargeType',
      align: 'center'
    }
  ]);

  // 表格选中数据
  const selection = ref<RechargeOrder[]>([]);
  const exportData = ref<RechargeOrder[]>([]);
  // 当前编辑数据
  const current = ref<RechargeOrder | null>(null);
  // 是否显示资产详情
  const showInfo = ref(false);
  // 是否显示编辑弹窗
  // const showEdit = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    return listRechargeOrder({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表单数据
  // const { form } = useFormData<RechargeOrder>({
  //   exportId: undefined
  // });

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

  /* 打开编辑弹窗 */
  const openInfo = (row?: RechargeOrder) => {
    current.value = row ?? null;
    showInfo.value = true;
  };

  /* 数据转为树形结构 */
  const parseData = (data: RechargeOrder[]) => {
    exportData.value = data;
    return data;
  };

  /* 批量删除 */
  const removeBatch = () => {
    console.log(selection.value);
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的记录吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = message.loading('请求中..', 0);
        removeBatchRechargeOrder(selection.value.map((d) => d.orderId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  // 导出
  const handleExport = () => {
    const array: (string | number)[][] = [
      [
        '部门',
        '编号',
        '姓名',
        '充值金额',
        '充值时间',
        '添加人',
        '备注',
        '充值方式'
      ]
    ];
    exportData.value?.forEach((d: RechargeOrder) => {
      array.push([
        `${d.organizationName}`,
        `${d.userId}`,
        `${d.nickname}`,
        `${d.payPrice}`,
        `${d.createTime}`,
        `财务充值`,
        `${d.comments}`,
        `管理员充值`
      ]);
    });
    const sheetName = '充值记录导出';
    const workbook = {
      SheetNames: [sheetName],
      Sheets: {}
    };
    const sheet = utils.aoa_to_sheet(array);
    workbook.Sheets[sheetName] = sheet;
    // 设置列宽
    sheet['!cols'] = [
      { wch: 10 },
      { wch: 10 },
      { wch: 10 },
      { wch: 10 },
      { wch: 20 },
      { wch: 40 },
      { wch: 10 }
    ];
    writeFile(workbook, '充值记录导出.xlsx');
  };

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

  const query = () => {
    listRechargeOrder({}).then((data) => {
      exportData.value = data;
      console.log(data);
    });
  };

  query();
  reload();
</script>

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

<style lang="less" scoped>
  p {
    line-height: 0.8;
  }
  .sys-org-table :deep(.ant-table-body) {
    overflow: auto !important;
    overflow: overlay !important;
  }

  .sys-org-table :deep(.ant-table-pagination.ant-pagination) {
    padding: 0 4px;
    margin-bottom: 0;
  }
  .price-edit {
    padding-right: 5px;
  }
  .comments {
    max-width: 200px;
  }
</style>
