<template>
  <div class="report-container">
    <div class="report-header">
      <div class="report-actions">
        <div class="filter-section">
          <div class="filter-row">
            <div class="filter-item">
              <span class="filter-label">日期：</span>
              <el-date-picker v-model="selectedDate" type="date" placeholder="选择日期" :shortcuts="dateShortcuts" @change="handleDateChange" class="date-picker" value-format="YYYY-MM-DD" />
            </div>
            <div class="filter-item">
              <span class="filter-label">终端：</span>
              <el-select v-model="selectedTerminal" placeholder="请选择终端" clearable class="terminal-select">
                <el-option v-for="item in terminalOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
            <div class="filter-actions">
              <el-button type="primary" @click="handleGetTimePeriodStatistics">查询</el-button>
              <el-button type="success" @click="exportToExcel">导出Excel</el-button>
              <el-button @click="resetFilters">重置</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="table-container" v-loading="loading" element-loading-text="数据加载中...">
      <table class="performance-table">
        <colgroup>
          <col style="width: 50%" />
          <col style="width: 50%" />
        </colgroup>
        <thead>
          <tr>
            <th>时间段</th>
            <th>数量</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in tableData" :key="index">
            <td>{{ item.timeSlot }}</td>
            <td>{{ item.count }}</td>
          </tr>
          <tr class="total-row">
            <td class="total-label">合计：</td>
            <td>{{ totalCount }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="footer-info">
      <span>共 {{ tableData.length }} 条记录</span>
      <!-- <span class="date-limit-info">* 查询限制为一个月内的数据</span> -->
    </div>
  </div>
</template>
  
<script setup>
import { ref, computed, onMounted, watch } from "vue";
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
import { ElButton, ElMessage, ElDatePicker } from "element-plus";
import { getTimePeriodStatistics } from "@/api/hlw";
import useModal from "@/hooks/useModal";
import { CheckBoxFilter, baseFilterItem } from "@/components/filter-bar";
import { storeToRefs } from "pinia";
import { staffStore } from "@/store/staff";

const receptionDoctorUserId = ref([]);

const doctorList = computed(() => {
  return staffList.value.filter((i) => Array.isArray(i.job) && i.job.includes("doctor")).map((i) => ({ value: i.userid }));
});

const { getStaffList } = staffStore();
const { staffList } = storeToRefs(staffStore());

// 日期筛选 - 改为单一日期
const selectedDate = ref("");

// 添加终端筛选（修改为单选）
const selectedTerminal = ref("");
const terminalOptions = [
  { value: "ALIPAY_MINI", label: "支付宝小程序" },
  { value: "MATEPAD", label: "门店pad" },
];

// 日期快捷选项
const dateShortcuts = [
  {
    text: "今天",
    value: () => {
      return new Date();
    },
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 1);
      return date;
    },
  },
  {
    text: "一周前",
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 7);
      return date;
    },
  },
];

// 监听日期变化
watch(selectedDate, (newValue) => {
  if (newValue) {
    // 日期变化后自动触发查询
    handleGetTimePeriodStatistics();
  }
});

// 格式化显示的日期
const formatDate = computed(() => {
  return selectedDate.value || "未选择日期";
});

// 格式化日期为YYYY-MM-DD
const formatDateString = (date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// 表格数据
const tableData = ref([]);
// 添加loading状态
const loading = ref(false);

// 获取时间段统计数据
async function handleGetTimePeriodStatistics() {
  loading.value = true;
  try {
    const params = {
      date: selectedDate.value,
      receptionDoctorUserId: receptionDoctorUserId.value?.length > 0 ? receptionDoctorUserId.value : undefined,
      orderSource: selectedTerminal.value || undefined, // 修改为单个终端参数
    };
    const { data, success, message } = await getTimePeriodStatistics(params);
    if (success) {
      tableData.value = data.data || [];
    } else {
      ElMessage.error(message || "获取时间段统计数据失败");
    }
  } catch (error) {
    ElMessage.error("获取时间段统计数据出错：" + error.message);
  } finally {
    loading.value = false;
  }
}

// 计算合计
const totalCount = computed(() => {
  return tableData.value.reduce((sum, item) => sum + (item.count || 0), 0);
});

// 重置筛选条件
const resetFilters = () => {
  // 设置默认日期为当天
  const today = new Date();
  selectedDate.value = formatDateString(today);
  receptionDoctorUserId.value = [];
  selectedTerminal.value = ""; // 清空终端选择（修改为单选）

  // 重置后自动查询
  handleGetTimePeriodStatistics();
};

// 日期变更处理函数
const handleDateChange = () => {
  // 日期变化会在watch中自动触发查询
  console.log("日期已变更:", selectedDate.value);
};

// 导出Excel
const exportToExcel = () => {
  if (loading.value) {
    ElMessage.warning("数据正在加载中，请稍后再试");
    return;
  }

  // 准备导出数据
  const exportData = [];

  // 添加表头和筛选信息
  exportData.push(["时间段统计表"]);
  exportData.push(["日期", selectedDate.value || "未选择日期"]);

  // 获取医生名称
  const doctorsText = receptionDoctorUserId.value.length > 0 ? `已选择${receptionDoctorUserId.value.length}位医生` : "全部";
  exportData.push(["医生", doctorsText]);
  
  // 添加终端筛选信息（修改为单选）
  const terminalText = selectedTerminal.value ? 
    terminalOptions.find(opt => opt.value === selectedTerminal.value)?.label || selectedTerminal.value : 
    "全部";
  exportData.push(["终端", terminalText]);

  exportData.push([]); // 空行

  // 添加表头
  exportData.push(["时间段", "数量"]);

  // 添加数据行
  tableData.value.forEach((item) => {
    exportData.push([item.timeSlot, item.count]);
  });

  // 添加总计行
  exportData.push(["合计", totalCount.value]);

  // 创建工作簿和工作表
  const wb = XLSX.utils.book_new();
  const ws = XLSX.utils.aoa_to_sheet(exportData);

  // 设置列宽
  const colWidths = [
    { wch: 15 }, // 时间段
    { wch: 12 }, // 数量
  ];

  ws["!cols"] = colWidths;

  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(wb, ws, "时间段统计");

  // 生成Excel文件并下载
  const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
  const blob = new Blob([excelBuffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });

  // 使用当前日期作为文件名的一部分
  const now = new Date();
  const fileName = `时间段统计_${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, "0")}${now.getDate().toString().padStart(2, "0")}.xlsx`;

  saveAs(blob, fileName);

  ElMessage.success("导出Excel成功");
};

onMounted(async () => {
  // 设置默认日期为当天
  if (staffList.value.length === 0) await getStaffList();
  const today = new Date();
  selectedDate.value = formatDateString(today);

  // 初始加载数据
  handleGetTimePeriodStatistics();
});
</script>
  
<style scoped>
.report-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;
  background-color: #f5f7fa;
  overflow: hidden;
  min-width: 1200px;
}

.report-header {
  background-color: white;
  padding: 15px 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
}

.report-title {
  text-align: center;
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 5px;
  color: #303133;
}

.report-date {
  text-align: center;
  font-size: 14px;
  margin-bottom: 15px;
  color: #606266;
}

.filter-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-label {
  white-space: nowrap;
  margin-right: 5px;
  font-size: 14px;
  color: #606266;
}

.filter-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.date-range {
  min-width: 320px;
}

:deep(.el-date-editor.el-input__wrapper),
:deep(.el-select) {
  width: 100%;
  flex: 1;
}

.buttons-row {
  justify-content: flex-end;
}

.filter-controls {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.table-container {
  flex: 1;
  margin: 15px 0 0 0;
  background-color: white;
  overflow: auto;
  position: relative;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

.performance-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
  table-layout: fixed;
}

.performance-table th,
.performance-table td {
  border: 1px solid #ebeef5;
  padding: 12px 8px;
  text-align: center;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.performance-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
  position: sticky;
  top: 0;
  z-index: 10;
}

.performance-table .amount {
  text-align: right;
  padding-right: 10px;
}

.total-row {
  background-color: #ebeef5;
  font-weight: bold;
  position: sticky;
  bottom: 0;
  z-index: 10;
}

.total-label {
  text-align: right;
  padding-right: 10px;
}

.footer-info {
  background-color: white;
  padding: 10px 20px;
  margin: 0;
  display: flex;
  justify-content: space-between;
  color: #606266;
  font-size: 14px;
  flex-shrink: 0;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.performance-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
  position: sticky;
  top: 0;
  z-index: 10;
}

.performance-table .amount {
  text-align: right;
  padding-right: 10px;
}

.total-row {
  background-color: #ebeef5;
  font-weight: bold;
  position: sticky;
  bottom: 0;
  z-index: 10;
}

.total-label {
  text-align: right;
  padding-right: 10px;
}

.footer-info {
  background-color: white;
  padding: 10px 20px;
  margin: 0;
  display: flex;
  justify-content: space-between;
  color: #606266;
  font-size: 14px;
  flex-shrink: 0;
  border-top: 1px solid #ebeef5;
}

.date-limit-info {
  color: #e6a23c;
  font-style: italic;
}

.terminal-select {
  min-width: 200px;
}

@media print {
  .report-container {
    background-color: white;
    height: auto;
  }

  .report-header {
    box-shadow: none;
  }

  .report-actions,
  .footer-info {
    display: none;
  }

  .table-container {
    margin: 0;
    border: none;
    overflow: visible;
    height: auto;
  }

  .performance-table th,
  .performance-table td {
    font-size: 12px;
    padding: 8px 4px;
  }
}

@media (max-width: 768px) {
  .filter-item {
    max-width: 100%;
  }

  .report-actions {
    flex-direction: column;
    align-items: stretch;
  }

  .filters-row {
    flex-direction: column;
  }

  .filter-item {
    width: 100%;
  }

  .filter-controls {
    margin-top: 10px;
    width: 100%;
    justify-content: space-between;
  }
}
</style>