<template>
  <div class="order-list admin-page-card">
    <el-form :inline="true" :model="filters" class="admin-filter-form filter-form">
      <el-form-item :label="''">
        <el-input v-model="filters.keyword" :placeholder="$t('placeholder.keyword')" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item :label="''">
        <el-select v-model="filters.status" :placeholder="'全部状态'" clearable style="width: 140px">
          <el-option label="待处理" value="待处理" />
          <el-option label="已完成" value="已完成" />
          <!-- <el-option label="取消" value="取消" /> -->
        </el-select>
      </el-form-item>
      <el-form-item :label="''">
        <el-select v-model="filters.priority" :placeholder="'全部优先级'" clearable style="width: 120px">
          <el-option label="高" value="高" />
          <el-option label="中" value="中" />
          <el-option label="低" value="低" />
        </el-select>
      </el-form-item>
      <el-form-item :label="''">
        <el-select v-model="filters.type" :placeholder="'全部类型'" clearable style="width: 120px">
          <el-option label="故障问题" value="故障问题" />
          <el-option label="使用咨询" value="使用咨询" />
          <el-option label="功能需求" value="功能需求" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('table.time')">
        <el-date-picker v-model="dateRange" type="daterange" range-separator="-"
          :start-placeholder="$t('common.startDate')" :end-placeholder="$t('common.endDate')" value-format="YYYY-MM-DD"
          :shortcuts="dateRangeShortcuts" style="width: 240px" />
      </el-form-item>

      <el-button type="primary" plain @click="onSearch">{{
        $t("btn.query")
      }}</el-button>
      <el-button @click="onReset">{{ $t("btn.reset") }}</el-button>
      <el-button type="primary" @click="goQuick">+ 新建工单</el-button>
    </el-form>

    <!-- 工单总览 -->
    <!-- <div class="order-stats">
        <div class="stat-card stat-total" :class="{ active: activeStat === 'total' }" @click="onStatClick('total')">
          <div class="stat-icon">📋</div>
          <div class="stat-value">{{ stats.total }}</div>
          <div class="stat-label">{{ $t("stat.totalOrders") }}</div>
        </div>
        <div class="stat-card stat-pending" :class="{ active: activeStat === 'pending' }"
          @click="onStatClick('pending')">
          <div class="stat-icon">⏳</div>
          <div class="stat-value">{{ stats.pending }}</div>
          <div class="stat-label">{{ $t("stat.pendingOrders") }}</div>
        </div>
        <div class="stat-card stat-completed" :class="{ active: activeStat === 'completed' }"
          @click="onStatClick('completed')">
          <div class="stat-icon">✅</div>
          <div class="stat-value">{{ stats.completed }}</div>
          <div class="stat-label">{{ $t("stat.completedOrders") }}</div>
        </div>
        <div class="stat-card stat-high" :class="{ active: activeStat === 'high' }" @click="onStatClick('high')">
          <div class="stat-icon">🔴</div>
          <div class="stat-value">{{ stats.highPriority }}</div>
          <div class="stat-label">{{ $t("stat.highPriorityOrders") }}</div>
        </div>
      </div> -->
    <el-table class="admin-table" :data="list" v-loading="loading" stripe
      header-cell-class-name="admin-table-header-cell">
      <el-table-column :label="$t('table.id')" prop="orderNo" width="160" />
      <el-table-column :label="$t('table.priority')" width="90">
        <template #default="{ row }">
          <div class="priority-row" :class="priorityClass(row.priority)">{{ row.priority }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.title')" prop="title" min-width="250" show-overflow-tooltip />
      <el-table-column :label="$t('table.type')" prop="serviceType" width="auto" />
      <el-table-column :label="$t('table.dept')" prop="department" min-width="120" show-overflow-tooltip />
      <el-table-column :label="$t('table.submitter')" prop="submitter" min-width="100" show-overflow-tooltip />
      <el-table-column :label="$t('table.feedbackchannel')" prop="feedbackChannel" min-width="100"
        show-overflow-tooltip />
      <el-table-column :label="$t('table.registrar')" prop="registrarName" min-width="100" show-overflow-tooltip />
      <el-table-column :label="$t('table.handler')" prop="processName" min-width="100" show-overflow-tooltip />
      <el-table-column :label="$t('table.handleTime')" prop="completedAt" width="165">
        <template #default="{ row }">
          {{ row.completedAt || "-" }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.status')" width="100">
        <template #default="{ row }">
          <div class="status-pill" :class="statusClass(row.status)">{{ row.status }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.time')" prop="createdAt" width="160" />
      <el-table-column :label="$t('table.action')" min-width="250" fixed="right">
        <template #default="{ row }">
          <el-button class="purple-sign smaller" plain @click="goDetail(row.id)">{{
            $t("btn.view")
          }}</el-button>
          <el-button class="rosein-sign smaller" plain :class="{ 'disabled-done': row.status === '已完成' }"
            @click="goEdit(row.id)">{{
              $t("btn.edit")
            }}</el-button>
          <el-button class="yellow-sign smaller" plain :class="{ 'disabled-done': row.status === '已完成' }"
            @click="cancel(row)">{{
              $t("btn.cancel") }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="admin-pagination">
      <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]" :total="total"
        layout="total, sizes, prev, pager, next, jumper" @size-change="loadList" @current-change="loadList" />
    </div>

    <!-- 工单详情 弹窗（查看操作直接打开弹窗，编辑成功后刷新列表） -->
    <OrderDetailDialog v-model="detailVisible" :order-id="currentOrderId" @updated="loadList" />
  </div>
</template>

<script setup>
import dayjs from "dayjs";
import { onMounted, onBeforeUnmount, reactive, ref } from "vue";
import { dateRangeShortcuts } from "@/utils/dateShortcuts";
import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { useI18n } from "vue-i18n";
import { getHospitalOrders, cancelHospitalOrder } from "@/service/modular/hospital";
import { useOrderDialogStore } from "@/stores/orderDialog";
import OrderDetailDialog from "./OrderDetailDialog.vue";

const { t: $t } = useI18n();
const route = useRoute();
const router = useRouter();
const list = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const dateRange = ref([]);
const filters = reactive({
  status: "",
  priority: "",
  type: "",
  keyword: "",
});

const priorityClass = (p) => {
  if (p === "高") return "high";
  if (p === "中") return "medium";
  if (p === "低") return "low";
  return "info";
};
const statusClass = (s) => {
  if (s === "已完成") return "done";
  if (s === "待处理") return "pending";
  if (s === "处理中") return "processing";
  if (s === "已取消") return "cancel";
  return "info";
};

// 工单总览统计
// const stats = reactive({
//   total: 0,
//   pending: 0,
//   completed: 0,
//   highPriority: 0,
// });
// 当前选中的总览卡片：total | pending | completed | high
// const activeStat = ref("total");
// const parseStats = (res) => {
//   let payload = res?.data;
//   if (typeof payload === "string") {
//     try {
//       payload = JSON.parse(payload);
//     } catch (_) {
//       payload = {};
//     }
//   }

//   stats.completed = Number(payload?.TotalStatus1 ?? 0);
//   stats.pending = Number(payload?.TotalStatus2 ?? 0);
//   stats.total = stats.completed + stats.pending;
//   stats.highPriority = Number(payload?.TotalPriority ?? 0);
// };

const loadList = async () => {
  loading.value = true;
  try {
    const params = { page: page.value, pageSize: pageSize.value, ...filters };
    if (dateRange.value?.length === 2) {
      params.startDate = dateRange.value[0];
      params.endDate = dateRange.value[1];
    }
    const res = await getHospitalOrders(params);
    list.value = res?.list || [];
    list.value.forEach((item) => {
      if (item.createdAt) {
        item.createdAt = dayjs(item.createdAt).format("YYYY-MM-DD HH:mm:ss");
      }
      if (item.completedAt) {
        item.completedAt = dayjs(item.completedAt).format(
          "YYYY-MM-DD HH:mm:ss",
        );
      }
    });
    total.value = res?.total || 0;
    // parseStats(res);
  } finally {
    loading.value = false;
  }
};

// 总览卡片点击：根据卡片类型设置筛选条件并重新加载
const onStatClick = (type) => {
  activeStat.value = type;
  if (type === "total") {
    filters.status = "";
    filters.priority = "";
  } else if (type === "pending") {
    filters.status = "待处理";
    filters.priority = "";
  } else if (type === "completed") {
    filters.status = "已完成";
    filters.priority = "";
  } else if (type === "high") {
    filters.status = "";
    filters.priority = "高";
  }
  page.value = 1;
  loadList();
};

const onSearch = () => {
  page.value = 1;
  loadList();
};
const onReset = () => {
  Object.assign(filters, {
    status: "",
    priority: "",
    type: "",
    keyword: "",
  });
  dateRange.value = [];
  activeStat.value = "total";
  onSearch();
};

// sessionStorage 缓存 key：保存列表页的筛选/分页状态，避免从详情或处理页返回时被重置
const LIST_STATE_KEY = "hospital_orders_list_state";

const saveListState = () => {
  try {
    const state = {
      filters: { ...filters },
      dateRange: Array.isArray(dateRange.value) ? [...dateRange.value] : [],
      page: page.value,
      pageSize: pageSize.value,
      activeStat: activeStat.value,
    };
    sessionStorage.setItem(LIST_STATE_KEY, JSON.stringify(state));
  } catch (_) {
    // 隐私模式或存储满等情况静默忽略，避免影响主流程
  }
};

const restoreListState = () => {
  try {
    const raw = sessionStorage.getItem(LIST_STATE_KEY);
    if (!raw) return;
    const state = JSON.parse(raw);
    if (!state || typeof state !== "object") return;
    if (state.filters && typeof state.filters === "object") {
      Object.assign(filters, state.filters);
    }
    if (Array.isArray(state.dateRange)) {
      dateRange.value = state.dateRange;
    }
    if (typeof state.page === "number" && state.page > 0) {
      page.value = state.page;
    }
    if (typeof state.pageSize === "number" && state.pageSize > 0) {
      pageSize.value = state.pageSize;
    }
    if (typeof state.activeStat === "string") {
      activeStat.value = state.activeStat;
    }
  } catch (_) {
    // 解析失败时静默忽略
  }
};

const clearListState = () => {
  try {
    sessionStorage.removeItem(LIST_STATE_KEY);
  } catch (_) {
    /* noop */
  }
};

const goDetail = (id) => {
  // "查看" 改为弹窗：复用 OrderDetailDialog
  currentOrderId.value = id;
  detailVisible.value = true;
};

// 工单详情弹窗状态
const currentOrderId = ref("");
const detailVisible = ref(false);

// 工单表单弹窗：通过全局 store 控制（弹窗本体挂在 AdminLayout）
const orderDialogStore = useOrderDialogStore();

const goEdit = (id) => {
  orderDialogStore.openEdit(id);
};
const goQuick = () => {
  orderDialogStore.open();
};

// 监听全局事件，提交成功后刷新列表
const onOrderSaved = () => loadList();

const cancel = async (row) => {
  try {
    await ElMessageBox.confirm(
      $t('msg.confirmCancelOrder').replace('{orderId}', row.title),
      $t('common.confirm'),
      {
        type: "warning",
        confirmButtonText: $t('common.confirm'),
        cancelButtonText: $t('common.cancel'),
      },
    );
    await cancelHospitalOrder(row.id);
    ElMessage.success($t('msg.cancelSuccess'));
    loadList();
  } catch (_) {
    /* canceled */
  }
};

// 跳转到详情 / 处理页前缓存当前搜索状态（编辑已改为弹窗，不再走路由）
onBeforeRouteLeave((to) => {
  const path = to?.path || "";
  if (
    path.startsWith("/hospital/orders/detail") ||
    path.startsWith("/hospital/orders/process")
  ) {
    saveListState();
  }
});

// 从工作台卡片跳转带入的查询参数填充筛选与时间范围
const applyRouteQuery = () => {
  const { status, priority, type, keyword, startDate, endDate } = route.query;
  if (status) filters.status = String(status);
  if (priority) filters.priority = String(priority);
  if (type) filters.type = String(type);
  if (keyword) filters.keyword = String(keyword);
  if (startDate && endDate) dateRange.value = [String(startDate), String(endDate)];
};

onMounted(() => {
  applyRouteQuery();
  // 先还原从详情 / 处理页返回时的筛选与分页状态，再清缓存避免后续直接进入页面仍套用旧值
  restoreListState();
  clearListState();
  loadList();
  // 监听全局事件，提交成功后刷新列表（仅挂载时挂一次）
  window.addEventListener("hospital-order-saved", onOrderSaved);
});
onBeforeUnmount(() => {
  window.removeEventListener("hospital-order-saved", onOrderSaved);
});
</script>

<style scoped lang="scss">
@use "@/assets/style/admin-common.scss" as *;

.filter-form {
  margin-bottom: 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
  width: 100%;

  :deep(.el-form-item),
  :deep(.el-button) {
    margin: 0 0 0 0;
  }

  :deep(.el-button:last-child) {
    margin-left: auto;
  }
}

// 优先级徽章（与 admin/orders/list.vue 保持一致）
.priority-row {
  width: 50px;
  height: 30px;
  border-radius: 8px 8px 8px 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  color: var(--current-color);
  font-weight: 500;
  font-size: 14px;

  &::before {
    content: "";
    display: block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--current-color);
  }

  &.high {
    --current-color: #ff383c;
    background: #ffebec;
  }

  &.medium {
    --current-color: #ff8d28;
    background: #ffefe2;
  }

  &.low {
    --current-color: #3289fb;
    background: #eaf3ff;
  }

  &.info {
    --current-color: #999999;
    background: #f0f0f0;
  }
}

// 状态徽章
.status-pill {
  width: 66px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  border-radius: 8px 8px 8px 8px;
  font-weight: 500;
  font-size: 14px;

  &.done {
    background: #E8FFEE;
    color: #34C759;
  }

  &.pending {
    background: #FFEFE2;
    color: #FF8D28;
  }

  &.processing {
    background: #EAF3FF;
    color: #3289FB;
  }

  &.cancel {
    background: #F0F0F0;
    color: #999999;
  }

  &.info {
    background: #F0F0F0;
    color: #666666;
  }
}
</style>

<style lang="scss">
@use "@/assets/style/admin-common.scss" as *;
</style>
