<template>
  <div style="background-color: #fff; padding: 15px">
    <baseTableHeader title="公司销售明细" @resetSearch="reset" @search="query">
      <template #content>
        <el-form v-model="searchForm" label-width="100">
          <el-row :gutter="25">
            <el-col :span="10">
              <el-form-item label="统计日期">
                <el-date-picker
                  v-model="searchForm.dateRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="选择开始日期"
                  end-placeholder="选择结束日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  @change="dateChange" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="逝者姓名">
                <el-input
                  v-model="searchForm.deceasedName"
                  placeholder="输入逝者名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="购买人">
                <el-input
                  v-model="searchForm.familyName"
                  placeholder="输入购买人" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="服务名称">
                <el-input
                  v-model="searchForm.serviceName"
                  placeholder="输入服务名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6" label="引导员">
              <el-form-item label="引导员">
                <guideList v-model="searchForm.guide"></guideList>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #operateBtns>
        <el-button @click="exportSalesDetailsExcel('当前')"
          ><img
            src="/assets/images/Excel.svg"
            alt=""
            width="20"
            height="20" />导出当前</el-button
        >
        <el-button @click="exportSalesDetailsExcel('所有')"
          ><img
            src="/assets/images/Excel.svg"
            alt=""
            width="20"
            height="20" />导出所有</el-button
        >
      </template>
    </baseTableHeader>
    <el-card style="margin-top: 8px">
      <base-table
        :option="tableOption"
        ref="table"
        border
        show-summary
        :summary-method="getSummaries">
        <template #colunm>
          <el-table-column
            type="index"
            width="80"
            fixed="left"
            label="序号"
            align="center"></el-table-column>
          <el-table-column
            width="120"
            fixed="left"
            prop="deceasedRetail.checkoutDate"
            label="结账日期"
            align="center">
            <template #default="{ row }">
              {{ row.deceasedRetail.checkoutDate.split(" ")[0] }}
            </template>
          </el-table-column>
          <el-table-column
            prop="deceased.name"
            label="逝者姓名"
            width="120"
            fixed="left"
            align="center">
            <template #default="{ row }">
              <span>{{
                row.deceased.name ||
                row.deceased.familyName ||
                row.deceasedRetail.deceasedName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="deceasedRetail.guide"
            label="引导员"
            fixed="left"
            align="center" />
          <el-table-column prop="deceased.gender" label="性别" align="center" />
          <el-table-column prop="deceased.age" label="年龄" align="center" />
          <el-table-column
            prop="deceased.idNumber"
            label="身份证"
            align="center"
            width="180" />
          <el-table-column label="地址" align="center" width="280">
            <template #default="{ row }">
              <div style="text-align: left">
                <span
                  v-if="row.deceased.province || row.deceasedRetail.province"
                  >{{
                    row.deceased.province || row.deceasedRetail.province
                  }}/</span
                >
                <span v-if="row.deceased.city || row.deceasedRetail.city"
                  >{{ row.deceased.city || row.deceasedRetail.city }}/</span
                >
                <span
                  v-if="row.deceased.address || row.deceasedRetail.address"
                  >{{
                    row.deceased.address || row.deceasedRetail.address
                  }}</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="deceased.name"
            label="购买人姓名"
            align="center"
            width="120">
            <template #default="{ row }">
              <span>{{
                row.deceased.familyName || row.deceasedRetail.deceasedName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="deceased.familyPhone"
            label="购买人电话"
            align="center"
            width="150" />
          <el-table-column
            prop="name"
            label="项目名称"
            align="center"
            width="150" />
          <el-table-column
            prop="price"
            label="单价"
            align="center"
            width="150" />
          <el-table-column
            prop="quantity"
            label="数量"
            align="center"
            width="150" />
          <el-table-column prop="sum" label="金额" align="center" width="150">
          </el-table-column>

          <el-table-column
            prop="remark"
            label="备注"
            width="280"
            align="center" />
        </template>
      </base-table>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import request from "@/lib/request";
import { tableOptionType } from "@/types/table";
import { ElMessage } from "element-plus";
import { nextTick, onMounted, ref } from "vue";
import ExcelJS from "exceljs";

const categories = ref<Array<{ id: number; name: string }>>([]);
let searchForm = ref({
  dateRange: [],
  serviceName: "",
  categoryName: "",
  categories: "",
  startDate: "",
  endDate: "",
  deceasedName: "",
  guide: "",
  familyName: "",
});

let tableOption = ref<tableOptionType>({
  url: "/stats/salesDetails",
  searchUrl: "/stats/salesDetails",
  searchParams: searchForm,
  executeType: "list",
});
let table = ref();
const fetchCategories = async () => {
  try {
    const res = await request().get("/public/service-categories");
    categories.value = res.data.map((item: any) => ({
      id: item.value,
      name: item.label,
    }));
  } catch (error) {
    ElMessage.error("分类加载失败");
  }
};
const getSummaries = (param: { columns: any[]; data: any[] }) => {
  const { columns, data } = param;
  const sums: any[] = [];
  // 需要统计的字段列表
  const sumKeys = ["price", "quantity", "sum"];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (sumKeys.includes(column.property)) {
      const values = data.map((item) => {
        const keys = column.property.split(".");
        let value = item;
        for (const key of keys) {
          value = value?.[key] || 0;
        }
        return Number(value) || 0;
      });

      if (!values.every((value) => isNaN(value))) {
        const sum = values.reduce((prev, curr) => {
          return prev + curr;
        }, 0);
        sums[index] = `${sum.toFixed(2)}`;
      } else {
        sums[index] = "0.00 元";
      }
    } else {
      sums[index] = "";
    }
  });

  return sums;
};

const dateChange = (val: string[]) => {
  if (val?.length === 2) {
    searchForm.value.dateRange = val;
    searchForm.value.startDate = val[0];
    searchForm.value.endDate = val[1];
  }
};

function reset() {
  searchForm.value = {
    dateRange: [],
    serviceName: "",
    categoryName: "",
    categories: "",
    startDate: "",
    endDate: "",
    deceasedName: "",
    familyName: "",
  };
  table.value.methods.setDataType("reset");
}

function query() {
  table.value.methods.setDataType("search");
}

onMounted(() => {
  fetchCategories();
});

async function exportSalesDetailsExcel(type: "当前" | "所有") {
  try {
    let list = [];

    if (type === "当前") {
      list = table.value.tableData.data;
    } else {
      // 1. 获取所有数据
      const res = await request().post("/stats/salesDetails", {
        pageSize: 999999999,
        pageNumber: 1,
        dateRange: [],
        serviceName: "",
        categoryName: "",
        categories: "",
        startDate: "",
        endDate: "",
        deceasedName: "",
        guide: "",
        familyName: "",
      });
      list = res.data?.list;
    }

    // 2. 获取模板文件
    const templateRes = await fetch("/excelTemple/销售明细.xlsx");
    const buffer = await templateRes.arrayBuffer();

    // 3. 加载 Excel 模板
    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.load(buffer);
    const sheet = workbook.getWorksheet(1); // 默认取第一个 sheet

    // 4. 从第 3 行开始填充数据
    list.forEach((item, index) => {
      const row = sheet.getRow(index + 2); // 第3行开始
      const deceased = item.deceased || {};
      const retail = item.deceasedRetail || {};

      row.getCell(1).value = index + 1;
      row.getCell(2).value = retail.checkoutDate || "";
      row.getCell(3).value = deceased.name || "";
      row.getCell(4).value = retail.guide || "";
      row.getCell(5).value = deceased.gender || "";
      row.getCell(6).value = deceased.age || "";
      row.getCell(7).value = deceased.idNumber || "";
      row.getCell(8).value = deceased.address || "";
      row.getCell(9).value = deceased.familyName || "";
      row.getCell(10).value = deceased.familyPhone || "";
      row.getCell(11).value = item.name || "";
      row.getCell(12).value = item.price || "";
      row.getCell(13).value = item.quantity || "";
      row.getCell(14).value = item.sum || "";
      row.getCell(15).value = item.remark || "";
      row.eachCell((cell) => {
        cell.alignment = { vertical: "middle", horizontal: "center" };
      });
      row.commit(); // 应用修改
    });

    // 5. 导出为 blob
    const blob = await workbook.xlsx.writeBuffer();
    const file = new Blob([blob], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });

    // 6. 触发下载
    const url = URL.createObjectURL(file);
    const a = document.createElement("a");
    a.href = url;
    a.download = "销售明细.xlsx";
    a.click();
    URL.revokeObjectURL(url);
  } catch (error) {
    console.error("导出销售明细失败:", error);
  }
}
</script>

<style scoped lang="scss">
.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.is-loading {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

th,
td {
  border: 1px solid #000;
  padding: 8px;
  font-size: 14px;
  text-align: center !important;
}
@media print {
  /* 移除全局布局影响 */
  body,
  html {
    display: block !important;
    height: auto !important;
    margin: 2mm !important; /* 添加安全边距 */
  }

  #print-container {
    width: auto !important; /* 改为自动宽度 */
    margin: 0 auto !important; /* 居中显示 */
    font-size: 12pt !important; /* 调整字号 */
    min-height: 297mm;
  }

  table {
    table-layout: fixed;
    width: 100% !important;
  }

  /* 优化单元格内边距 */
  td,
  th {
    padding: 4px 2mm !important;
    line-height: 1.4 !important;
  }
}

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: 10px 2mm !important;
    word-wrap: break-word;
  }
}
</style>
