<template>
  <div class="page">
    <div class="ele-body">
      <a-card title="财务报表" :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="userId"
          :columns="columns"
          :datasource="datasource"
          :parse-data="parseData"
          v-model:selection="selection"
          tool-class="ele-toolbar-form"
          :scroll="{ x: 1200 }"
          class="sys-org-table"
          :striped="true"
        >
          <template #toolbar>
            <search
              @search="reload"
              :selection="selection"
              :export-data="exportData"
              @done="handleExport"
            />
          </template>
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'lunchPost'">
              <div v-if="index === 0">
                <div>{{ record.lunchPost }}</div>
                <div>{{ record.gear10 }}/{{ record.gear20 }}</div>
              </div>
            </template>
            <template v-if="column.key === 'lunchSign'">
              <div v-if="index === 0">
                <div>{{ record.lunchSign }}</div>
                <div>{{ record.signGear10 }}/{{ record.signGear20 }}</div>
              </div>
            </template>
            <template v-if="column.key === 'createTime'">
              {{ record.createTime }}
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import Search from './components/search.vue';
  import { listOrderExport } from '@/api/booking/orderExport';
  import type {
    OrderExport,
    OrderExportParam
  } from '@/api/booking/orderExport/model';
  import ExcelJS from 'exceljs';
  import { EleProTable, toDateString } from 'ele-admin-pro';
  import {
    ColumnItem,
    DatasourceFunction
  } from 'ele-admin-pro/es/ele-pro-table/types';

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

  // 表格选中数据
  const selection = ref<OrderExport[]>([]);
  const exportData = ref<OrderExport[]>([]);
  const exportTitle = ref<string>(`贵港资源报餐人员统计`);

  /* 导出数据 */
  const parseData = (data: OrderExport[]) => {
    exportData.value = data;
    return data;
  };

  // 导出
  const handleExport = async () => {
    // 创建工作簿
    const workbook = new ExcelJS.Workbook();
    // 添加工作表
    const sheet = workbook.addWorksheet(exportTitle.value, {
      headerFooter: { firstHeader: 'Hello Exceljs' }
    });
    const style: ExcelJS.Style = {
      alignment: { horizontal: 'center' }
    };
    sheet.columns = [
      { header: '部门', key: 'organizationName', style, width: 30 },
      { header: '编号', key: 'userId', style, width: 20 },
      { header: '姓名', key: 'nickname', style, width: 20 },
      { header: '早餐报餐次数', key: 'breakfastPost', style, width: 20 },
      { header: '早餐签到次数', key: 'breakfastSign', style, width: 20 },
      {
        header: '午餐报餐次数(食堂/领物)',
        key: 'lunchPostText',
        style,
        width: 20
      },
      {
        header: '午餐签到次数(食堂/领物)',
        key: 'lunchSignText',
        style,
        width: 20
      },
      { header: '晚餐报餐次数', key: 'dinnerPost', style, width: 20 },
      { header: '晚餐签到次数', key: 'dinnerSign', style, width: 20 },
      { header: '消费金额', key: 'expendMoney', style, width: 20 }
    ];
    sheet.addRows(exportData.value);
    sheet.insertRow(1, [exportTitle.value]);
    const a1 = sheet.getCell(1, 1);

    a1.style = {
      alignment: { horizontal: 'center' },
      font: {
        bold: true,
        size: 26
      }
    };
    sheet.mergeCells('A1:J1');
    // sheet.getRow(2).fill = {
    //   type: 'pattern',
    //   pattern: 'darkTrellis',
    //   fgColor: { argb: '92d050' },
    //   bgColor: { argb: '92d050' }
    // };
    // 写入 buffer
    const buffer = await workbook.xlsx.writeBuffer();
    let blob = new Blob([buffer]);
    var aEle = document.createElement('a'); // 创建a标签
    aEle.download = exportTitle.value + '.xlsx'; // 设置下载文件的文件名
    aEle.href = URL.createObjectURL(blob);
    aEle.click(); // 设置点击事件
  };

  // const reload = (where) => {
  //   title.value.deliveryTimeStart = where.deliveryTimeStart;
  //   title.value.deliveryTimeEnd = where.deliveryTimeEnd;
  //
  //   listOrderExport(where).then((data) => {
  //     exportData.value = data;
  //   });
  // };
  // reload({});

  /* 搜索 */
  const reload = (where?: OrderExportParam) => {
    exportTitle.value = `贵港资源${toDateString(
      where?.deliveryTimeStart,
      'yyyy-MM-dd'
    )} 至 ${toDateString(where?.deliveryTimeEnd, 'yyyy-MM-dd')}报餐人员统计`;
    selection.value = [];
    tableRef?.value?.reload({ where: where });
  };

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    // 搜索条件
    if (filters.payStatus) {
      where.payStatus = filters.payStatus;
    }
    if (filters.deliveryStatus) {
      where.deliveryStatus = filters.deliveryStatus;
    }
    // 默认查询今天
    // where.deliveryTime = toDateString(new Date(), 'YYYY-MM-dd 00:00:00');
    return listOrderExport({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表格实例
  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'
    },
    {
      title: '下单时间',
      dataIndex: 'createTime',
      key: 'createTime'
    },
    {
      title: '单位',
      dataIndex: 'realName',
      key: 'realName'
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone'
    },
    {
      title: '实际转账单位/个人',
      dataIndex: 'phone',
      key: 'phone'
    },
    {
      title: '价格',
      dataIndex: 'price',
      align: 'center'
    },
    {
      title: '积分',
      dataIndex: 'price',
      align: 'center'
    },
    {
      title: '支付方式',
      dataIndex: 'breakfastSign',
      align: 'center'
    },
    {
      title: '会员/散客',
      dataIndex: 'lunchPost',
      key: 'lunchPost',
      align: 'center'
    },
    {
      title: '预付卡号',
      dataIndex: 'expendMoney',
      align: 'center'
    },
    {
      title: '预付卡到期时间',
      dataIndex: 'expendMoney',
      align: 'center'
    },
    {
      title: '备注',
      dataIndex: 'expendMoney',
      align: 'center'
    }
  ]);
</script>

<script lang="ts">
  export default {
    name: 'OrderExportIndex'
  };
</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>
