<template>
  <div class="global-variable">
    <h2 class="TitleH2">主轴</h2>
    <zhuzhou
      v-if="bearingBrandOptions.length > 0 && lubricantBrandOptions.length > 0"
      :rhyPP="lubricantBrandOptions"
      :rhyZC="bearingBrandOptions"
      :unitBearingsVo="unitBearingsVo"
      @update="handleUpdate('unitBearingsDto', $event)"
    ></zhuzhou>
    <div v-if="clxShow">
      <h2 class="TitleH2">齿轮箱</h2>
      <Chilunxiang
        v-if="
          bearingBrandOptions.length > 0 && lubricantBrandOptions.length > 0
        "
        :clxPP="lubricantBrandOptions"
        :clxZC="bearingBrandOptions"
        :unitGearDto="unitGearDto"
        @update="handleUpdate('unitGearDto', $event)"
      ></Chilunxiang>
    </div>

    <h2 class="TitleH2">发电机</h2>
    <Fadianji
      v-if="bearingBrandOptions.length > 0 && lubricantBrandOptions.length > 0"
      :fdjPP="lubricantBrandOptions"
      :fdjZC="bearingBrandOptions"
      :unitDynamoDto="unitDynamoDto"
      :fdjLQ="coolingoptions"
      @update="handleUpdate('unitDynamoDto', $event)"
    ></Fadianji>

    <el-button @click="ALLsubmit">提交</el-button>
  </div>
</template>

<script>
import {
  getBrandModelNameOrModelNumber,
  getUnitDictRoutineList,
  modificationUnit,
  getUnitVo,
} from "@/api/maintain";
import Chilunxiang from "./componentBJ/chilunxiang.vue";
import Fadianji from "./componentBJ/fadianji.vue";
import zhuzhou from "./componentBJ/zhuzhou.vue";
import router from "@/router";

export default {
  components: { zhuzhou, Chilunxiang, Fadianji },
  data() {
    return {
      clxShow: true,
      // 润滑油选项
      lubricantBrandOptions: [],
      // 轴承选项
      bearingBrandOptions: [],
      // 主轴的
      unitBearingsVo: {},
      // 发电机
      unitDynamoDto: {},
      // 齿轮箱
      unitGearDto: {},
      // 冷却选项
      coolingOptions: [],
      // 存储不同子组件的状态
      formData: {
        millTypeCode: "",
        // 主轴
        unitBearingsDto: {
          code: "",
          id: "",
        },
        // 齿轮箱
        unitGearDto: {
          code: "",
          id: "",
          lubricantBrand: "",
          lubricantModel: "",
          unitGearboxBearingsDtoList: [{ id: "" }],
          // 齿轮箱结构集合
          unitGearboxStructureDtoList: [{ id: "" }],
        },
        //发电机
        unitDynamoDto: {
          id: "",
        },
      },
      submittedData: null,
      allParams: {},
      coolingoptions: null,
    };
  },
  created() {
    this.curvedMotionType = this.$route.query.curvedMotionType;
    this.formData.millTypeCode = this.$route.query.millTypeCode;
    if (this.curvedMotionType == "2") {
      this.clxShow = false;
    }
    this.GETbrand(); // 加载品牌和型号数据
    this.GETecho();
  },
  methods: {
    // 获取品牌和型号数据
    GETbrand() {
      const params = { unitType: 1 };
      const params2 = { unitType: 2 };
      const params3 = { contentsType: "UDTC00031" };
      getBrandModelNameOrModelNumber(params)
        .then((res) => {
          // 确保数据有效
          if (res && res.data) {
            this.bearingBrandOptions = res.data;
          } else {
            console.error("获取轴承品牌失败:", res);
          }
        })
        .catch((error) => {
          console.error("获取轴承品牌请求失败:", error);
        });

      getBrandModelNameOrModelNumber(params2)
        .then((res) => {
          // 确保数据有效
          if (res && res.data) {
            this.lubricantBrandOptions = res.data;
          } else {
            console.error("获取润滑油品牌失败:", res);
          }
        })
        .catch((error) => {
          console.error("获取润滑油品牌请求失败:", error);
        });

      getUnitDictRoutineList(params3)
        .then((res) => {
          // 确保数据有效
          if (res && res.data) {
            this.coolingoptions = res.data;
          } else {
            console.error("获取冷却选项失败:", res);
          }
        })
        .catch((error) => {
          console.error("获取冷却选项请求失败:", error);
        });
    },

    GETecho() {
      getUnitVo({ millTypeCode: this.formData.millTypeCode }).then((res) => {
        console.log(res.data.unitDynamoVo, "============");

        if (res.data.unitBearingsVo != null) {
          // 主轴
          this.formData.unitBearingsDto.code = res.data.unitBearingsVo.code;
          this.formData.unitBearingsDto.id = res.data.unitBearingsVo.id;
        }

        if (res.data.unitGearVo) {
          const unitGearVo = res.data.unitGearVo;

          // 齿轮箱基本信息
          this.formData.unitGearDto.code = unitGearVo.code || "";
          this.formData.unitGearDto.id = unitGearVo.id || "";
          // 齿轮箱轴承集合（确保列表存在且是数组）
          if (Array.isArray(unitGearVo.unitGearboxBearingsList)) {
            this.formData.unitGearDto.unitGearboxBearingsDtoList =
              unitGearVo.unitGearboxBearingsList.map((item) => ({
                id: item.id || "",
              }));
          }

          // 齿轮箱结构集合（确保列表存在且是数组）
          if (Array.isArray(unitGearVo.unitGearboxStructureList)) {
            this.formData.unitGearDto.unitGearboxStructureDtoList =
              unitGearVo.unitGearboxStructureList.map((item) => ({
                id: item.id || "",
              }));
          }
        }

        if (res.data.unitDynamoVo != null) {
          // 齿轮箱
          this.formData.unitDynamoDto.id = res.data.unitDynamoVo.id;
        }
        this.unitBearingsVo = res.data.unitBearingsVo;
        this.unitDynamoDto = res.data.unitDynamoVo;
        this.unitGearDto = res.data.unitGearVo;
      });
    },

    /**
     * 处理子组件传来的更新事件
     * @param {Object} payload 子组件发送的数据
     * @param {String} payload.key 要更新的字段
     * @param {String} payload.value 字段的新值
     */

    handleUpdate(componentName, { key, value }) {
      if (key && key.includes(".")) {
        // 如果 key 包含路径，解析并更新对应路径
        const keys = key.split("."); // 分割路径
        let target = this.formData;

        // 遍历路径逐层深入
        for (let i = 0; i < keys.length - 1; i++) {
          const keyPart = keys[i];
          if (keyPart.includes("[")) {
            const [arrayKey, index] = keyPart.split(/[\[\]]/).filter(Boolean);
            target = target[arrayKey][index]; // 数组元素访问
          } else {
            target = target[keyPart]; // 对象访问
          }
        }

        // 最后一层赋值
        const lastKey = keys[keys.length - 1];
        this.$set(target, lastKey, value); // 使用 $set 确保响应式更新
        console.log("更新后的数据:", this.formData);
      } else if (this.formData[componentName]) {
        // 如果是直接指定 componentName 更新
        this.$set(this.formData[componentName], key, value);
        console.log("更新后的数据:", this.formData);
      } else {
        console.error("无效的组件名称或 key");
      }
    },

    ALLsubmit() {
      // 轴
      console.log(this.formData.unitGearDto);
      const unitGearboxBearingsDtoList =
        this.formData.unitGearDto.unitGearboxBearingsDtoList.map(
          ({ uniqueKey, ...rest }) => rest
        );
      console.log(unitGearboxBearingsDtoList);
      this.formData.unitGearDto.unitGearboxBearingsDtoList =
        unitGearboxBearingsDtoList;
      // 结构
      const unitGearboxStructureDtoList =
        this.formData.unitGearDto.unitGearboxStructureDtoList.map(
          ({ uniqueKey, ...rest }) => rest
        );
      console.log(unitGearboxStructureDtoList);
      // 汇总所有子组件的数据
      this.formData.unitGearDto.unitGearboxStructureDtoList =
        unitGearboxStructureDtoList;
      this.allParams = { ...this.formData };
      // 发送到后端或执行其他操作
      this.submitToBackend(this.allParams);
    },

    /**
     * 模拟发送数据到后端
     * @param {Object} params 提交的所有参数
     */
    submitToBackend(params) {
      modificationUnit(params).then((res) => {
        if (res.code == 200)
          this.$router.push({
            path: "/home/ledger/milltype",
          });
      });

      // 你可以调用后台 API，例如：axios.post('/api/submit', params);
    },
  },
};
</script>

<style lang="scss" scoped>
.TitleH2 {
  font-weight: 800;
  font-size: 28px;
  margin: 20px 0;
}
</style>
