<template>
  <div style="background-color: #fff; padding: 15px">
    <baseTableHeader
      title="公司日收入统计"
      @resetSearch="reset"
      @search="query">
      <template #content>
        <el-form v-model="searchForm">
          <el-row :gutter="15">
            <el-col>
              <el-form-item label="购买日期">
                <el-date-picker
                  v-model="searchForm.purchaseDate"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="选择日期"
                  end-placeholder="选择日期"
                  @change="dataChange" />
              </el-form-item>
              <!-- <div>
                <el-button
                  type="primary"
                  style="margin-left: 15px"
                  @click="query"
                  >查询</el-button
                ><el-button
                  type="warning"
                  style="margin-left: 15px"
                  @click="reset"
                  >重置</el-button
                >
                <el-button v-print="print">打印单据</el-button>
              </div> -->
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #operateBtns>
        <el-button v-print="print"
          ><img
            src="/assets/icon/打印机.svg"
            style="margin-right: 5px"
            width="20"
            height="20" />打印单据</el-button
        >
        <el-button @click="exportFile"
          ><img
            src="/assets/images/Excel.svg"
            alt=""
            width="20"
            height="20" />导出</el-button
        >
      </template>
    </baseTableHeader>

    <div id="print-container">
      <h2
        style="
          color: #000;
          text-align: center;
          font-size: 20pt;
          padding: 15px;
          font-weight: bold;
        ">
        殡仪服务公司日收入统计表
      </h2>
      <table
        id="print-table"
        class=""
        style="
          font-family: 仿宋;
          table-layout: fixed;
          width: 100%;
          border-collapse: collapse;
        ">
        <tbody>
          <tr>
            <td
              colspan="4"
              class="l"
              style="
                text-align: left;

                font-weight: bold;
                font-size: 25px;
                font-family: 宋体;
              ">
              <span>
                统计时间：{{
                  dayjs(searchForm.startDate).format("YYYY-MM-DD HH:mm:ss")
                }}
                至
                {{ dayjs(searchForm.endDate).format("YYYY-MM-DD HH:mm:ss") }}
              </span>
              <!-- <span v-else>
                开始时间：{{ dayjs(searchForm.startDate).format("YYYY-MM-DD") }}
              </span> -->
            </td>
            <td
              colspan="2"
              class="l"
              style="
                text-align: left;

                font-weight: bold;
                font-size: 25px;
                font-family: 宋体;
              ">
              单位：元
            </td>
          </tr>
          <tr>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              <b></b>
            </td>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              <b>小计</b>
            </td>
            <td
              colspan="2"
              style="height: 30px; border: 1px solid black; text-align: center">
              <b>总计</b>
            </td>
            <td
              colspan="2"
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              <b>备注</b>
            </td>
          </tr>

          <tr>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              现金
            </td>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              {{ statsData.service.cashAmount + statsData.retail.cashAmount }}
            </td>
            <td
              rowspan="6"
              colspan="2"
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              {{
                statsData.service.cashAmount +
                statsData.service.unionPayAmount +
                statsData.service.cardAmount +
                statsData.service.publicTransferAmount +
                statsData.service.workshopPayment +
                statsData.retail.cashAmount +
                statsData.retail.unionPayAmount +
                statsData.retail.cardAmount +
                statsData.retail.publicTransferAmount +
                statsData.retail.workshopPayment
              }}
            </td>

            <td
              colspan="2"
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              "></td>
          </tr>
          <tr>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              银联
            </td>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              {{
                statsData.service.unionPayAmount +
                statsData.retail.unionPayAmount
              }}
            </td>

            <td
              colspan="2"
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              "></td>
          </tr>
          <tr>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              银行卡
            </td>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              {{ statsData.service.cardAmount + statsData.retail.cardAmount }}
            </td>

            <td
              colspan="2"
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              "></td>
          </tr>
          <tr>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              车间支付
            </td>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              {{
                statsData.service.workshopPayment +
                statsData.retail.workshopPayment
              }}
            </td>

            <td
              colspan="2"
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              "></td>
          </tr>
          <tr>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              对公转账
            </td>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              {{
                statsData.service.publicTransferAmount +
                statsData.retail.publicTransferAmount
              }}
            </td>

            <td
              colspan="2"
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              "></td>
          </tr>
          <tr>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              "></td>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              "></td>

            <td
              colspan="2"
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              "></td>
          </tr>

          <tr>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              <b>现金合计</b>
            </td>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              <b>微信合计</b>
            </td>
            <td
              colspan="2"
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              <b>银行卡合计</b>
            </td>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              <b>车间支付合计</b>
            </td>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              <b>对公转账合计</b>
            </td>
          </tr>
          <tr>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              {{ statsData.total.cashAmount }}
            </td>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              {{ statsData.total.unionPayAmount }}
            </td>

            <td
              colspan="2"
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              {{ statsData.total.cardAmount }}
            </td>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              {{ statsData.total.workshopPayment }}
            </td>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              {{ statsData.total.publicTransferAmount }}
            </td>
          </tr>

          <tr>
            <td
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              <b>总合计：</b>
            </td>
            <td
              colspan="5"
              style="
                height: 30px;

                border: 1px solid black;
                text-align: center;
              ">
              {{
                statsData.total.cashAmount +
                statsData.total.unionPayAmount +
                statsData.total.cardAmount +
                statsData.total.workshopPayment +
                statsData.total.publicTransferAmount
              }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref } from "vue";
import request from "@/lib/request";
import dayjs from "dayjs";
import ExcelJS from "exceljs";

export type PaymentStats = {
  cashAmount: number;
  unionPayAmount: number;
  cardAmount: number;
  publicTransferAmount: number;
  workshopPayment: number;
};

// 完整响应类型
export type StatsResponse = {
  retail: PaymentStats;
  service: PaymentStats;
  total: PaymentStats;
};

let searchForm = ref({
  startDate: dayjs().startOf("day").toDate(),
  endDate: new Date(),
  purchaseDate: [dayjs().startOf("day").toDate(), new Date()],
});

let statsData = ref<StatsResponse>({
  retail: {
    cashAmount: 0,
    unionPayAmount: 0,
    cardAmount: 0,
    publicTransferAmount: 0,
    workshopPayment: 0,
  },
  service: {
    cashAmount: 0,
    unionPayAmount: 0,
    cardAmount: 0,
    publicTransferAmount: 0,
    workshopPayment: 0,
  },
  total: {
    cashAmount: 0,
    unionPayAmount: 0,
    cardAmount: 0,
    publicTransferAmount: 0,
    workshopPayment: 0,
  },
});
let searched = ref(false);

request()
  .get("/stats/dayIncome", {
    params: {
      startDate: dayjs().startOf("day").toDate(),
      endDate: new Date(),
    },
  })
  .then((res) => {
    statsData.value = res.data;
  });

const print = {
  id: "print-container",
};

function query() {
  searched.value = false;
  request()
    .get("/stats/dayIncome", {
      params: {
        startDate: dayjs(searchForm.value.startDate).format(
          "YYYY-MM-DD HH:mm:ss"
        ),
        endDate: dayjs(searchForm.value.endDate).format("YYYY-MM-DD HH:mm:ss"),
      },
    })
    .then((res) => {
      statsData.value = res.data;
    });
}

function reset() {
  searchForm.value = {
    startDate: dayjs().startOf("day").toDate(),
    endDate: new Date(),
    purchaseDate: [dayjs().startOf("day").toDate(), new Date()],
  };
  query();
}

function dataChange(val: Date[]) {
  searchForm.value.startDate = val[0];
  searchForm.value.endDate = val[1];
}

async function exportFile() {
  try {
    // 获取模板文件
    const response = await fetch("/excelTemple/日收入统计.xlsx");
    const buffer = await response.arrayBuffer();

    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.load(buffer);
    const sheet = workbook.getWorksheet(1); // 默认第一个工作表

    const startDate = dayjs(searchForm.value.startDate).format(
      "YYYY-MM-DD HH:mm:ss"
    );
    const endDate = dayjs(searchForm.value.endDate).format(
      "YYYY-MM-DD HH:mm:ss"
    );

    // 工具函数：填充值并保留样式
    const setCellValueWithStyle = (cellAddress, value) => {
      const cell = sheet.getCell(cellAddress);
      const style = { ...cell.style };
      cell.value = value;
      cell.style = style;
    };

    // 填充各项内容（保持样式）
    setCellValueWithStyle("C2", `${startDate} 至 ${endDate}`);

    setCellValueWithStyle("B4", statsData.value.total.cashAmount);

    setCellValueWithStyle("B5", statsData.value.total.unionPayAmount);
    setCellValueWithStyle("B6", statsData.value.total.cardAmount);
    setCellValueWithStyle("B7", statsData.value.total.workshopPayment);
    setCellValueWithStyle("B8", statsData.value.total.publicTransferAmount);

    const total =
      statsData.value.service.cashAmount +
      statsData.value.service.unionPayAmount +
      statsData.value.service.cardAmount +
      statsData.value.service.publicTransferAmount +
      statsData.value.service.workshopPayment +
      statsData.value.retail.cashAmount +
      statsData.value.retail.unionPayAmount +
      statsData.value.retail.cardAmount +
      statsData.value.retail.publicTransferAmount +
      statsData.value.retail.workshopPayment;
    setCellValueWithStyle("C4", total);

    setCellValueWithStyle("A11", statsData.value.total.cashAmount);
    setCellValueWithStyle("B11", statsData.value.total.unionPayAmount);
    setCellValueWithStyle("C11", statsData.value.total.cardAmount);
    setCellValueWithStyle("D11", statsData.value.total.workshopPayment);
    setCellValueWithStyle("E11", statsData.value.total.publicTransferAmount);

    const grandTotal =
      statsData.value.total.cashAmount +
      statsData.value.total.unionPayAmount +
      statsData.value.total.cardAmount +
      statsData.value.total.workshopPayment +
      statsData.value.total.publicTransferAmount;
    setCellValueWithStyle("B12", grandTotal);

    // 导出文件
    const newBuffer = await workbook.xlsx.writeBuffer();
    const blob = new Blob([newBuffer], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "日收入统计.xlsx";
    a.click();
    URL.revokeObjectURL(url);
  } catch (error) {
    console.error("导出 Excel 文件时出错:", error);
  }
}
</script>
<style lang="scss" scoped>
tr,
td {
  font-size: 14px !important;
}

#print-container {
  width: 100% !important;
  margin: 0 !important;
  padding: 0 5mm !important;
  font-size: 14pt;
  color: #000 !important;
  font-family: Microsoft YaHei, "SimSun", serif !important;

  /* 添加表格布局优化 */
  table {
    width: 100% !important;
    table-layout: fixed;
    border-collapse: collapse !important;

    td,
    th {
      padding: 5px 2mm !important;
      word-wrap: break-word;
    }
  }
}

@media print {
  /* 重置body和html的布局方式 */
  body,
  html {
    display: block !important;
    height: auto !important;
    margin: 0 !important;
    padding: 0 !important;
  }

  @page {
    margin: 15pt;
  }

  #print-container {
    min-height: 297mm; /* A4纸高度 */
    width: 100% !important;
    vertical-align: top !important;
    position: relative;
    top: 0;
    transform: none !important;
  }

  /* 隐藏不需要打印的元素 */
  .el-form,
  .el-button {
    display: none !important;
  }
}
</style>
