<template>
	<view class="phone-haibao-page">
		<view class="icon-title-navBar-box">
			<view @click="goUpPage" class="nav-bar-icon"></view>
			<text class="nav-bar-title">职业海报</text>
		</view>
		<view class="haibao-body-box">
			<view class="haibao-menu-box">
				<view v-for="menu in menuData" :key="menu.id" class="menu-item-box"
				      :class="{ active: selectedCategory === Number(menu.id) }"
				      @click="menuBtn(menu.id)">
				  {{ menu.name }}
				</view>
			</view>
			<view class="haibao-show-box">
				<view class="haibao-title">共{{cardData.length}}个海报</view>
				<view class="card-list-box">
					<view v-for="item in cardData" :key="item.id" class="haibao-card-box"
					      @click="cardBtn(item.id)">
						  <img :src="item.image"/>
						  <view class="card-name">{{ item.name }}</view>
					</view>
				</view>
			</view>
		</view>
	</view>
	
</template>

<script setup>
import * as httpApi from '@/api/haibao.js'	
import { ref, reactive } from "vue"
import {onLoad} from "@dcloudio/uni-app";
const menuData = ref([])
const cardData = ref([])
// 当前选中的分类
const selectedCategory = ref(null)

function goUpPage() {
	uni.redirectTo({
		url: `/pages/admin/ShouYe/shouye`
	})
}

// 加载海报列表
function getHaibaoListData(zyId) {
    if (zyId == null) return;
    httpApi.getHaibaoList({ zyId }).then(res => {
        cardData.value = Array.isArray(res.data) ? res.data : [];
    }).catch(err => {
        console.error('获取海报列表失败:', err);
        cardData.value = [];
        uni.showToast({ title: '加载失败', icon: 'none' });
    });
}
	
// 菜单按钮点击
function menuBtn(id) {
    const numericId = Number(id);
    selectedCategory.value = numericId;
    getHaibaoListData(numericId);
}

// 海报卡片点击
function cardBtn(data) {
    uni.redirectTo({
        url: `/pages/admin/haibao/haibaoInfo?cardId=${data}&menuId=${selectedCategory.value}`
    });
}

// 首次进入页面初始化
function pageInit() {
    httpApi.getHaibaoOpsZhiye().then(res => {
        menuData.value = Array.isArray(res.data) ? res.data : [];
        if (menuData.value.length > 0) {
            const firstId = Number(menuData.value[0].id);
            selectedCategory.value = firstId;
            getHaibaoListData(firstId);
        }
    }).catch(err => {
        console.error('初始化职业失败:', err);
        menuData.value = [];
        uni.showToast({ title: '职业加载失败', icon: 'none' });
    });
}

// 从详情页返回时恢复状态
function pageRecover(data) {
    httpApi.getHaibaoOpsZhiye().then(res => {
        menuData.value = Array.isArray(res.data) ? res.data : [];
        const menuId = Number(data.menuId);
        menuBtn(menuId); 
    }).catch(err => {
        console.error('页面加载:', err);
        uni.showToast({ title: '页面加载失败', icon: 'none' });
    });
}
onLoad((options) => {
	// 详情页返回
	if(options.menuId){
		pageRecover(options)
	}else{
		// 首页进入
		pageInit()
	}
	
})
</script>
