<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="dateRange" type="datetimerange" range-separator="至" start-placeholder="开始日期时间" end-placeholder="结束日期时间" :shortcuts="dateShortcuts" :disabled-date="disabledDate" @change="handleDateChange" class="date-range" value-format="YYYY-MM-DD HH:mm:ss" />
            </div>
            <div class="filter-item">
              <check-box-filter v-model="receptionDoctorUserId" label="医生" :list="doctorList">
                <template #item="{ item }">
                  <ww-user :openid="item.value"></ww-user>
                </template>
              </check-box-filter>
            </div>
            <div class="filter-actions">
              <el-button type="primary" @click="handleGetDoctorPrescriptionCount">查询</el-button>
              <el-button type="success" @click="exportToExcel">导出Excel</el-button>
              <el-button @click="resetFilters">重置</el-button>
            </div>
          </div>
          
          <div class="filter-row">
            <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>
        </div>
      </div>
    </div>

    <div class="table-container">
      <table class="performance-table">
        <colgroup>
          <col style="width: 33%" />
          <col style="width: 33%" />
          <col style="width: 34%" />
        </colgroup>
        <thead>
          <tr>
            <th>医生姓名</th>
            <th>医生工号</th>
            <th>处方数量</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in tableData" :key="index">
            <td>{{ item.doctorName }}</td>
            <td>{{ item.doctorCode }}</td>
            <td>{{ item.prescriptionCount }}</td>
          </tr>
          <tr class="total-row">
            <td class="total-label">合计：</td>
            <td>-</td>
            <td>{{ totalPrescriptionCount }}</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 { getDoctorPrescriptionCount } 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) => i.doctorNo).map((i) => ({ value: i.userid }));
});

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

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

// 日期筛选
const dateRange = ref([]);

// 日期快捷选项
const dateShortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近半个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
      return [start, end];
    },
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
];
const list = ref([]);

// 禁用超过一个月范围的日期
const disabledDate = (time) => {
  if (!dateRange.value || dateRange.value.length === 0) {
    return false;
  }

  const startDate = new Date(dateRange.value[0]);
  const endDate = new Date(dateRange.value[1]);
  const currentDate = new Date(time);

  // 如果已选择了开始日期，限制结束日期不能超过开始日期后的31天
  if (dateRange.value.length === 1) {
    const oneMonthLater = new Date(startDate);
    oneMonthLater.setDate(startDate.getDate() + 31);
    return currentDate > oneMonthLater;
  }

  return false;
};

// 监听日期变化，确保不超过一个月
watch(dateRange, (newValue) => {
  if (newValue && newValue.length === 2) {
    const start = new Date(newValue[0]);
    const end = new Date(newValue[1]);
    const diffTime = Math.abs(end - start);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

    if (diffDays > 31) {
      // 如果超过31天，将结束日期设置为开始日期后的31天
      const maxEnd = new Date(start);
      maxEnd.setDate(start.getDate() + 31);
      const formattedMaxEnd = formatDateTime(maxEnd);

      dateRange.value = [newValue[0], formattedMaxEnd];
      ElMessage.warning("查询范围已限制为一个月内");
    }
    // 日期变化后自动触发查询
    handleGetDoctorPrescriptionCount();
  }
});

// 格式化显示的日期范围
const formatDateRange = computed(() => {
  if (dateRange.value && dateRange.value.length === 2) {
    return `${dateRange.value[0]} 至 ${dateRange.value[1]}`;
  }
  return "全部日期";
});

// 格式化日期时间为YYYY-MM-DD HH:mm:ss
const formatDateTime = (date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  const seconds = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 获取当天的日期范围（从00:00:00到23:59:59）
const getTodayDateRange = () => {
  const today = new Date();
  const startOfToday = new Date(today);
  startOfToday.setHours(0, 0, 0, 0);
  
  const endOfToday = new Date(today);
  endOfToday.setHours(23, 59, 59, 999);
  
  return [formatDateTime(startOfToday), formatDateTime(endOfToday)];
};

// 存储原始未筛选的数据
const rawTableData = ref([]);
// 表格数据
const tableData = computed(() => {
  // 过滤原始数据
  console.log("筛选条件:", receptionDoctorUserId.value);
  console.log("原始数据:", rawTableData.value);
  return rawTableData.value.filter((item) => {
    const doctorFilter = receptionDoctorUserId.value.length === 0 || receptionDoctorUserId.value.includes(item.doctorCode);

    return doctorFilter;
  });
});
// 获取医生处方数据
async function handleGetDoctorPrescriptionCount() {
  try {
    const params = {
      startDate: dateRange.value ? dateRange.value[0] : undefined,
      endDate: dateRange.value ? dateRange.value[1] : undefined,
      orderSource: selectedTerminal.value || undefined, // 修改为单个终端参数
    };
    const { data, success, message } = await getDoctorPrescriptionCount(params);
    if (success) {
      rawTableData.value = data.data || [];
    } else {
      ElMessage.error(message || "获取医生处方数据失败");
    }
  } catch (error) {
    ElMessage.error("获取医生处方数据出错：" + error.message);
  }
}

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

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

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

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

// 导出Excel
const exportToExcel = () => {
  // 准备导出数据
  const exportData = [];

  // 添加表头和筛选信息
  exportData.push(["医生处方统计表"]);
  exportData.push(["日期范围", dateRange.value ? `${dateRange.value[0]} 至 ${dateRange.value[1]}` : "全部日期"]);

  // 获取医生名称
  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.doctorName, item.doctorCode, item.prescriptionCount]);
  });

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

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

  // 设置列宽
  const colWidths = [
    { wch: 15 }, // 医生姓名
    { 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();
  
  dateRange.value = getTodayDateRange();

  // 初始加载数据
  handleGetDoctorPrescriptionCount();
});
</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;
  border-top: 1px solid #ebeef5;
}

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

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

@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>