<template>
	<div class="home-container">
		<!-- 快捷入口（样式对齐参考稿 quick-section） -->
		<div class="quick-section">
			<div class="section-title">
				<h3>
					<i class="fa fa-bolt section-title-bolt" aria-hidden="true"></i>
					快捷入口
				</h3>
				<button type="button" class="edit-quick-btn" @click="openQuickEdit">
					<i class="fa fa-pencil" aria-hidden="true"></i>
					编辑
				</button>
			</div>
			<div class="quick-grid">
				<div
					v-for="(item, idx) in quickDisplayItems"
					:key="`${item.id}-${idx}`"
					class="quick-btn"
					:class="{ 'highlight-card': item.highlight }"
					role="button"
					tabindex="0"
					@click="onQuickCardClick(item)"
					@keydown.enter.prevent="onQuickCardClick(item)"
				>
					<div v-if="item.highlight" class="hot-badge">
						<i class="fa fa-star" aria-hidden="true"></i>
						常用
					</div>
					<div class="quick-icon">
						<i :class="item.iconClass" aria-hidden="true"></i>
					</div>
					<span>{{ item.title }}</span>
				</div>
			</div>
		</div>

		<el-dialog
			v-model="quickEditVisible"
			title="编辑快捷入口"
			width="560px"
			destroy-on-close
			class="screenconsole-quick-edit"
			append-to-body
		>
			<div class="quick-edit-body">
				<div v-for="(_, idx) in quickEditDraft.slots" :key="idx" class="edit-item">
					<div class="edit-item-index">{{ idx + 1 }}.</div>
					<div class="edit-item-select">
						<label>选择功能</label>
						<el-select
							v-model="quickEditDraft.slots[idx]"
							placeholder="请选择"
							style="width: 100%"
							filterable
							popper-class="screenconsole-quick-edit-select-popper"
						>
							<el-option
								v-for="opt in quickMenuOptions"
								:key="opt.id"
								:label="opt.title"
								:value="opt.id"
								:disabled="isQuickEntryOptionTakenByOtherSlot(opt.id, idx)"
							/>
						</el-select>
					</div>
					<div class="edit-item-radio">
						<label>标记为常用</label>
						<div class="radio-group">
							<el-radio v-model="quickEditDraft.highlightIndex" :label="idx">橙色高亮</el-radio>
						</div>
					</div>
				</div>
			</div>
			<template #footer>
				<el-button @click="quickEditVisible = false">取消</el-button>
				<el-button
					type="primary"
					class="screenconsole-quick-save-btn"
					:loading="quickSaving"
					@click="saveQuickEdit"
				>
					保存修改
				</el-button>
			</template>
		</el-dialog>

		<!-- 第一行 -->
		<el-row :gutter="15" class="home-row">
		<el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="6" style="margin-bottom: 10px;">
			<StatusCards :statusData="pendingItems" />
		</el-col>
		<el-col :xs="24" :sm="24" :md="24" :lg="16" :xl="18">
			<InfoCards  :summaryData="dataSummary" />
		</el-col>
		</el-row>

		<el-row :gutter="15" class="home-row">
		<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" style="margin-bottom: 10px;">
			<BorrowRankingList/>
		</el-col>
		<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
			<BorrowTrendsChart />
		</el-col>
		</el-row>
	</div>
  </template>
  
  

<script lang="ts" setup name="screenconsole">
import { reactive, onMounted, ref, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useI18n } from 'vue-i18n';
import { useRoutesList } from '/@/stores/routesList';
import { filterRoutesFun } from '/@/utils/routeFilter';
import * as api from './api';

import StatusCards from './component/StatusCards.vue';
import InfoCards from './component/InfoCards.vue';
import BorrowTrendsChart from './component/BorrowTrendsChart.vue';
import BorrowRankingList from './component/BorrowRankingList.vue';
import {
	QUICK_ENTRY_SLOT_COUNT,
	buildQuickMenuOptionsFromRoutes,
	loadQuickEntryPrefs,
	pickPreferredQuickSlotIds,
	saveQuickEntryPrefs,
	resolvePathForQuickOption,
	type QuickEntryMenuOption,
} from './quickEntry';
import * as workbenchApi from './userWorkbenchShortcutApi';
import {
	mapWorkbenchShortcutListToState,
	syncQuickSlotsToServer,
	buildRecordBySlotFromList,
} from './quickEntryServerAdapter';
import { Session } from '/@/utils/storage';

const router = useRouter();
const { t } = useI18n();
const storesRoutesList = useRoutesList();
const { routesList } = storeToRefs(storesRoutesList);

/** 与侧栏子菜单一致的叶子路由列表（随权限/菜单接口变化） */
const quickMenuOptions = computed(() =>
	buildQuickMenuOptionsFromRoutes(filterRoutesFun(routesList.value as RouteItem[]), (k) => t(k))
);

function getQuickOptionById(id: string): QuickEntryMenuOption | undefined {
	return quickMenuOptions.value.find((o) => o.id === id);
}

const quickSlotMenuIds = ref<string[]>([]);
const quickHighlightIndex = ref(0);
/** 与 `/api/system/user_workbench_shortcut/` 中每条 id 的对应，用于 PATCH */
const quickServerRecordBySlot = ref(new Map<number, { id: string | number }>());
const quickEntryHydrated = ref(false);
const quickSaving = ref(false);

function applyQuickSlotsFromRoutes() {
	const opts = quickMenuOptions.value;
	if (!opts.length) return;
	const idSet = new Set(opts.map((o) => o.id));
	const persisted = loadQuickEntryPrefs();

	const seed = quickSlotMenuIds.value.length
		? [...quickSlotMenuIds.value]
		: persisted.menuIds.filter((id) => idSet.has(id));

	const used = new Set<string>();
	const next: string[] = [];

	for (const id of seed) {
		if (next.length >= QUICK_ENTRY_SLOT_COUNT) break;
		if (idSet.has(id) && !used.has(id)) {
			next.push(id);
			used.add(id);
		}
	}

	if (next.length === 0) {
		for (const id of pickPreferredQuickSlotIds(opts)) {
			if (next.length >= QUICK_ENTRY_SLOT_COUNT) break;
			if (!used.has(id)) {
				next.push(id);
				used.add(id);
			}
		}
	} else {
		while (next.length < QUICK_ENTRY_SLOT_COUNT) {
			const fill = opts.find((o) => !used.has(o.id));
			if (!fill) break;
			next.push(fill.id);
			used.add(fill.id);
		}
	}

	const wasEmpty = quickSlotMenuIds.value.length === 0;
	quickSlotMenuIds.value = next.slice(0, QUICK_ENTRY_SLOT_COUNT);

	if (wasEmpty) {
		quickHighlightIndex.value = Math.min(
			Math.max(0, persisted.highlightIndex),
			QUICK_ENTRY_SLOT_COUNT - 1
		);
	}
}

/**
 * 优先拉取用户工作台快捷入口；无数据或失败时走本地/默认填充（与原先一致）
 */
async function hydrateQuickEntry() {
	const opts = quickMenuOptions.value;
	if (!opts.length) return;
	if (quickEntryHydrated.value) {
		applyQuickSlotsFromRoutes();
		return;
	}
	try {
		const res = await workbenchApi.listUserWorkbenchShortcuts();
		if (res.code === 2000) {
			const list = workbenchApi.unwrapShortcutListData(res.data);
			const mapped = mapWorkbenchShortcutListToState(list, opts);
			if (mapped) {
				quickSlotMenuIds.value = mapped.menuIds;
				quickHighlightIndex.value = mapped.highlightIndex;
				quickServerRecordBySlot.value = mapped.recordBySlot;
				quickEntryHydrated.value = true;
				return;
			}
		}
	} catch (e) {
		console.error('load user_workbench_shortcut', e);
	}
	applyQuickSlotsFromRoutes();
	quickEntryHydrated.value = true;
}

watch(quickMenuOptions, () => {
	void hydrateQuickEntry();
}, { immediate: true });

/** 与「常用」单选对应的目标菜单 path（id），用 id 判断高亮，避免无权限项被滤掉后下标错位 */
const quickFrequentMenuId = computed(() => {
	const ids = quickSlotMenuIds.value;
	const h = quickHighlightIndex.value;
	if (h < 0 || h >= ids.length) return null;
	return ids[h] ?? null;
});

/**
 * 仅展示当前 `routesList` 过滤后仍有权访问的项（`quickMenuOptions` 中存在的 path）；
 * 无权限/菜单已下线的项在列表中不渲染。
 */
const quickDisplayItems = computed(() => {
	const frequentId = quickFrequentMenuId.value;
	return quickSlotMenuIds.value
		.map((menuId) => {
			const opt = getQuickOptionById(menuId);
			if (!opt) return null;
			return {
				...opt,
				highlight: frequentId !== null && opt.id === frequentId,
			};
		})
		.filter((x): x is QuickEntryMenuOption & { highlight: boolean } => x !== null);
});

const quickEditVisible = ref(false);
const quickEditDraft = reactive({
	slots: [] as string[],
	highlightIndex: 0,
});

/** 编辑弹窗内：某菜单已被其它格子选中时，当前格子的下拉中禁用该项（避免重复） */
function isQuickEntryOptionTakenByOtherSlot(optionId: string, slotIndex: number): boolean {
	return quickEditDraft.slots.some((id, i) => i !== slotIndex && id === optionId);
}

function openQuickEdit() {
	const pad = quickSlotMenuIds.value.slice(0, QUICK_ENTRY_SLOT_COUNT);
	const used = new Set(pad);
	while (pad.length < QUICK_ENTRY_SLOT_COUNT) {
		const o = quickMenuOptions.value.find((x) => !used.has(x.id));
		if (!o) break;
		pad.push(o.id);
		used.add(o.id);
	}
	quickEditDraft.slots = pad;
	quickEditDraft.highlightIndex = quickHighlightIndex.value;
	quickEditVisible.value = true;
}

async function saveQuickEdit() {
	quickSaving.value = true;
	try {
		quickSlotMenuIds.value = [...quickEditDraft.slots];
		quickHighlightIndex.value = quickEditDraft.highlightIndex;
		const opts = quickMenuOptions.value;
		await syncQuickSlotsToServer(
			quickSlotMenuIds.value,
			quickHighlightIndex.value,
			new Map(quickServerRecordBySlot.value),
			opts
		);
		const res = await workbenchApi.listUserWorkbenchShortcuts();
		if (res.code === 2000) {
			const list = workbenchApi.unwrapShortcutListData(res.data);
			const nextMap = buildRecordBySlotFromList(list, opts);
			if (nextMap.size) {
				quickServerRecordBySlot.value = nextMap;
			}
		}
		saveQuickEntryPrefs({
			menuIds: [...quickSlotMenuIds.value],
			highlightIndex: quickHighlightIndex.value,
		});
		quickEditVisible.value = false;
		ElMessage.success('快捷入口已更新');
	} catch (e) {
		console.error(e);
		ElMessage.error('保存失败，请稍后再试');
	} finally {
		quickSaving.value = false;
	}
}

function onQuickCardClick(item: QuickEntryMenuOption & { highlight?: boolean }) {
	const path = resolvePathForQuickOption(router, item);
	if (!path) {
		ElMessage.warning('未找到对应菜单路由，请联系管理员检查菜单配置');
		return;
	}
	router.push(path);
}

const pendingItems = ref({
  pending_approval: 0,
  pending_return: 0,
  pending_overdue: 0,
  pending_maintenance: 0,
  pending_restock: 0,
  pending_warehousing: 0,
  pending_inventory_check: 0
})

const dataSummary = ref({
	total_devices: 0,
	borrowed_devices: 0,
	available_devices: 0,
	today_borrowed: 0,
	today_returned: 0,
	total_borrows: 0,
	total_borrowers: 0,
})

/* 看板字段：pending_approval 待审批；borrowed 已借出；overdue 已逾期；pending_repair 待维修 */
onMounted(async () => {
	try {
		const userInfo = Session.get('userInfo');
		if (userInfo?.username === '平台管理员') return;

		const res = await api.dashboardStatistics();
		if (res.code === 2000) {
			pendingItems.value.pending_approval = res.data.pending_approval;
			pendingItems.value.pending_return = res.data.borrowed;
			pendingItems.value.pending_maintenance = res.data.pending_repair;
			pendingItems.value.pending_overdue = res.data.overdue;
		}

		const ress = await api.GetOverviewList();
		if (ress.code === 2000) {
			dataSummary.value = ress.data;
		}
	} catch (error) {
		console.error('获取数据失败:', error);
	}
});

</script>

<style scoped lang="scss">
.home-container {
  padding: 20px;
  min-height: 100vh;
  box-sizing: border-box;
}

.home-row {
  margin-bottom: 10px;
  
  // 小屏幕时减少间距
  @media (max-width: 768px) {
    margin-bottom: 15px;
    
    :deep(.el-col) {
      margin-bottom: 15px;
    }
  }
}

.home-col-table {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

// 响应式断点
@media (max-width: 576px) {
  .home-container {
    padding: 10px;
  }
  
  .home-row {
    margin-bottom: 10px;
  }
}

@media (min-width: 577px) and (max-width: 768px) {
  .home-container {
    padding: 15px;
  }
}

@media (min-width: 1920px) {
  .home-container {
    max-width: 1920px;
    margin: 0 auto;
  }
}

/* ========= 快捷入口（与参考 HTML quick-section 一致） ========= */
.quick-section {
  margin-bottom: 24px;
  /* 减轻 Windows 下 transform / 半透明层导致的文字发虚 */
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-rendering: optimizeLegibility;
}

.section-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 14px;
}

.section-title h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  color: #0f172a;
  display: flex;
  align-items: center;
  gap: 6px;
}

.section-title-bolt {
  color: #3b82f6;
  font-size: 20px;
}

.edit-quick-btn {
  background: #f1f5f9;
  border-radius: 40px;
  padding: 6px 14px;
  font-size: 0.8rem;
  font-weight: 500;
  color: #475569;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  gap: 6px;
  font-family: inherit;
  line-height: 1.4;
}

.edit-quick-btn:hover {
  background: #e6edf5;
  color: #2563eb;
  border-color: #cbd5e1;
}

.quick-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 12px;
}

.quick-btn {
  background: white;
  border-radius: 14px;
  padding: 14px 8px 12px 8px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.2s ease, box-shadow 0.2s ease, background 0.2s ease;
  border: 1px solid #eef2f8;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.02);
  position: relative;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-rendering: optimizeLegibility;
}

.quick-btn:hover {
  border-color: #cbdff2;
  box-shadow: 0 8px 16px -6px rgba(0, 0, 0, 0.12);
  background: #fefefe;
}

.quick-icon {
  font-size: 2rem;
  margin: 0 auto 11px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #eff6ff;
  width: 52px;
  height: 52px;
  border-radius: 50%;
  line-height: 1;
  color: #2563eb;
  transition: all 0.2s;
}

.quick-icon i {
  font-size: 2rem;
}

.quick-btn span {
  display: block;
  font-weight: 600;
  font-size: 13px;
  margin-top: 0;
  color: #1e293b;
  line-height: 1.35;
  letter-spacing: 0.01em;
}

.quick-btn.highlight-card {
  background: #ff7c42;
  border-color: #e55a2e;
  box-shadow: 0 8px 18px rgba(255, 100, 50, 0.25);
}

.quick-btn.highlight-card .quick-icon {
  background: rgba(255, 255, 255, 0.25);
  color: white;
}

.quick-btn.highlight-card span {
  color: white;
  font-weight: 700;
}

.quick-btn.highlight-card:hover {
  background: #e55a2e;
  box-shadow: 0 10px 20px rgba(229, 90, 46, 0.32);
}

.hot-badge {
  position: absolute;
  top: 6px;
  right: 6px;
  /* 不用 backdrop-filter，避免与整卡合成层叠导致字迹发糊 */
  background: #ffffff;
  color: #ff7c42;
  font-size: 11px;
  font-weight: 700;
  padding: 3px 7px;
  border-radius: 40px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  letter-spacing: 0.02em;
  z-index: 2;
  display: flex;
  align-items: center;
  gap: 3px;
  -webkit-font-smoothing: antialiased;
  line-height: 1.2;
}

.hot-badge i {
  font-size: 10px;
}

.quick-btn:not(.highlight-card) .quick-icon {
  background: #eff6ff;
  color: #3b82f6;
}

.quick-btn:not(.highlight-card):hover .quick-icon {
  background: #e0edff;
  color: #2563eb;
}

@media (max-width: 1100px) {
  .quick-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
  }
}

@media (max-width: 780px) {
  .quick-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }

  .quick-btn {
    padding: 12px 6px 10px 6px;
  }

  .quick-icon {
    margin-bottom: 8px;
    width: 46px;
    height: 46px;
  }

  .quick-icon i {
    font-size: 1.35rem;
  }

  .quick-btn span {
    font-size: 12px;
  }

  .hot-badge {
    font-size: 10px;
    padding: 2px 6px;
    top: 4px;
    right: 4px;
  }
}

@media (max-width: 500px) {
  .quick-grid {
    grid-template-columns: 1fr;
  }
}

</style>

<!-- 编辑弹窗挂载到 body，单独块 -->
<style lang="scss">
/* 下拉层挂到 body，与弹窗样式分离 */
.screenconsole-quick-edit-select-popper {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;

  .el-select-dropdown__item {
    font-size: 13px;
    font-weight: 400;
    color: #1e293b;
  }

  .el-select-dropdown__item.is-selected {
    font-weight: 500;
    color: #2563eb;
  }

  /* 已被其它格子选中的项：置灰且不可点（与 Element Plus 禁用态一致） */
  .el-select-dropdown__item.is-disabled,
  .el-select-dropdown__item[aria-disabled='true'] {
    color: #a8abb2 !important;
    cursor: not-allowed;
    background-color: #f5f7fa !important;
  }

  .el-select-dropdown__item.is-disabled:hover,
  .el-select-dropdown__item[aria-disabled='true']:hover {
    background-color: #f0f2f5 !important;
  }
}

.screenconsole-quick-edit {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-rendering: optimizeLegibility;

  .edit-item {
    margin-bottom: 24px;
    background: #f8fafc;
    padding: 16px;
    border-radius: 20px;
    border: 1px solid #eef2f8;
    display: flex;
    flex-wrap: wrap;
    align-items: stretch;
    gap: 16px;
  }

  .edit-item:last-child {
    margin-bottom: 0;
  }

  .edit-item-index {
    width: 36px;
    flex-shrink: 0;
    font-weight: 700;
    font-size: 1.05rem;
    color: #1e293b;
    line-height: 1.2;
    align-self: center;
    text-align: right;
    padding-right: 4px;
  }

  .edit-item-select {
    flex: 2;
    min-width: 160px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
  }

  .edit-item-select label {
    font-size: 13px;
    font-weight: 600;
    color: #334155;
    display: block;
    margin-bottom: 6px;
    letter-spacing: 0.02em;
    line-height: 1.4;
  }

  .edit-item-radio {
    flex: 1;
    min-width: 120px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 6px;
  }

  .edit-item-radio > label {
    font-size: 13px;
    font-weight: 600;
    color: #334155;
    display: block;
    margin-bottom: 0;
    letter-spacing: 0.02em;
    line-height: 1.4;
  }

  /* Select 展示区：减轻小字号 + 粗体带来的发糊、发胀 */
  .edit-item-select .el-select {
    font-size: 13px;
  }

  .edit-item-select .el-select .el-input__inner {
    font-size: 13px;
    font-weight: 400;
    line-height: 1.5;
    color: #1e293b;
    -webkit-font-smoothing: antialiased;
  }

  .edit-item-select .el-select .el-input__wrapper {
    font-size: 13px;
  }

  .edit-item-select .el-select .el-select__placeholder,
  .edit-item-select .el-select .el-select__selected-item,
  .edit-item-select .el-select .el-select__selection-text {
    font-size: 13px !important;
    font-weight: 400 !important;
    line-height: 1.5 !important;
    color: #1e293b !important;
    -webkit-font-smoothing: antialiased;
  }

  .radio-group {
    display: flex;
    align-items: center;
    background: white;
    padding: 8px 14px;
    border-radius: 40px;
    border: 1px solid #e2e8f0;
    min-height: 30px;
    box-sizing: border-box;
    -webkit-font-smoothing: antialiased;
  }

  .radio-group .el-radio {
    margin-right: 0;
    height: auto;
    display: inline-flex;
    align-items: center;
  }

  .radio-group .el-radio__label {
    font-size: 13px;
    font-weight: 400;
    line-height: 1.5;
    color: #334155;
    padding-left: 8px;
    -webkit-font-smoothing: antialiased;
  }

  .radio-group .el-radio.is-checked .el-radio__label {
    color: #2563eb;
    font-weight: 500;
  }
}

.screenconsole-quick-save-btn {
 
  color: #fff !important;
  box-shadow: 0 2px 6px rgba(255, 124, 66, 0.2);
}



@media (max-width: 780px) {
  .screenconsole-quick-edit .edit-item {
    flex-direction: column;
    align-items: stretch;
  }

  .screenconsole-quick-edit .edit-item-index {
    width: auto;
    text-align: left;
    align-self: flex-start;
    padding-right: 0;
  }

  .screenconsole-quick-edit .edit-item-radio {
    justify-content: flex-start;
  }
}
</style>
