<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  getWorkOrderList,
  getWorkOrderStatistics,
  deleteWorkOrder,
  type WorkOrderVO,
  type WorkOrderStatisticsVO,
  type WorkOrderQueryParams
} from "@/api/risk-workorder";
import { message } from "@/utils/message";
import dayjs from "dayjs";
import * as echarts from "echarts";

import AddIcon from "~icons/ri/add-line";
import SearchIcon from "~icons/ri/search-line";
import RefreshIcon from "~icons/ri/refresh-line";
import FilterIcon from "~icons/ri/filter-3-line";
import MoreIcon from "~icons/ep/more-filled";
import DeleteIcon from "~icons/ep/delete";
import EditPenIcon from "~icons/ep/edit-pen";
import ViewIcon from "~icons/ri/eye-line";
import DownloadIcon from "~icons/ri/download-line";
import TicketIcon from "~icons/ri/ticket-line";
import TimeIcon from "~icons/ri/time-line";
import CheckLineIcon from "~icons/ri/check-line";
import LoaderIcon from "~icons/ri/loader-4-line";

defineOptions({
  name: "WorkorderManagementIndex"
});

const loading = ref(false);
const dataList = ref<WorkOrderVO[]>([]);
const statistics = ref<WorkOrderStatisticsVO>({
  totalCount: 0,
  pendingCount: 0,
  assignedCount: 0,
  processingCount: 0,
  completedCount: 0,
  closedCount: 0,
  rejectedCount: 0,
  overdueCount: 0,
  aboutToExpireCount: 0,
  typeStats: {},
  priorityStats: {}
});

// 查询参数
const queryParams = ref<WorkOrderQueryParams>({
  pageNum: 1,
  pageSize: 10,
  keyword: "",
  orderType: "",
  status: "",
  priority: ""
});

// 分页
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 图表引用
const statusChartRef = ref<HTMLDivElement>();
const priorityChartRef = ref<HTMLDivElement>();
const durationChartRef = ref<HTMLDivElement>();
let statusChart: echarts.ECharts | null = null;
let priorityChart: echarts.ECharts | null = null;
let durationChart: echarts.ECharts | null = null;

// 统计卡片数据
const statCards = computed(() => [
  {
    title: "总工单",
    value: statistics.value.totalCount || 0,
    subText: "↑ 12% 较上月",
    subTextColor: "text-green-500",
    icon: "ri:ticket-line",
    color: "#409eff",
    bgColor: "#ecf5ff"
  },
  {
    title: "待处理",
    value: statistics.value.pendingCount || 0,
    subText: `${statistics.value.aboutToExpireCount || 0} 个即将超期`,
    subTextColor: "text-orange-500",
    icon: "ri:time-line",
    color: "#e6a23c",
    bgColor: "#fdf6ec"
  },
  {
    title: "处理中",
    value: statistics.value.processingCount || 0,
    subText: "进行中",
    subTextColor: "text-blue-500",
    icon: "ri:loader-4-line",
    color: "#409eff",
    bgColor: "#ecf5ff"
  },
  {
    title: "已完成",
    value: statistics.value.completedCount || 0,
    subText: `完成率 ${statistics.value.totalCount ? Math.round((statistics.value.completedCount / statistics.value.totalCount) * 100) : 0}%`,
    subTextColor: "text-green-500",
    icon: "ri:check-line",
    color: "#67c23a",
    bgColor: "#f0f9eb"
  }
]);

// 工单类型选项
const orderTypeOptions = [
  { label: "缺陷", value: "bug" },
  { label: "需求", value: "feature" },
  { label: "任务", value: "task" },
  { label: "事件", value: "incident" },
  { label: "风险处理", value: "risk_handle" },
  { label: "其他", value: "other" }
];

// 优先级选项
const priorityOptions = [
  { label: "紧急", value: "critical", color: "#f56c6c" },
  { label: "高", value: "high", color: "#e6a23c" },
  { label: "中", value: "medium", color: "#409eff" },
  { label: "低", value: "low", color: "#909399" }
];

// 状态选项
const statusOptions = [
  { label: "待处理", value: "pending" },
  { label: "已分派", value: "assigned" },
  { label: "处理中", value: "processing" },
  { label: "已解决", value: "resolved" },
  { label: "已关闭", value: "closed" },
  { label: "已重开", value: "reopened" }
];

// 获取优先级标签类型
function getPriorityType(
  priority?: string
): "danger" | "warning" | "info" | "success" {
  switch (priority) {
    case "critical":
      return "danger";
    case "high":
      return "warning";
    case "medium":
      return "info";
    case "low":
      return "success";
    default:
      return "info";
  }
}

// 获取优先级显示文本
function getPriorityLabel(priority?: string): string {
  const option = priorityOptions.find(o => o.value === priority);
  return option?.label || priority || "未知";
}

// 获取状态标签类型
function getStatusType(
  status?: string
): "success" | "warning" | "info" | "primary" | "danger" {
  switch (status) {
    case "resolved":
    case "closed":
      return "success";
    case "processing":
      return "warning";
    case "assigned":
      return "primary";
    case "pending":
      return "info";
    case "reopened":
      return "danger";
    default:
      return "info";
  }
}

// 获取状态显示文本
function getStatusLabel(status?: string): string {
  const option = statusOptions.find(o => o.value === status);
  return option?.label || status || "未知";
}

// 获取类型显示文本
function getTypeLabel(type?: string): string {
  const option = orderTypeOptions.find(o => o.value === type);
  return option?.label || type || "未知";
}

// 加载工单列表
async function loadWorkOrderList() {
  loading.value = true;
  try {
    const res = await getWorkOrderList({
      ...queryParams.value,
      pageNum: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    });
    const responseData = res.data as any;
    if (responseData.code === 200 && responseData.data) {
      const tableData = responseData.data;
      dataList.value = tableData.rows || [];
      pagination.value.total = tableData.total || 0;
    }
  } catch (error) {
    message("加载工单列表失败", { type: "error" });
  } finally {
    loading.value = false;
  }
}

// 加载统计数据
async function loadStatistics() {
  try {
    const res = await getWorkOrderStatistics();
    const statsResponse = res.data as any;
    if (statsResponse.code === 200 && statsResponse.data) {
      statistics.value = statsResponse.data;
      updateCharts();
    }
  } catch (error) {
    console.error("加载统计数据失败", error);
  }
}

// 初始化状态分布饼图
function initStatusChart() {
  if (!statusChartRef.value) return;
  statusChart = echarts.init(statusChartRef.value);
  updateStatusChart();
}

// 更新状态分布饼图
function updateStatusChart() {
  if (!statusChart) return;
  const data = [
    {
      value: statistics.value.pendingCount || 0,
      name: "待处理",
      itemStyle: { color: "#409eff" }
    },
    {
      value: statistics.value.processingCount || 0,
      name: "处理中",
      itemStyle: { color: "#e6a23c" }
    },
    {
      value: statistics.value.completedCount || 0,
      name: "已完成",
      itemStyle: { color: "#67c23a" }
    },
    {
      value: statistics.value.closedCount || 0,
      name: "已关闭",
      itemStyle: { color: "#909399" }
    }
  ].filter(item => item.value > 0);

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)"
    },
    series: [
      {
        name: "工单状态",
        type: "pie",
        radius: "65%",
        center: ["50%", "50%"],
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        },
        label: {
          show: false
        }
      }
    ]
  };
  statusChart.setOption(option);
}

// 初始化优先级分布饼图
function initPriorityChart() {
  if (!priorityChartRef.value) return;
  priorityChart = echarts.init(priorityChartRef.value);
  updatePriorityChart();
}

// 更新优先级分布饼图
function updatePriorityChart() {
  if (!priorityChart) return;
  const priorityStats = statistics.value.priorityStats || {};
  const data = [
    {
      value: priorityStats.critical || 0,
      name: "紧急",
      itemStyle: { color: "#f56c6c" }
    },
    {
      value: priorityStats.high || 0,
      name: "高",
      itemStyle: { color: "#e6a23c" }
    },
    {
      value: priorityStats.medium || 0,
      name: "中",
      itemStyle: { color: "#409eff" }
    },
    {
      value: priorityStats.low || 0,
      name: "低",
      itemStyle: { color: "#909399" }
    }
  ].filter(item => item.value > 0);

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)"
    },
    series: [
      {
        name: "优先级",
        type: "pie",
        radius: "65%",
        center: ["50%", "50%"],
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        },
        label: {
          show: false
        }
      }
    ]
  };
  priorityChart.setOption(option);
}

// 初始化平均处理时长折线图
function initDurationChart() {
  if (!durationChartRef.value) return;
  durationChart = echarts.init(durationChartRef.value);
  updateDurationChart();
}

// 更新平均处理时长折线图
function updateDurationChart() {
  if (!durationChart) return;
  const months = ["1月", "2月", "3月", "4月", "5月", "6月"];
  const data = [4.5, 4.2, 3.8, 3.5, 3.2, 2.8];

  const option = {
    tooltip: {
      trigger: "axis",
      formatter: "{b}: {c} 天"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "10%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: months,
      axisLine: { lineStyle: { color: "#dcdfe6" } },
      axisLabel: { color: "#606266" }
    },
    yAxis: {
      type: "value",
      name: "天",
      min: 0,
      max: 5,
      axisLine: { show: false },
      splitLine: { lineStyle: { color: "#ebeef5" } },
      axisLabel: { color: "#606266" }
    },
    series: [
      {
        name: "平均处理时长",
        type: "line",
        data,
        smooth: true,
        symbol: "circle",
        symbolSize: 8,
        lineStyle: {
          color: "#409eff",
          width: 2
        },
        itemStyle: {
          color: "#409eff"
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "rgba(64, 158, 255, 0.3)" },
              { offset: 1, color: "rgba(64, 158, 255, 0.05)" }
            ]
          }
        }
      }
    ]
  };
  durationChart.setOption(option);
}

// 更新图表
function updateCharts() {
  updateStatusChart();
  updatePriorityChart();
}

// 搜索
function onSearch() {
  pagination.value.currentPage = 1;
  loadWorkOrderList();
}

// 重置
function resetForm() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    orderType: "",
    status: "",
    priority: ""
  };
  onSearch();
}

// 分页大小变化
function handleSizeChange(val: number) {
  pagination.value.pageSize = val;
  loadWorkOrderList();
}

// 页码变化
function handleCurrentChange(val: number) {
  pagination.value.currentPage = val;
  loadWorkOrderList();
}

// 新建工单
function handleCreate() {
  message("新建工单功能开发中", { type: "info" });
}

// 导出工单
function handleExport() {
  message("导出功能开发中", { type: "info" });
}

// 查看工单详情
function handleView(row: WorkOrderVO) {
  message(`查看工单: ${row.title}`, { type: "info" });
}

// 编辑工单
function handleEdit(row: WorkOrderVO) {
  message(`编辑工单: ${row.title}`, { type: "info" });
}

// 删除工单
async function handleDelete(row: WorkOrderVO) {
  if (!row.id) return;
  try {
    await deleteWorkOrder(row.id);
    message("删除成功", { type: "success" });
    loadWorkOrderList();
    loadStatistics();
  } catch (error) {
    message("删除失败", { type: "error" });
  }
}

// 窗口大小变化时重新渲染图表
function handleResize() {
  statusChart?.resize();
  priorityChart?.resize();
  durationChart?.resize();
}

onMounted(() => {
  loadWorkOrderList();
  loadStatistics();
  initStatusChart();
  initPriorityChart();
  initDurationChart();
  window.addEventListener("resize", handleResize);
});
</script>

<template>
  <div class="workorder-management w-full">
    <!-- 页面标题 -->
    <div class="flex-bc mb-4">
      <div>
        <h2 class="text-xl font-bold">工单管理</h2>
        <p class="text-gray-500 text-sm mt-1">
          分发工单给相关人员，跟踪整改进度
        </p>
      </div>
      <div class="flex gap-2">
        <el-button type="primary" @click="handleCreate">
          <template #icon>
            <component :is="useRenderIcon(AddIcon)" />
          </template>
          创建工单
        </el-button>
        <el-button>
          <template #icon>
            <component :is="useRenderIcon(FilterIcon)" />
          </template>
          筛选
        </el-button>
        <el-button @click="handleExport">
          <template #icon>
            <component :is="useRenderIcon(DownloadIcon)" />
          </template>
          导出
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="mb-4">
      <el-col
        v-for="(card, index) in statCards"
        :key="index"
        :xs="24"
        :sm="12"
        :md="6"
      >
        <el-card shadow="hover" class="stat-card">
          <div class="flex-bc">
            <div>
              <p class="text-gray-500 text-sm">{{ card.title }}</p>
              <p class="text-2xl font-bold mt-1" :style="{ color: card.color }">
                {{ card.value }}
              </p>
              <p class="text-xs mt-1" :class="card.subTextColor">
                {{ card.subText }}
              </p>
            </div>
            <div class="stat-icon" :style="{ backgroundColor: card.bgColor }">
              <el-icon :size="24" :color="card.color">
                <component :is="useRenderIcon(card.icon)" />
              </el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="16" class="mb-4">
      <el-col :xs="24" :md="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="flex-bc">
              <span class="font-medium">工单状态分布</span>
              <el-button link>
                <component :is="useRenderIcon(MoreIcon)" />
              </el-button>
            </div>
          </template>
          <div ref="statusChartRef" class="chart-container" />
          <div class="chart-legend">
            <div class="legend-row">
              <div class="legend-item">
                <span class="legend-dot" style="background-color: #409eff" />
                <span>待处理</span>
              </div>
              <div class="legend-item">
                <span class="legend-dot" style="background-color: #e6a23c" />
                <span>处理中</span>
              </div>
            </div>
            <div class="legend-row">
              <div class="legend-item">
                <span class="legend-dot" style="background-color: #67c23a" />
                <span>已完成</span>
              </div>
              <div class="legend-item">
                <span class="legend-dot" style="background-color: #909399" />
                <span>已逾期</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="flex-bc">
              <span class="font-medium">工单优先级分布</span>
              <el-button link>
                <component :is="useRenderIcon(MoreIcon)" />
              </el-button>
            </div>
          </template>
          <div ref="priorityChartRef" class="chart-container" />
          <div class="chart-legend">
            <div class="legend-row">
              <div class="legend-item">
                <span class="legend-dot" style="background-color: #f56c6c" />
                <span>紧急</span>
              </div>
              <div class="legend-item">
                <span class="legend-dot" style="background-color: #e6a23c" />
                <span>高</span>
              </div>
            </div>
            <div class="legend-row">
              <div class="legend-item">
                <span class="legend-dot" style="background-color: #409eff" />
                <span>中</span>
              </div>
              <div class="legend-item">
                <span class="legend-dot" style="background-color: #909399" />
                <span>低</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="flex-bc">
              <span class="font-medium">平均处理时长</span>
              <el-button link>
                <component :is="useRenderIcon(MoreIcon)" />
              </el-button>
            </div>
          </template>
          <div ref="durationChartRef" class="chart-container" />
          <div class="duration-info">
            <p class="text-gray-500 text-sm">平均处理时长</p>
            <p class="text-3xl font-bold text-blue-500">2.8 天</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 工单列表 -->
    <el-card shadow="hover">
      <template #header>
        <div class="flex-bc">
          <span class="font-medium">工单列表</span>
          <div class="flex gap-2">
            <el-input
              v-model="queryParams.keyword"
              placeholder="搜索工单..."
              clearable
              style="width: 200px"
              @keyup.enter="onSearch"
            >
              <template #prefix>
                <component :is="useRenderIcon(SearchIcon)" />
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table v-loading="loading" :data="dataList" style="width: 100%">
        <el-table-column label="工单编号" width="140">
          <template #default="{ row }">
            <span class="font-mono">{{ row.orderCode || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目名称" min-width="150">
          <template #default="{ row }">
            <div class="flex items-center gap-2">
              <div class="size-8 rounded bg-blue-100 flex-c">
                <el-icon color="#409eff"
                  ><component :is="useRenderIcon('ri:building-line')"
                /></el-icon>
              </div>
              <span>{{ row.projectName || "-" }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="工单标题" min-width="200">
          <template #default="{ row }">
            <div class="font-medium">{{ row.title }}</div>
          </template>
        </el-table-column>
        <el-table-column label="负责人" width="120">
          <template #default="{ row }">
            <div class="flex items-center gap-2">
              <el-avatar :size="24" :src="row.handlerAvatar">
                {{ row.handlerName?.charAt(0) || "?" }}
              </el-avatar>
              <span>{{ row.handlerName || "未分配" }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="优先级" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getPriorityType(row.priority)"
              size="small"
              effect="light"
            >
              {{ getPriorityLabel(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
              effect="light"
            >
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="120">
          <template #default="{ row }">
            {{
              row.createTime ? dayjs(row.createTime).format("YYYY-MM-DD") : "-"
            }}
          </template>
        </el-table-column>
        <el-table-column label="截止时间" width="120">
          <template #default="{ row }">
            <span :class="{ 'text-red-500': row.isOverdue }">
              {{
                row.deadline ? dayjs(row.deadline).format("YYYY-MM-DD") : "-"
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">
              <component :is="useRenderIcon(ViewIcon)" />
            </el-button>
            <el-button link type="primary" @click="handleEdit(row)">
              <component :is="useRenderIcon(EditPenIcon)" />
            </el-button>
            <el-dropdown trigger="click">
              <el-button link>
                <component :is="useRenderIcon(MoreIcon)" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleDelete(row)">
                    <span class="text-red-500">删除</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.workorder-management {
  padding: 16px 80px 16px 16px;

  .stat-card {
    .stat-icon {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 48px;
      height: 48px;
      border-radius: 8px;
    }
  }

  .chart-card {
    .chart-container {
      height: 200px;
    }
  }

  .chart-legend {
    margin-top: 16px;

    .legend-row {
      display: flex;
      justify-content: space-around;
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .legend-item {
      display: flex;
      gap: 6px;
      align-items: center;
      font-size: 13px;
      color: var(--el-text-color-regular);

      .legend-dot {
        width: 10px;
        height: 10px;
        border-radius: 50%;
      }
    }
  }

  .duration-info {
    padding-top: 16px;
    margin-top: 16px;
    text-align: center;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}
</style>
