﻿<template>
  <div class="competitive-page student-training-shell">
    <main class="training-core">
      <section class="task-header">
        <div class="task-badge">市场洞察与需求分析</div>
        <h1 class="task-title">{{ taskTitle }}</h1>
      </section>

      <TrainingTaskBrief
        :background="taskBackground"
        :goals="taskGoals"
        :requirements="taskRequirement"
        :show-material="false"
      />

      <section class="task-card">
        <div class="workbench-head">
          <div>
            <p class="section-eyebrow">Training Task</p>
            <h3>任务实训</h3>
            <p v-if="taskRequirement" class="workbench-description">{{ taskRequirement }}</p>
          </div>
          <div class="workbench-actions">
            <TrainingMaterialButton :material-name="taskConfig?.materialName" :material-url="taskConfig?.materialUrl" />
            <button type="button" class="outline-action" @click="exportOutcome">
              <el-icon><Download /></el-icon>
              导出实训成果
            </button>
          </div>
        </div>

        <nav v-if="trainingSteps.length" class="step-indicator" aria-label="竞争环境分析步骤">
          <span
            v-for="(step, index) in trainingSteps"
            :key="`${index}-${step}`"
            class="step-tab"
            :class="{ active: currentStep === index + 1 }"
          >
            {{ step }}
          </span>
        </nav>

        <section class="step-card competitive-step-card">
          <div v-if="activeStepName" class="step-title-row">
            <div>
              <p class="section-eyebrow">Step {{ String(currentStep).padStart(2, "0") }}</p>
              <h3>{{ activeStepName }}</h3>
            </div>
          </div>

          <div class="background-block">
            <h4>小家电品类背景信息</h4>
            <ol>
              <li v-for="item in backgroundItems" :key="item">{{ item }}</li>
            </ol>
          </div>

          <p class="task-desc">请对上述信息进行SWOT分析归类。</p>

          <div class="swot-grid">
            <article v-for="item in swotItems" :key="item.key" class="swot-card">
              <div class="swot-card__title">{{ item.label }}</div>
              <textarea v-model="form.swot[item.key]" class="swot-input" :placeholder="item.placeholder" />
            </article>
          </div>

          <label class="field-block">
            <span>请对小家电品类进行SWOT分析，假如你想要进入小家电市场，该如何切入？</span>
            <textarea v-model="form.entryStrategy" class="long-textarea" placeholder="填写市场切入策略、定位选择、差异化打法和风险规避措施" />
          </label>

          <div class="competitor-block">
            <p class="competitor-title">
              下是2025年市场热度TOP3智能小家电的竞品对比分析（基于最新销售数据及消费者调研），三种品牌扫地机器人多维度对比分析：
            </p>
            <div class="competitor-table">
              <div class="competitor-row competitor-head">
                <div>维度</div>
                <div>科沃斯X2 OMNI</div>
                <div>石头G20</div>
                <div>追觅X30 PRO</div>
              </div>
              <div v-for="row in competitorRows" :key="row.dimension" class="competitor-row">
                <div class="dimension-cell">{{ row.dimension }}</div>
                <div>{{ row.ecovacs }}</div>
                <div>{{ row.roborock }}</div>
                <div>{{ row.dreame }}</div>
              </div>
            </div>
          </div>

          <label class="field-block">
            <span>请根据上述对比情况，分析扫地机器人竞争环境，根据自身实际情况判断是否进入该市场。</span>
            <textarea v-model="form.competitionConclusion" class="long-textarea" placeholder="填写竞品格局判断、进入可行性、切入机会和不进入理由" />
          </label>

          <div class="training-actions">
            <el-button class="training-action training-action--save" :loading="saving" @click="saveCurrentProgress">保存当前进度</el-button>
            <el-button class="training-action training-action--submit" :loading="saving" @click="submitTask">提交任务</el-button>
            <el-button class="training-action training-action--reset" @click="resetTraining">重新实训</el-button>
          </div>
        </section>
      </section>
    </main>

    <TrainingAiSidebar
      study-tip="当前任务建议：先把背景信息拆成优势、劣势、机会、威胁，再结合竞品对比判断是否进入市场。"
      :progress-items="progressItems"
    />
  </div>
</template>

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

const TASK_KEY = "competitive-environment-analysis";
const { proxy } = getCurrentInstance();

const taskConfig = ref(null);
const saving = ref(false);
const currentStep = ref(1);

const defaultRequirement = "SWOT分析用于从内部优势、内部劣势、外部机会、外部威胁四个角度判断竞争环境与市场进入策略。";
const defaultBackground = "以国内小家电品类和智能扫地机器人竞品为例，完成竞争环境归类、市场切入策略和进入可行性判断。";
const defaultGoals = [
  "掌握SWOT模型在竞争环境分析中的使用方法",
  "能够根据行业背景信息完成优势、劣势、机会、威胁归类",
  "能够结合竞品对比判断市场进入策略",
];

const backgroundItems = [
  "健康/智能化产品溢价能力提升，如低糖电饭煲、母婴消毒柜等高端品类溢价率达35%。",
  "年轻群体对高颜值、个性化设计支付意愿强烈（90后溢价接受度22%）。",
  "珠三角产业集群实现“14天快速打样”，新品上市周期缩短60%。",
  "跨境电商矩阵成熟（如德尔玛亚马逊渠道增长300%）。",
  "国家以旧换新政策推动2024年换新销量超6200万台，节能属性成必备要素。",
  "中小企业研发投入占比仅5%，同质化严重导致退货率高。",
  "45%产品因清洗麻烦/功能单一被闲置（如烤箱、空气炸锅闲置率高）。",
  "下沉市场产品破损率达一线城市2倍，方言语音等区域适配功能缺失。",
  "中国户均小家电9.5件，仅为欧美1/3，预计2025年市场规模6500亿元。",
  "智能家居年复合增长率15.7%（超行业3倍）。",
  "东南亚工厂规避关税（如美的泰国生产线）。",
  "关税壁垒升级，厨房小家电出口占国内营收30%（2024年出口额199亿美元）。",
  "IC芯片依赖台积电代工，蓝牙模组成本波动影响智能品类毛利率。",
  "《家电安全使用年限》强制标准淘汰30%在售产品。",
];

const swotItems = [
  { key: "strengths", label: "优势（Strengths）", placeholder: "归类溢价能力、设计、产业集群、渠道等优势" },
  { key: "weaknesses", label: "劣势（Weaknesses）", placeholder: "归类研发投入、同质化、闲置率、区域适配等劣势" },
  { key: "opportunities", label: "机会（Opportunities）", placeholder: "归类市场空间、政策、智能家居增长、海外产能等机会" },
  { key: "threats", label: "威胁（Threats）", placeholder: "归类关税、核心部件依赖、标准淘汰、成本波动等威胁" },
];

const competitorRows = [
  {
    dimension: "核心卖点",
    ecovacs: "双机械臂边刷+方形机身贴边",
    roborock: "动态热风烘干+AI宠物粪便识别",
    dreame: "7000Pa吸力+60℃热水洗拖布",
  },
  {
    dimension: "智能功能",
    ecovacs: "3D结构光建模（精度±1cm）",
    roborock: "自动升降滚刷（地毯识别率99%）",
    dreame: "自动集尘+UV杀菌（除菌率99.9%）",
  },
  {
    dimension: "用户体验",
    ecovacs: "复杂户型覆盖率↑37%",
    roborock: "噪音低至54dB（睡眠模式）",
    dreame: "地毯增压响应0.3秒",
  },
  {
    dimension: "定价策略",
    ecovacs: "¥6499（商用级溢价）",
    roborock: "¥4599（宠物家庭专供）",
    dreame: "¥5599（清洁性能标杆）",
  },
  {
    dimension: "商业模式",
    ecovacs: "线下6000家体验店",
    roborock: "与宠物医院联合会员",
    dreame: "订阅耗材服务（年费¥299）",
  },
];

function createForm() {
  return {
    swot: {
      strengths: "",
      weaknesses: "",
      opportunities: "",
      threats: "",
    },
    entryStrategy: "",
    competitionConclusion: "",
  };
}

const form = ref(createForm());

const taskTitle = computed(() => taskConfig.value?.taskName || "竞争环境分析");
const taskBackground = computed(() => taskConfig.value?.background || defaultBackground);
const taskGoals = computed(() => parseArray(taskConfig.value?.objectives, defaultGoals));
const taskRequirement = computed(() => taskConfig.value?.requirements || defaultRequirement);
const trainingSteps = computed(() => parseArray(taskConfig.value?.steps, []));
const activeStepName = computed(() => trainingSteps.value[currentStep.value - 1] || trainingSteps.value[0] || "");

const progressItems = computed(() => [
  { text: "进行中：SWOT四象限归类", status: "doing" },
  { text: form.value.entryStrategy ? "已填写：市场切入策略" : "待完成：市场切入策略", status: form.value.entryStrategy ? "done" : "" },
  { text: form.value.competitionConclusion ? "已填写：竞品判断" : "待完成：竞品判断", status: form.value.competitionConclusion ? "done" : "" },
]);

onMounted(async () => {
  await loadTaskConfig();
  await loadSavedAnswer();
});

async function loadTaskConfig() {
  try {
    const res = await getTrainingTaskByKey(TASK_KEY);
    taskConfig.value = res?.data || null;
  } catch (error) {
    taskConfig.value = null;
  }
}

async function loadSavedAnswer() {
  try {
    const res = await getStudentTrainingAnswer(TASK_KEY);
    const answer = res?.data;
    if (answer?.currentStep && Number(answer.currentStep) > 0) {
      currentStep.value = Number(answer.currentStep);
    }
    if (answer?.step1Answer) {
      applySavedAnswer(answer.step1Answer);
    }
  } catch (error) {
    // Keep the page usable even when the answer endpoint is unavailable.
  }
}

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 : fallback;
  } catch (error) {
    const list = String(value)
      .split(/[，,|]/)
      .map((item) => item.trim())
      .filter(Boolean);
    return list.length ? list : fallback;
  }
}

function applySavedAnswer(value) {
  try {
    const parsed = JSON.parse(value);
    if (!parsed || typeof parsed !== "object") return;
    form.value = {
      swot: {
        ...createForm().swot,
        ...(parsed.swot || {}),
      },
      entryStrategy: parsed.entryStrategy || "",
      competitionConclusion: parsed.competitionConclusion || "",
    };
  } catch (error) {
    // Ignore malformed historical answers.
  }
}

function buildOutcome() {
  return {
    title: taskTitle.value,
    swot: form.value.swot,
    entryStrategy: form.value.entryStrategy,
    competitors: competitorRows,
    competitionConclusion: form.value.competitionConclusion,
  };
}

function buildAnswerPayload(saveAction = "SAVE") {
  return {
    step1Answer: JSON.stringify(buildOutcome()),
    currentStep: currentStep.value,
    submitted: saveAction === "SUBMIT",
    saveAction,
  };
}

async function saveAnswer(saveAction = "SAVE") {
  if (saving.value) return;
  saving.value = true;
  try {
    await saveStudentTrainingAnswer(TASK_KEY, buildAnswerPayload(saveAction));
    proxy?.$modal?.msgSuccess(saveAction === "SUBMIT" ? "提交成功" : "已保存");
  } catch (error) {
    proxy?.$modal?.msgError?.(saveAction === "SUBMIT" ? "提交失败" : "保存失败");
  } finally {
    saving.value = false;
  }
}

function saveCurrentProgress() {
  return saveAnswer("SAVE");
}

function submitTask() {
  return saveAnswer("SUBMIT");
}

async function resetTraining() {
  form.value = createForm();
  await saveAnswer("RESET");
}

function exportOutcome() {
  const blob = new Blob([JSON.stringify(buildOutcome(), null, 2)], { type: "application/json;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = `${taskTitle.value}-实训成果.json`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
  proxy?.$modal?.msgSuccess("导出成功");
}
</script>

<style lang="scss" scoped>
.competitive-page {
  position: relative;
  z-index: 2;
  display: grid;
  grid-template-columns: minmax(720px, 1fr) 340px;
  gap: 24px;
  width: 100%;
  max-width: 100%;
  min-height: calc(100vh - 106px);
  margin: 0;
  padding: 0 0 32px;
  color: #e8f7ff;
  background: transparent;
}

.training-core {
  padding: 28px;
  border: 1px solid rgba(0, 180, 255, 0.25);
  border-radius: 36px;
  background: rgba(8, 18, 28, 0.6);
  box-shadow: 0 22px 48px rgba(0, 0, 0, 0.22), inset 0 1px 0 rgba(169, 229, 255, 0.08);
  backdrop-filter: blur(8px);
}

.task-header {
  margin-bottom: 24px;
}

.task-badge {
  display: inline-flex;
  margin-bottom: 12px;
  padding: 4px 14px;
  border: 1px solid rgba(0, 170, 255, 0.5);
  border-radius: 30px;
  color: #d6f6ff;
  background: rgba(0, 170, 255, 0.2);
  font-size: 12px;
  font-weight: 700;
}

.task-title {
  margin: 0;
  color: transparent;
  background: linear-gradient(135deg, #ffffff, #8bcbff);
  -webkit-background-clip: text;
  background-clip: text;
  font-size: 30px;
  line-height: 1.3;
  font-weight: 900;
}

.goal-bg,
.task-card,
.step-card {
  margin-bottom: 28px;
  padding: 18px 22px;
  border: 1px solid rgba(82, 174, 226, 0.42);
  border-radius: 26px;
  background: rgba(0, 25, 42, 0.64);
}

.goal-bg {
  p,
  li {
    color: #d7ecff;
    font-size: 14px;
    line-height: 1.8;
  }

  p,
  ol {
    margin: 0;
  }

  ol {
    padding-left: 18px;
  }
}

.subtitle-icon {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #b9e2ff;
  font-weight: 800;
}

.subtitle-icon--spaced {
  margin-top: 12px;
}

.workbench-head {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 18px;
  margin-bottom: 22px;
  padding-bottom: 18px;
  border-bottom: 1px solid rgba(0, 180, 255, 0.2);

  h3 {
    margin: 4px 0 8px;
    color: #ffffff;
    font-size: 26px !important;
    font-weight: 800 !important;
    line-height: 1.3 !important;
  }
}

.workbench-actions {
  display: flex;
  flex: 0 0 auto;
  flex-wrap: wrap;
  justify-content: flex-end;
  gap: 10px;
}

.section-eyebrow {
  margin: 0;
  color: #71dfff;
  font-size: 12px;
  font-weight: 800;
  line-height: 1.4;
}

.workbench-description {
  margin: 0;
  color: #d7ecff;
  font-size: 15px;
  font-weight: 400;
  line-height: 1.8;
}

.outline-action {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-height: 40px;
  padding: 0 18px;
  border: 1px solid rgba(99, 217, 255, 0.55);
  border-radius: 999px;
  color: #e9fbff;
  background: rgba(17, 126, 178, 0.36);
  font-size: 14px;
  font-weight: 800;

  &:hover:not(.is-disabled) {
    transform: translateY(-1px);
    border-color: rgba(116, 235, 255, 0.85);
    background: rgba(18, 146, 204, 0.5);
  }
}

.step-indicator {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 6px;
  margin-bottom: 32px;
  padding: 6px;
  border: 1px solid rgba(0, 180, 255, 0.3);
  border-radius: 60px;
  background: rgba(0, 0, 0, 0.3);
}

.step-tab {
  display: inline-flex;
  flex: 1 1 0;
  align-items: center;
  justify-content: center;
  min-height: 46px;
  padding: 0 14px;
  border: 1px solid transparent;
  border-radius: 40px;
  color: #9ab3d0;
  background: transparent;
  font-size: 14px;
  font-weight: 800;
  text-align: center;
  transition: color 0.2s, background 0.2s, border-color 0.2s, box-shadow 0.2s;

  &.active {
    border-color: rgba(0, 170, 255, 0.55);
    color: #ffffff;
    background: linear-gradient(95deg, #0a6b9e, #0a5c86);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  }
}

.step-card {
  margin-bottom: 0;
}

.step-title-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 18px;
  margin-bottom: 14px;

  h3 {
    margin: 4px 0 0;
    color: #ffffff;
    font-size: 22px;
    font-weight: 900;
  }
}

.background-block {
  padding: 16px;
  border: 1px solid rgba(0, 180, 255, 0.22);
  border-radius: 22px;
  background: rgba(1, 14, 26, 0.72);

  h4 {
    margin: 0 0 12px;
    color: #dff5ff;
    font-size: 15px;
    font-weight: 800;
  }

  ol {
    margin: 0;
    padding-left: 20px;
  }

  li {
    margin-bottom: 8px;
    color: #d7ecff;
    font-size: 14px;
    line-height: 1.72;
  }
}

.task-desc {
  margin: 22px 0 18px;
  color: #d7ecff;
  font-size: 15px;
  line-height: 1.8;
}

.swot-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 16px;
  margin: 20px 0;
}

.swot-card {
  min-height: 196px;
  padding: 16px;
  border: 1px solid rgba(0, 180, 255, 0.22);
  border-radius: 20px;
  background: rgba(1, 14, 26, 0.72);
}

.swot-card__title {
  min-height: 22px;
  margin-bottom: 12px;
  color: #ffffff;
  font-size: 15px;
  font-weight: 800;
}

.swot-input,
.long-textarea {
  width: 100%;
  border: 1px solid rgba(45, 95, 126, 0.95);
  outline: none;
  resize: vertical;
  color: #eef5ff;
  background: #0f1a24;
  font-size: 14px;
  line-height: 1.65;
  transition: border-color 0.16s ease, box-shadow 0.16s ease, background 0.16s ease;

  &::placeholder {
    color: #8299aa;
    opacity: 0.9;
  }

  &:focus {
    border-color: rgba(92, 224, 255, 0.7);
    background: #0f1a24;
    box-shadow: 0 0 0 3px rgba(0, 174, 255, 0.13);
  }
}

.swot-input {
  min-height: 128px;
  padding: 12px 14px;
  border-radius: 16px;
}

.field-block {
  display: block;
  margin-top: 22px;

  span {
    display: block;
    margin-bottom: 10px;
    color: #d7ecff;
    font-size: 15px;
    line-height: 1.8;
  }
}

.long-textarea {
  min-height: 170px;
  padding: 14px 16px;
  border-radius: 18px;
}

.competitor-block {
  margin-top: 28px;
}

.competitor-title {
  margin: 0 0 12px;
  color: #d7ecff;
  font-size: 15px;
  line-height: 1.8;
}

.competitor-table {
  overflow: hidden;
  border: 1px solid rgba(82, 174, 226, 0.48);
  border-radius: 18px;
  background: rgba(0, 13, 24, 0.68);
}

.competitor-row {
  display: grid;
  grid-template-columns: 150px repeat(3, minmax(0, 1fr));
  border-top: 1px solid rgba(87, 159, 200, 0.35);

  > div {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 58px;
    padding: 12px;
    border-right: 1px solid rgba(87, 159, 200, 0.28);
    color: #d7ecff;
    line-height: 1.65;
    text-align: center;
  }

  > :last-child {
    border-right: 0;
  }
}

.competitor-head {
  border-top: 0;
  background: linear-gradient(180deg, #0b7fb3, #075c88);

  div {
    color: #effdff;
    font-weight: 900;
  }
}

.dimension-cell {
  color: #eafaff !important;
  font-weight: 800;
}

.training-actions {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 52px;
  margin-top: 36px;
}

.training-actions :deep(.training-action) {
  min-width: 172px;
  height: 64px;
  padding: 0 28px;
  border: 1px solid #2c83aa;
  border-radius: 6px;
  color: #dff7ff;
  background: rgba(13, 64, 88, 0.62);
  box-shadow: none;
  font-size: 24px;
  font-weight: 900;
  line-height: 1;
  letter-spacing: 0;
  text-shadow: none;
}

.training-actions :deep(.training-action span) {
  display: inline-flex;
  align-items: center;
  color: inherit;
  font-size: inherit;
  line-height: 1;
}

.training-actions :deep(.training-action--submit),
.training-actions :deep(.training-action--reset),
.training-actions :deep(.training-action--export) {
  border-color: #2c83aa;
  color: #dff7ff;
  background: rgba(13, 64, 88, 0.62);
}

.training-actions :deep(.training-action:hover:not(.is-disabled)) {
  border-color: #46b5e7;
  color: #ffffff;
  background: rgba(18, 85, 116, 0.78);
}

@media (max-width: 1100px) {
  .competitive-page {
    grid-template-columns: 1fr;
  }

  .swot-grid {
    grid-template-columns: 1fr;
    margin: 8px 0 36px;
  }
}

@media (max-width: 900px) {
  .training-core {
    padding: 18px;
    border-radius: 24px;
  }

  .workbench-head,
  .workbench-actions {
    flex-direction: column;
    align-items: stretch;
  }

  .workbench-actions :deep(.material-download),
  .workbench-actions .outline-action {
    width: 100%;
  }
}

@media (max-width: 760px) {

  .competitor-row {
    grid-template-columns: 110px repeat(3, minmax(160px, 1fr));
    min-width: 760px;
  }

  .competitor-table {
    overflow-x: auto;
  }
}
</style>
