<template>
  <div class="order-list admin-page-card">
    <!-- 工单总览 -->
    <div class="order-stats">
      <div class="stat-card stat-total" :class="{ active: activeStat === 'total' }" @click="onStatClick('total')">
        <div class="stat-icon">
          <img :src="iconAll" alt="total" />
        </div>
        <div class="right">
          <div class="stat-value">{{ stats.total }}</div>
          <div class="stat-label">{{ $t("stat.totalOrders") }}</div>
        </div>
      </div>
      <div class="stat-card stat-pending" :class="{ active: activeStat === 'pending' }" @click="onStatClick('pending')">
        <div class="stat-icon">
          <img :src="iconPending" alt="pending" />
        </div>
        <div class="right">
          <div class="stat-value">{{ stats.pending }}</div>
          <div class="stat-label">{{ $t("stat.pendingOrders") }}</div>
        </div>
      </div>
      <div class="stat-card stat-completed" :class="{ active: activeStat === 'completed' }"
        @click="onStatClick('completed')">
        <div class="stat-icon">
          <img :src="iconComplete" alt="complete" />
        </div>
        <div class="right">
          <div class="stat-value">{{ stats.completed }}</div>
          <div class="stat-label">{{ $t("stat.completedOrders") }}</div>
        </div>
      </div>
      <div class="stat-card stat-high" :class="{ active: activeStat === 'high' }" @click="onStatClick('high')">
        <div class="stat-icon">
          <img :src="iconHigh" alt="high" />
        </div>
        <div class="right">
          <div class="stat-value">{{ stats.highPriority }}</div>
          <div class="stat-label">{{ $t("stat.highPriorityOrders") }}</div>
        </div>
      </div>
    </div>

    <el-form :inline="true" :model="filters" class="admin-filter-form" :style="formStyle">
      <el-form-item :label="''">
        <el-input v-model="filters.keyword" :placeholder="'搜索问题名称/工单号'" clearable style="width: 160px" />
      </el-form-item>
      <el-form-item :label="''">
        <el-select v-model="filters.status" :placeholder="'全部状态'" clearable style="width: 120px">
          <el-option label="待处理" value="待处理" />
          <el-option label="已完成" value="已完成" />
        </el-select>
      </el-form-item>
      <el-form-item :label="''">
        <el-select v-model="filters.hospitalId" :placeholder="'输入医院名称'" clearable filterable style="width: 160px">
          <el-option v-for="h in hospitals" :key="h.id" :label="h.name" :value="h.id" />
        </el-select>
      </el-form-item>
      <el-form-item :label="''">
        <el-select v-model="filters.type" :placeholder="'全部类型'" clearable style="width: 110px">
          <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="''">
        <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-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-form-item :label="'处理时间：'">
        <el-date-picker v-model="processDateRange" type="daterange" range-separator="-" :start-placeholder="'开始时间'"
          :end-placeholder="'结束时间'" 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="quickVisible = true">{{
        $t("btn.quickAddOrder")
      }}</el-button>
    </el-form>

    <el-table class="order-table" :data="list" v-loading="loading" stripe
      header-cell-class-name="order-table-header-cell">
      <el-table-column :label="$t('table.id')" prop="orderNo" width="160" />
      <el-table-column :label="$t('table.hospital')" prop="hospitalName" min-width="160" show-overflow-tooltip />
      <el-table-column :label="$t('table.priority')" width="90">
        <template #default="{ row }">
          <div class="priority-row high" v-if="row.priority === '高'">
            {{ row.priority }}
          </div>
          <div class="priority-row medium" v-if="row.priority === '中'">
            {{ row.priority }}
          </div>
          <div class="priority-row low" v-if="row.priority === '低'">
            {{ row.priority }}
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.title')" min-width="300" show-overflow-tooltip>
        <template #default="{ row }">
          <span class="title-link" style="text-decoration: underline;" @click="goHandle(row.id)">{{ row.title
          }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.type')" prop="serviceType" width="120" />
      <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="170">
        <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="170" />
      <el-table-column :label="$t('table.action')" width="160" fixed="right">
        <template #default="{ row }">
          <el-button class="handle smaller" plain :class="row.status === '已完成' ? 'purple-sign' : 'rosein-sign'"
            @click="goProcess(row.id)">{{
              row.status === "已完成" ? $t("btn.modify") : $t("btn.process")
            }}</el-button>
          <el-button class="blue-sign smaller" type="primary" plain @click="goDetail(row.id)">{{
            $t("btn.detail")
          }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="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>

    <!-- 快速提交工单 弹窗（复用公共 OrderFormDialog，mode='create'） -->
    <OrderFormDialog v-model="quickVisible" mode="create" :hospitals="hospitals" :submitting="quickSubmitting"
      @submit="onQuickSubmit" />

    <!-- 工单详情 弹窗 -->
    <OrderDetailDialog v-model="detailVisible" :order-id="currentOrderId" @updated="loadList" />

    <!-- 处理工单 弹窗 -->
    <OrderProcessDialog v-model="processVisible" :order-id="currentOrderId" @processed="loadList" />

    <!-- 工单处理/详情一体化 弹窗（点击标题进入） -->
    <OrderHandleDialog v-model="handleVisible" :order-id="currentOrderId" @updated="loadList" />
  </div>
</template>

<script setup>
import dayjs from "dayjs";
import { computed, onBeforeUnmount, onMounted, reactive, ref } from "vue";
import { dateRangeShortcuts } from "@/utils/dateShortcuts";
import { ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import {
  createAdminOrder,
  getAdminOrders,
} from "@/service/modular/admin";
import { useUserStore } from "@/stores/api/user";
import { useHospitalStore } from "@/stores/api/hospital";
import OrderFormDialog from "./components/OrderFormDialog.vue";
import OrderDetailDialog from "./components/OrderDetailDialog.vue";
import OrderProcessDialog from "./components/OrderProcessDialog.vue";
import OrderHandleDialog from "./components/OrderHandleDialog.vue";
import iconAll from "@/assets/image/admin/orders/all.svg";
import iconPending from "@/assets/image/admin/orders/pending.svg";
import iconComplete from "@/assets/image/admin/orders/complete.svg";
import iconHigh from "@/assets/image/admin/orders/high.svg";

const { t: $t } = useI18n();
const userStore = useUserStore();
const hospitalStore = useHospitalStore();
const hospitals = computed(() => hospitalStore.list);
const list = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const dateRange = ref([]);
const processDateRange = ref([]);
const filters = reactive({
  hospitalId: undefined,
  status: "",
  priority: "",
  type: "",
  keyword: "",
});

const statusClass = (s) =>
  s === "已完成" ? "done" : s === "待处理" ? "pending" : '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];
    }
    if (processDateRange.value?.length === 2) {
      params.completedDateStart = processDateRange.value[0];
      params.completedDateEnd = processDateRange.value[1];
    }
    const res = await getAdminOrders(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, {
    hospitalId: undefined,
    status: "",
    priority: "",
    type: "",
    keyword: "",
  });
  dateRange.value = [];
  processDateRange.value = [];
  activeStat.value = "total";
  onSearch();
};

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

const goDetail = (id) => {
  currentOrderId.value = id;
  detailVisible.value = true;
};
const goProcess = (id) => {
  currentOrderId.value = id;
  processVisible.value = true;
};
const goHandle = (id) => {
  currentOrderId.value = id;
  handleVisible.value = true;
};

// 快速提交工单弹窗
const quickVisible = ref(false);
const quickSubmitting = ref(false);

const onQuickSubmit = async ({ formData }) => {
  // 快速提交模式下补登当前操作人作为登记人
  formData.append("registrarName", userStore.userInfo?.userName || "");
  quickSubmitting.value = true;
  try {
    await createAdminOrder(formData);
    ElMessage.success($t("msg.submitSuccess"));
    quickVisible.value = false;
    loadList();
  } finally {
    quickSubmitting.value = false;
  }
};

// 视口宽度，用于动态计算 filter-form 的缩放比例（基准 1920）
const viewportWidth = ref(typeof window !== "undefined" ? (window.innerWidth - 120) : 1800);
const onResize = () => {
  viewportWidth.value = window.innerWidth - 120;
};
onMounted(() => {
  hospitalStore.ensureLoaded();
  loadList();
  window.addEventListener("resize", onResize);
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", onResize);
});

const formStyle = computed(() => {
  const scale = (viewportWidth.value / 1800).toFixed(4);
  return {
    transform: `scale(${scale})`,
    transformOrigin: "center left",
  };
});
</script>

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

.order-list {
  background: #ffffff;
  border-radius: 16px 16px 16px 16px;
  border: 1px solid #e0e0e0;
  padding: 24px;

  .admin-filter-form {
    width: 1800px !important;
  }

  .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;
    }

    &.info {
      background: #999;
      color: #666;
    }
  }

  & .title-link {
    color: var(--el-color-primary);
    cursor: pointer;
    user-select: text;
    -webkit-user-select: text;

    &:hover {
      color: var(--el-color-primary-light-3);
    }
  }
}

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

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

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

:deep(.order-table) {
  border-radius: 12px 12px 12px 12px;
  border: 1px solid #e0e0e0;
  overflow: hidden;

  // el-table 的 border 是用伪元素绘制外层 1px（左/右/上） + 内部 cell 的 border-right / border-bottom
  // 这里把外层 3 条伪元素边框隐藏，仅保留 cell 之间的分隔线，避免与外层自加 border 叠加
  &::before,
  &::after {
    display: none !important;
  }

  .el-table__inner-wrapper::before .el-table__inner-wrapper::after {
    display: none !important;
  }

  .order-table-header-cell {
    background: #f9faff;
    font-weight: 500;
    font-size: 14px;
    color: #666666;
    line-height: 18px;
  }

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

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

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

    width: 50px;
    height: 30px;
    border-radius: 8px 8px 8px 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;

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

    color: var(--current-color);
  }
}

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

// 工单总览统计
.order-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  position: relative;
  display: flex;
  align-items: center;
  gap: 18px;
  padding: 18px 24px;
  background: #fff;
  border-radius: 16px 16px 16px 16px;
  border: 1px solid #e0e0e0;
  transition:
    transform 0.2s ease,
    box-shadow 0.2s ease,
    background 0.2s ease;
  cursor: pointer;
  user-select: none;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
}

.stat-card.active {
  background: #f0f7ff;
  box-shadow: 0 4px 14px rgba(24, 144, 255, 0.18);
  transform: translateY(-2px);
}

.stat-card.active.stat-pending {
  background: #fff1f0;
  box-shadow: 0 4px 14px rgba(255, 77, 79, 0.18);
}

.stat-card.active.stat-completed {
  background: #f6ffed;
  box-shadow: 0 4px 14px rgba(82, 196, 26, 0.18);
}

.stat-card.active.stat-high {
  background: #fff7e6;
  box-shadow: 0 4px 14px rgba(250, 140, 22, 0.18);
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}

.stat-icon img {
  width: 48px;
  height: 48px;
  object-fit: contain;
}

// 右侧文字区（value + label 垂直堆叠）
.stat-card .right {
  display: flex;
  flex-direction: column-reverse;
  gap: 2px;
  min-width: 0;
}

.stat-value {
  font-size: 26px;
  font-weight: 700;
  color: #333;
  line-height: 1.1;
}

.stat-label {
  font-size: 13px;
  color: #999;
  margin-top: 4px;
}
</style>
