<template>
  <div class="app-container">
    <div class="header">
      <h2>{{ orderId ? "修改订单/单" : "创建订单/意向单" }}</h2>
      <div class="price-box" v-if="shouldShowPrice">
        <span>预计总价：</span>
        <span class="price">{{ currentPrice }}万</span>
      </div>
    </div>
    <el-steps :active="stepForStepsBar" finish-status="success" align-center>
      <el-step title="选择客户信息" description="选择销售客户对象" />
      <el-step title="选择商品规格" description="根据客户需求选择商品" />
      <el-step
        title="录入商务信息"
        description="根据客户要求录入商务信息"
        :status="step3Status"
      />
      <el-step
        :title="selectedCarType === '其他' ? '完成意向单' : '完成订单'"
        :description="selectedCarType === '其他' ? '完成意向单' : '完成订单'"
      />
    </el-steps>
    <component
      :is="currentStepComponent"
      :form="form"
      :selected-car-type="selectedCarType"
      @update:form="handleFormUpdate"
      @next-step="handleNextStep"
      @prev-step="handlePrevStep"
      @view-list="goToListView"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import Step1 from "./Step1.vue";
import Step2 from "./Step2.vue";
import Step3 from "./Step3.vue";
import Step4 from "./Step4.vue";
import { useRoute, useRouter } from "vue-router";
import { mockData } from "@/mockData";
import { ElMessage } from "element-plus";
import { defaultOrderForm } from "@/data/defaultOrderForm";

const step = ref(1);
const form = ref({ ...defaultOrderForm });

const route = useRoute();
const router = useRouter();
const orderId = computed(() => route.query.id);

// Load data if editing
if (orderId.value) {
  const orderToEdit = mockData.value.find(
    (item) => item.id === parseInt(orderId.value)
  );
  if (orderToEdit) {
    form.value = { ...orderToEdit };
    // 根据车型类型设置初始步骤
    if (form.value.selectedCarType === "其他") {
      step.value = 4;
    } else {
      step.value = 1; // 对于具体车型，从步骤1开始
    }
  }
}

// 监听车型变化，清除价格
watch(
  () => form.value.selectedCarType,
  () => {
    currentPrice.value = null;
  }
);

// 当前价格
const currentPrice = ref(null);

// 是否应该显示价格
const shouldShowPrice = computed(() => {
  if (step.value !== 2) return false;

  if (form.value.selectedCarType === "其他") {
    // 其他车型需要填写完所有信息
    return (
      form.value.modelInput && form.value.modelDesc && form.value.planCount
    );
  } else {
    // 具体车型只需要选择商品参数
    return form.value.selectedPartInfo !== null;
  }
});

// 生成价格
const generatePrice = () => {
  if (!shouldShowPrice.value) return;

  if (form.value.selectedCarType === "其他") {
    // 其他车型基础价格300-500万
    const basePrice = Math.floor(Math.random() * (500 - 300 + 1)) + 300;
    // 根据数量调整价格
    const count = parseInt(form.value.planCount) || 1;
    currentPrice.value = Math.floor(basePrice * count);
  } else {
    // 具体车型根据选择的部件生成不同价格
    if (form.value.selectedPartInfo) {
      const partId = parseInt(form.value.selectedPartInfo.id) || 1;
      let price;

      // 根据部件ID计算价格
      switch (partId) {
        case 1: // 动力轮对轴箱组装(带联轴节) - 父节点
          // 包含动力轮对(300) + 左轴箱组装(250) + 左轴端装置(250) + 右轴箱组装(250) + 右轴端装置(250)
          price = 300 + 250 + 250 + 250 + 250;
          break;
        case 2: // 动力轮对(带轴承+联轴节) - 父节点
          // 包含动力轮对(300) + 左轴箱组装(250) + 左轴端装置(250) + 右轴箱组装(250) + 右轴端装置(250)
          price = 300 + 250 + 250 + 250 + 250;
          break;
        case 3: // 动力轮对
          price = 300;
          break;
        case 4: // 左轴箱组装
          price = 250;
          break;
        case 5: // 左轴端装置
          price = 250;
          break;
        case 6: // 右轴箱组装
          price = 250;
          break;
        case 7: // 右轴端装置
          price = 250;
          break;
        default:
          price = 300;
      }

      currentPrice.value = price;
    } else {
      currentPrice.value = null;
    }
  }
};

// 监听表单变化，更新价格
watch(
  [
    () => form.value.modelInput,
    () => form.value.modelDesc,
    () => form.value.planCount,
    () => form.value.selectedPartInfo,
    () => form.value.selectedCarType,
  ],
  () => {
    generatePrice();
  },
  { immediate: true }
);

const selectedCarType = computed(() => form.value.selectedCarType);

const currentStepComponent = computed(() => {
  if (step.value === 1) return Step1;
  if (step.value === 2) return Step2;
  if (step.value === 3) return Step3;
  if (step.value === 4) return Step4;
  return Step1;
});

// 步骤条动态高亮/置灰
const stepForStepsBar = computed(() => {
  // 车型为其他且在step2时，步骤条高亮到2，step4时高亮到4
  if (selectedCarType.value === "其他") {
    if (step.value === 2) return 2;
    if (step.value === 4) return 4;
  }
  return step.value;
});
const step3Status = computed(() => {
  // 车型为其他且在step2或step4时，步骤三置灰
  if (
    selectedCarType.value === "其他" &&
    (step.value === 2 || step.value === 4)
  ) {
    return "wait";
  }
  return undefined;
});

function handleNextStep() {
  if (step.value === 4) {
    // This is the final step, save the data
    saveOrder();
  } else if (step.value === 2 && selectedCarType.value === "其他") {
    step.value = 4;
  } else if (step.value < 4) {
    step.value++;
  }
}
function handlePrevStep() {
  if (step.value === 2) {
    step.value = 1;
  } else if (step.value === 3) {
    step.value = 2;
  } else if (step.value === 4) {
    if (selectedCarType.value === "其他") {
      step.value = 2;
    } else {
      step.value = 3;
    }
  }
}

// 处理表单更新
function handleFormUpdate(newForm) {
  form.value = { ...newForm };
}

// Add saveOrder function
function saveOrder() {
  if (orderId.value) {
    // Edit existing order
    const index = mockData.value.findIndex(
      (item) => item.id === parseInt(orderId.value)
    );
    if (index !== -1) {
      mockData.value[index] = { ...form.value, id: parseInt(orderId.value) };
      ElMessage.success("订单更新成功");
    }
  } else {
    // Add new order
    const newId =
      mockData.value.length > 0
        ? Math.max(...mockData.value.map((item) => item.id)) + 1
        : 1;
    mockData.value.push({ ...form.value, id: newId });
    ElMessage.success("订单创建成功");
  }
  // Navigate back to the list view - Remove this navigation from here
}

// Add goToListView function
function goToListView() {
  console.log("Navigating to list view from Step 4");
  router.push("/order/intention");
}
</script>

<style scoped lang="scss">
.app-container {
  max-width: 1200px;
  margin: 0 auto;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .price-box {
      margin-top: 10px;
      font-size: 20px;
    }
    .price {
      background: #a6a6fa;
      color: #fff;
      padding: 4px 16px;
      border-radius: 4px;
      font-size: 28px;
      margin-left: 8px;
    }
  }
}
</style> 