<template>
  <div class="industry-pest-page student-training-shell">
    <main class="industry-core">
      <section class="task-header">
        <div class="task-badge"><el-icon><DataAnalysis /></el-icon>核心实训 · 市场洞察与需求分析</div>
        <h1 class="task-title">{{ taskTitle }}</h1>
      </section>
      <TrainingTaskBrief :background="taskBackground" :goals="taskGoals" :requirements="taskRequirement" :show-material="false" />

      <section class="industry-workbench">
        <div class="workbench-head">
          <TrainingMaterialButton :material-name="taskConfig?.materialName" :material-url="taskConfig?.materialUrl" />
          <button type="button" class="outline-action" @click="exportOutcome"><el-icon><Download /></el-icon>导出实训成果</button>
        </div>
        <nav class="step-indicator" aria-label="行业需求分析步骤">
          <template v-for="(step, index) in trainingSteps" :key="`${step}-${index}`">
            <button type="button" :class="['step-tab', { active: currentStep === index + 1, complete: currentStep > index + 1 }]" @click="currentStep = index + 1">
              <span class="step-marker">{{ String(index + 1).padStart(2, '0') }}</span>
              <span class="step-copy"><strong class="step-name" :title="step">{{ step }}</strong><span class="step-action">{{ currentStep === index + 1 ? '当前步骤' : '点击切换' }} →</span></span>
            </button>
            <span v-if="index < trainingSteps.length - 1" class="step-connector" />
          </template>
        </nav>

        <section class="industry-step-card">
          <template v-if="currentStep === 1">
            <div class="step-title-row"><div><p class="section-eyebrow">Step 01</p><h3>{{ trainingSteps[0] }}</h3></div><span class="step-chip">PEST分类练习</span></div>
            <p class="step-desc">请根据案例文档中的案例信息进行PEST分析，进行上述各项内容归类，把文档中相应内容填写到以下四类中：</p>
            <div class="pest-table-wrap">
              <table class="pest-table">
                <thead><tr><th>序号</th><th>PEST类型</th><th>信息资讯</th></tr></thead>
                <tbody><tr v-for="(row, index) in pestRows" :key="row.key"><td>{{ index + 1 }}</td><td class="type-cell">{{ row.label }}</td><td><textarea v-model.trim="form[row.key]" :placeholder="row.placeholder" /></td></tr></tbody>
              </table>
            </div>
            <div class="task-actions"><button type="button" class="btn-nav btn-submit" :disabled="saving" @click="saveAndGoToStepTwo">保存并进入第 2 步</button><button type="button" class="btn-nav" :disabled="saving" @click="resetTraining"><el-icon><RefreshLeft /></el-icon>清空填写</button></div>
          </template>
          <div v-else class="step-placeholder"><p>第 {{ currentStep }} 步内容待配置</p><span>第 1 步PEST分析已保存，可从上方步骤栏返回查看。</span></div>
        </section>
      </section>
    </main>
    <TrainingAiSidebar study-tip="先从案例中提取宏观环境信息，再按政治、经济、社会、技术四个维度归类。" reference-title="PEST 分类提示" reference-text="· 政治：政策、法规、认证、税收、数据合规<br />· 经济：市场规模、成本、商业模式、供应链<br />· 社会：人群需求、消费趋势、生活方式与场景<br />· 技术：产品技术、平台能力、设备互联与创新" :progress-items="progressItems" />
  </div>
</template>

<script setup>
import { DataAnalysis, Download, RefreshLeft } from "@element-plus/icons-vue";
import { checkIndustryDemandAnalysisStepOne, getStudentTrainingAnswer, saveStudentTrainingAnswer } from "@/api/studentTrainingAnswer";
import { getTrainingTaskByKey } from "@/api/trainingTask";
import useUserStore from "@/store/modules/user";
import TrainingAiSidebar from "@/views/components/TrainingAiSidebar.vue";
import TrainingMaterialButton from "@/views/components/TrainingMaterialButton.vue";
import TrainingTaskBrief from "@/views/components/TrainingTaskBrief.vue";

const TASK_KEY = "industry-demand-analysis";
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const DEFAULT_STEPS = ["PEST宏观环境分析", "行业机会识别", "需求判断", "分析结论"];
const pestRows = [
  { key: "political", label: "政治环境", placeholder: "填写政策、法规、认证、税收或数据合规等案例信息" },
  { key: "economic", label: "经济环境", placeholder: "填写市场规模、成本、商业模式或供应链等案例信息" },
  { key: "social", label: "社会环境", placeholder: "填写用户需求、消费趋势、生活方式或场景变化等案例信息" },
  { key: "technology", label: "技术环境", placeholder: "填写产品技术、平台能力、设备互联或创新等案例信息" },
];
const defaultTask = { title: "行业需求分析", background: "通过PEST模型识别影响行业需求的宏观环境因素，为后续产品机会判断提供依据。", goals: ["掌握PEST四维度的分类方法", "提炼案例中的宏观环境信息", "形成行业需求分析的基础材料"], requirement: "请阅读案例资料，将相关信息归类到政治、经济、社会和技术环境中。" };
const taskConfig = ref(null);
const currentStep = ref(1);
const saving = ref(false);
const draftReady = ref(false);
const form = ref(createForm());
const taskTitle = computed(() => taskConfig.value?.taskName || defaultTask.title);
const taskBackground = computed(() => taskConfig.value?.background || defaultTask.background);
const taskGoals = computed(() => parseArray(taskConfig.value?.objectives, defaultTask.goals));
const taskRequirement = computed(() => taskConfig.value?.requirements || defaultTask.requirement);
const trainingSteps = computed(() => parseArray(taskConfig.value?.steps, DEFAULT_STEPS));
const progressItems = computed(() => pestRows.map((row) => ({ text: `${form.value[row.key] ? '已填写' : '待填写'}：${row.label}`, status: form.value[row.key] ? 'done' : '' })));

onMounted(async () => { await loadTaskConfig(); loadDraft(); await loadSavedAnswer(); draftReady.value = true; });
watch(() => JSON.stringify(buildDraft()), persistDraft);

function createForm() { return { political: "", economic: "", social: "", technology: "" }; }
function parseArray(value, fallback) { if (Array.isArray(value)) return value.length ? value : fallback; if (!value) return fallback; try { const parsed = JSON.parse(value); return Array.isArray(parsed) && parsed.length ? parsed.map((item) => String(item?.name ?? item).trim()).filter(Boolean) : fallback; } catch (error) { const list = String(value).split(/[；;|]/).map((item) => item.trim()).filter(Boolean); return list.length ? list : fallback; } }
async function loadTaskConfig() { try { taskConfig.value = (await getTrainingTaskByKey(TASK_KEY))?.data || null; } catch (error) { taskConfig.value = null; } }
async function loadSavedAnswer() { try { const answer = (await getStudentTrainingAnswer(TASK_KEY))?.data; if (answer?.step1Answer) { restoreOutcome(answer.step1Answer); clearDraft(); } if (Number(answer?.currentStep) > 0) currentStep.value = Number(answer.currentStep); } catch (error) { /* Keep the local draft when the answer endpoint is unavailable. */ } }
function restoreOutcome(value) { try { const parsed = typeof value === "string" ? JSON.parse(value) : value; form.value = { ...createForm(), ...(parsed?.pest || parsed || {}) }; } catch (error) { form.value = createForm(); } }
function buildOutcome() { return { title: taskTitle.value, pest: { ...form.value } }; }
function buildDraft() { return { step1: buildOutcome(), currentStep: currentStep.value }; }
function getLocalDraftKey() { const info = userStore.userInfo || {}; return `${TASK_KEY}:draft:${info.userId || info.user_id || info.username || info.userName || 'anonymous'}`; }
function persistDraft() { if (!draftReady.value) return; try { localStorage.setItem(getLocalDraftKey(), JSON.stringify(buildDraft())); } catch (error) { /* Browser draft is optional. */ } }
function loadDraft() { try { const raw = localStorage.getItem(getLocalDraftKey()); if (raw) { const draft = JSON.parse(raw); restoreOutcome(draft?.step1 || draft); if (Number(draft?.currentStep) > 0) currentStep.value = Number(draft.currentStep); } } catch (error) { clearDraft(); } }
function clearDraft() { try { localStorage.removeItem(getLocalDraftKey()); } catch (error) { /* Ignore storage failures. */ } }
async function saveAndGoToStepTwo() { if (saving.value) return; saving.value = true; try { await checkIndustryDemandAnalysisStepOne(form.value); await saveStudentTrainingAnswer(TASK_KEY, { step1Answer: JSON.stringify(buildOutcome()), currentStep: 2, submitted: false, saveAction: "SAVE" }); clearDraft(); currentStep.value = 2; proxy?.$modal?.msgSuccess("已保存，已进入第 2 步"); } catch (error) { proxy?.$modal?.msgError?.(error?.message || "请完整填写PEST四类信息"); } finally { saving.value = false; } }
async function resetTraining() { form.value = createForm(); currentStep.value = 1; clearDraft(); try { saving.value = true; await saveStudentTrainingAnswer(TASK_KEY, { step1Answer: JSON.stringify(buildOutcome()), currentStep: 1, submitted: false, saveAction: "RESET" }); } catch (error) { /* Local clearing still succeeds. */ } finally { saving.value = false; } proxy?.$modal?.msgSuccess("已清空填写内容"); }
function exportOutcome() { const blob = new Blob([JSON.stringify(buildDraft(), null, 2)], { type: "application/json;charset=utf-8" }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = "行业需求分析-实训成果.json"; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); proxy?.$modal?.msgSuccess("导出成功"); }
</script>

<style lang="scss" scoped>
.industry-pest-page { display: grid; grid-template-columns: minmax(720px, 1fr) 340px; gap: 24px; min-height: calc(100vh - 106px); padding: 24px; color: #e8f7ff; background: #06111d; }.industry-core { min-width: 0; border: 1px solid rgba(0,180,255,.25); background: rgba(8,18,28,.6); box-shadow: 0 22px 48px rgba(0,0,0,.22); }.task-header { padding: 22px 28px 4px; }.task-badge,.section-eyebrow { color: #65dcff; font-weight: 700; }.task-title { margin: 10px 0 0; color: #fff; font-size: 28px; }.industry-workbench { margin: 24px; padding: 22px; border: 1px solid rgba(33,194,255,.35); border-radius: 20px; background: rgba(1,24,39,.72); }.workbench-head { display: flex; justify-content: flex-end; gap: 12px; }.outline-action,.btn-nav { display: inline-flex; align-items: center; justify-content: center; gap: 6px; border: 1px solid #2cc9ff; border-radius: 999px; padding: 10px 18px; color: #dff8ff; background: rgba(8,87,121,.55); cursor: pointer; }.step-indicator { display: flex; align-items: center; gap: 12px; margin: 28px 0; padding: 12px; border: 1px solid rgba(30,190,255,.28); border-radius: 22px; }.step-tab { display: flex; align-items: center; flex: 1; gap: 10px; min-width: 0; padding: 10px; border: 0; border-radius: 16px; color: #96c6d8; background: transparent; text-align: left; cursor: pointer; }.step-tab.active { color: #fff; background: linear-gradient(110deg,#148fc6,#0879aa); }.step-marker { display: grid; place-items: center; flex: 0 0 42px; width: 42px; height: 42px; border: 1px solid #4ed7ff; border-radius: 50%; font-weight: 800; }.step-copy { display: grid; min-width: 0; gap: 4px; }.step-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.step-action { color: #5ec9ed; font-size: 12px; }.step-connector { flex: 0 0 25px; height: 2px; background: rgba(83,204,255,.4); }.industry-step-card { padding: 24px; border: 1px solid rgba(31,185,249,.32); border-radius: 18px; background: rgba(1,21,34,.65); }.step-title-row { display: flex; justify-content: space-between; align-items: flex-start; }.step-title-row h3 { margin: 5px 0 0; color: #fff; font-size: 24px; }.step-chip { border: 1px solid #38caff; border-radius: 999px; padding: 7px 12px; color: #9aeaff; }.step-desc { margin: 24px 0; color: #c5e4ef; font-size: 16px; line-height: 1.8; }.pest-table-wrap { overflow-x: auto; }.pest-table { width: 100%; min-width: 720px; border-collapse: collapse; }.pest-table th,.pest-table td { border: 1px solid rgba(139,213,241,.45); }.pest-table th { padding: 14px; color: #fff; background: #079ed9; font-size: 16px; }.pest-table th:first-child,.pest-table td:first-child { width: 8%; text-align: center; }.pest-table th:nth-child(2),.pest-table .type-cell { width: 18%; text-align: center; font-weight: 700; }.pest-table textarea { box-sizing: border-box; display: block; width: 100%; min-height: 136px; resize: vertical; border: 0; padding: 16px; color: #e9faff; background: transparent; font: inherit; line-height: 1.7; }.pest-table textarea:focus { outline: 2px solid rgba(57,207,255,.4); outline-offset: -2px; }.task-actions { display: flex; justify-content: center; gap: 12px; margin-top: 26px; }.btn-submit { border-color: #36d9ff; background: linear-gradient(110deg,#0eaae4,#0572ac); font-weight: 700; }.btn-nav:disabled { cursor: not-allowed; opacity: .6; }.step-placeholder { padding: 90px 20px; text-align: center; color: #a8cfdd; }.step-placeholder p { color: #fff; font-size: 20px; } @media (max-width:1280px) { .industry-pest-page { grid-template-columns: 1fr; }.step-indicator { overflow-x: auto; }.step-tab { min-width: 190px; } } @media (max-width:720px) { .industry-pest-page { padding: 12px; }.industry-workbench { margin: 12px; padding: 14px; }.task-header { padding: 18px; }.workbench-head { justify-content: flex-start; flex-wrap: wrap; }.step-chip { display: none; } }
</style>
