<template>
  <div class="work-order-analysis">
    <!-- 搜索栏 -->
    <el-card class="filter-section">
      <el-form :model="queryParams" ref="searchForm" :inline="true" class="search-form">
        <el-form-item label="统计时间" prop="timeRange">
          <el-date-picker
              v-model="queryParams.timeRange"
              type="monthrange"
              range-separator="至"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              format="YYYY-MM"
              value-format="YYYY-MM"
              :picker-options="pickerOptions"
              style="width: 300px;"
          />
        </el-form-item>

        <el-form-item label="高频问题分类" prop="topIssue">
          <el-select
              v-model="queryParams.topIssue"
              placeholder="请选择高频问题"
              style="width: 200px;"
          >
            <el-option label="全部" value="" />
            <el-option label="设备故障" value="设备故障" />
            <el-option label="公共区域卫生" value="公共区域卫生" />
            <el-option label="停车管理" value="停车管理" />
            <el-option label="电梯维护" value="电梯维护" />
            <el-option label="公共设施维修" value="公共设施维修" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="getList" :disabled="isLoading">
            查询
          </el-button>
          <el-button icon="Refresh" @click="resetSearch" :disabled="isLoading">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据展示区域 -->
    <el-card class="analysis-container">
      <!-- 关键指标卡片（带背景色） -->
      <div class="key-metrics">
        <el-card
            v-for="(metric, index) in keyMetrics"
            :key="metric.title"
            class="metric-card"
            :style="{ background: metricColors[index] }"
        >
          <div class="metric-title">{{ metric.title }}</div>
          <div class="metric-value">
            {{ metric.value || "-" }}
            <span v-if="metric.unit">{{ metric.unit }}</span>
          </div>
        </el-card>
      </div>

      <!-- 数据表格 -->
      <el-table
          v-loading="isLoading"
          :data="analysisData"
          border
          v-show="analysisData.length > 0"
      >
        <el-table-column label="统计月份" prop="month" align="center" />
        <el-table-column label="工单完成率" prop="completionRate" align="right">
          <template #default="scope">
            {{ scope.row.completionRate }}%
          </template>
        </el-table-column>
        <el-table-column label="平均响应时长" prop="avgResponseTime" align="right">
          <template #default="scope">
            {{ scope.row.avgResponseTime }}小时
          </template>
        </el-table-column>
        <el-table-column label="返工率" prop="reworkRate" align="right">
          <template #default="scope">
            {{ scope.row.reworkRate }}%
          </template>
        </el-table-column>
        <el-table-column label="满意度评分" prop="satisfactionScore" align="right">
          <template #default="scope">
            {{ scope.row.satisfactionScore }}/5
          </template>
        </el-table-column>
        <el-table-column label="高频问题" prop="topIssue" align="center" />
      </el-table>

      <!-- 空数据提示 -->
      <div class="empty-tip" v-show="!analysisData.length && !isLoading">
        <el-icon><CircleClose /></el-icon>
        <span>暂无符合条件的工单数据</span>
      </div>

      <!-- 分页组件 -->
      <el-pagination
          v-show="total > 0"
          :total="total"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          layout="total, sizes, prev, pager, next, jumper"
          class="pagination"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from "vue";
import { getEstateManagementWorkOrderAnalysisDataList } from "@/api/estateManagement/estateManagement";

// 查询参数
const queryParams = reactive({
  timeRange: [], // 时间范围数组 ["start", "end"]
  topIssue: "",
  pageNum: 1,
  pageSize: 10,
  interfaceName: "服务工单分析",
});

const total = ref(0);
const analysisData = ref([]);
const isLoading = ref(false);

// 关键指标
const keyMetrics = ref([
  { title: "平均完成率", value: null, unit: "%" },
  { title: "平均响应时长", value: null, unit: "小时" },
  { title: "平均返工率", value: null, unit: "%" },
  { title: "平均满意度", value: null, unit: "/5" },
]);

// 日期格式化函数（修复年份和月份显示）
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 确保两位月份
  return `${year}-${month}`; // 返回完整格式如 "2025-01"
};

// 日期选择器快捷选项
const pickerOptions = {
  shortcuts: [
    {
      text: "近1个月",
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setMonth(start.getMonth() - 1);
        picker.$emit("input", [formatDate(start), formatDate(end)]);
      },
    },
    {
      text: "近3个月",
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setMonth(start.getMonth() - 3);
        picker.$emit("input", [formatDate(start), formatDate(end)]);
      },
    },
    {
      text: "近6个月",
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setMonth(start.getMonth() - 5);
        picker.$emit("input", [formatDate(start), formatDate(end)]);
      },
    },
  ],
};

// 获取数据
const getList = async () => {
  if (isLoading.value) return;
  isLoading.value = true;

  try {
    const [startMonth, endMonth] = queryParams.timeRange;

    const params = {
      ...queryParams,
      startMonth,
      endMonth,
    };

    const response = await getEstateManagementWorkOrderAnalysisDataList(params);
    analysisData.value =  [];
    total.value =  0;
    updateKeyMetrics(analysisData.value);
  } catch (error) {
    console.error("数据获取失败:", error);
  } finally {
    isLoading.value = false;
  }
};

// 更新关键指标
const updateKeyMetrics = (data) => {
  if (data.length === 0) {
    keyMetrics.value = keyMetrics.value.map(metric => ({ ...metric, value: null }));
    return;
  }

  const completionRate = data.reduce((sum, item) => sum + item.completionRate, 0) / data.length;
  const avgResponseTime = data.reduce((sum, item) => sum + item.avgResponseTime, 0) / data.length;
  const reworkRate = data.reduce((sum, item) => sum + item.reworkRate, 0) / data.length;
  const satisfactionScore = data.reduce((sum, item) => sum + item.satisfactionScore, 0) / data.length;

  keyMetrics.value = [
    { title: "平均完成率", value: completionRate.toFixed(1), unit: "%" },
    { title: "平均响应时长", value: avgResponseTime.toFixed(1), unit: "小时" },
    { title: "平均返工率", value: reworkRate.toFixed(1), unit: "%" },
    { title: "平均满意度", value: satisfactionScore.toFixed(1), unit: "/5" },
  ];
};

// 重置搜索条件
const resetSearch = () => {
  queryParams.timeRange = [];
  queryParams.topIssue = "";
  queryParams.pageNum = 1;
  getList();
};

// 分页处理
const handlePageChange = (newPage) => {
  queryParams.pageNum = newPage;
  getList();
};

const handleSizeChange = (newSize) => {
  queryParams.pageSize = newSize;
  getList();
};

// 初始化默认查询（近6个月）
watch(
    () => queryParams.timeRange.length,
    (hasRange) => {
      if (!hasRange) {
        const end = new Date();
        const start = new Date();
        start.setMonth(start.getMonth() - 12); // 近6个月

        // 确保生成正确的年份和月份
        queryParams.timeRange = [formatDate(start), formatDate(end)];
        console.log("初始化时间范围:", queryParams.timeRange); // 调试输出

        // 延迟执行，确保DOM更新
        setTimeout(() => {
          getList();
        }, 100);
      }
    },
    { immediate: true }
);
// 新增：关键指标背景色（4种不同颜色循环）
const metricColors = ref([
  "#e0f2f1", "#e3f2fd", "#fce4ec", "#f9fbe7", // 绿色、蓝色、粉色、黄色系
]);
</script>

<style scoped>
.filter-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.key-metrics {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.metric-card {
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  text-align: center;
  transition: transform 0.2s ease;
}

.metric-title {
  font-size: 14px;
  color: #6c757d;
  margin-bottom: 8px;
}

.metric-value {
  font-size: 24px;
  font-weight: 500;
  color: #333;
}

.detail-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.empty-tip {
  padding: 40px;
  text-align: center;
  color: #6c757d;
}

.el-pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.el-table th {
  background: #f5f7fa;
  font-weight: 500;
}
.key-metrics {
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); /* 调整卡片宽度 */
  gap: 32px; /* 增加间距 */
}

.metric-card {
  padding: 32px 24px; /* 增加内边距 */
  border-radius: 16px; /* 更圆润的边框 */
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08); /* 更深的阴影 */
  transition: all 0.3s ease; /* 平滑过渡 */
  cursor: pointer; /* 鼠标悬停手势 */
}

/* 鼠标悬停效果 */
.metric-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

/* 不同指标的背景色（对应metricColors数组） */
.metric-card:nth-child(1) { background: #e0f2f1; }
.metric-card:nth-child(2) { background: #e3f2fd; }
.metric-card:nth-child(3) { background: #fce4ec; }
.metric-card:nth-child(4) { background: #f9fbe7; }

.metric-title {
  font-size: 16px; /* 更大的标题字体 */
  color: #4a4a4a; /* 深灰色标题 */
  margin-bottom: 12px;
}

.metric-value {
  font-size: 32px; /* 更大的数值字体 */
  font-weight: 600;
  color: #212121; /* 深黑色数值 */
}

/* 表格和分页样式优化 */
.detail-table {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  overflow: hidden;
}

.el-table th {
  background: #f0f4f8; /* 更浅的表头背景 */
  font-weight: 500;
}

.el-pagination {
  margin-top: 40px;
}
</style>
