<template>
  <view class="page maintenance">
    <view class="segmented-header">
      <uni-segmented-control
        :current="currentTab"
        :values="tabTitles"
        :style-type="styleType"
        :active-color="activeColor"
        @clickItem="onClickTabItem"
      />
    </view>
    <scroll-view scroll-y="true" class="segmented-content">
      <!-- 工单信息 -->
      <view class="work-order-info" v-show="currentTab === 0">
        <work-order-form
          ref="workOrderFormRef"
          :form-data="mainWorkOrder"
          :form-disabled="false"
        />
      </view>
      <!-- 保养项列表 -->
      <view class="work-order-bom-list" v-show="currentTab === 1">
        <view class="list-content all">
          <work-order-boms
            :boms-data="mainWorkOrderBom"
            :work-order-type="mainWorkOrder.type"
            :current-bom="currentBomData"
            @onSelectBom="onSelectBom"
            @updateStatistics="updateBomStatisticsAndCost"
          ></work-order-boms>
        </view>
      </view>
      <!--物料列表 -->
      <view class="material-list" v-show="currentTab === 2">
        <!-- 物料列表操作栏 -->
        <uni-row
          class="list-header flex-row align-center justify-start"
          :gutter="10"
        >
          <!-- 选择物料  -->
          <uni-col :span="8">
            <button
              class="list-header-item flex-row align-center justify-center"
              type="default"
              :disabled="
                !currentBomData ||
                currentBomData.rule == '1' ||
                currentBomData.status == '1'
              "
              @click="onMaterialChoose(currentBomData)"
            >
              <image
                src="~@/static/workOrder/xuanzhewuliao.png"
                mode="aspectFill"
              ></image>
              <text>{{ t("workOrder.selectMaterial") }}</text>
            </button>
          </uni-col>
          <!-- 所有物料/当前保养项物料 -->
          <uni-col :span="8">
            <button
              class="list-header-item flex-row align-center justify-center"
              type="default"
              @click="changeMaterialList"
            >
              <image
                src="~@/static/workOrder/suoyoueuliao.png"
                mode="aspectFill"
              ></image>
              <text v-if="allMaterialShow">
                {{ t("workOrder.currentMaterial") }}
              </text>
              <text v-else>{{ t("workOrder.allMaterial") }}</text>
            </button>
          </uni-col>
          <!-- 新增物料 -->
          <uni-col :span="8">
            <button
              class="list-header-item flex-row align-center justify-center"
              type="default"
              :disabled="
                !currentBomData ||
                currentBomData.rule == '1' ||
                currentBomData.status == '1'
              "
              @click="addMaterial"
            >
              <image
                src="~@/static/workOrder/xinzengwuliao.png"
                mode="aspectFill"
              ></image>
              <text>{{ t("workOrder.addMaterial") }}</text>
            </button>
          </uni-col>
        </uni-row>
        <view class="list-content">
          <work-order-materials
            :materials-data="materialList"
            :material-disabled="false"
            @deleteMaterial="onDeleteMaterial"
            @materialChanged="updateBomStatisticsAndCost"
          ></work-order-materials>
        </view>
      </view>
    </scroll-view>
    <!-- 底部总览 及 操作按钮 -->
    <view class="segmented-footer">
      <view
        class="footer-total flex-row align-center justify-between"
        v-if="currentTab < 2"
      >
        <view class="total-item flex-row align-center justify-around">
          <!-- 共xx项 -->
          <view class="total-item-text">
            <text>{{ t("workOrder.total") }}</text>
            <text class="number">{{ bomNumbers.total }}</text>
            <text>{{ t("workOrder.item") }}</text>
          </view>
          <!-- 已保养xx项 -->
          <view class="total-item-text">
            <text>{{ t("maintenanceWorkOrder.maintained") }}</text>
            <text class="number">{{ bomNumbers.maintained }}</text>
            <text>{{ t("workOrder.item") }}</text>
          </view>
          <!-- 未保养xx项 -->
          <view class="total-item-text color-red">
            <text>{{ t("maintenanceWorkOrder.notMaintained") }}</text>
            <text class="number">{{ bomNumbers.notMaintained }}</text>
            <text>{{ t("workOrder.item") }}</text>
          </view>
        </view>
        <view class="total-btn">
          <button class="mini-btn" type="primary" @click="submitWorkOrder">
            {{ t("operation.submit") }}
          </button>
        </view>
      </view>
      <view class="footer-btn" v-else>
        <button class="mini-btn" type="primary" @click="saveMartialList">
          {{ t("operation.save") }}{{ t("workOrder.currentMaterialList") }}
        </button>
      </view>
    </view>
  </view>
  <!-- 选择物料弹窗 -->
  <materials-choose
    ref="materialsChooseRef"
    :deptId="mainWorkOrder?.deptId"
    :deviceId="currentBomData?.deviceId"
    :bomNodeId="currentBomData?.bomNodeId"
    :noAdd="true"
    @material-submit="onMaterialChooseSubmit"
  />
  <!-- 全局提示信息弹窗 -->
  <global-message-popup
    class="edit-message-popup"
    ref="messageGlobalRef"
    :msgType="msgType"
    :messageText="messageText"
  />
</template>

<script setup>
import { onLoad, onReady, onBackPress } from "@dcloudio/uni-app";
import {
  reactive,
  ref,
  onMounted,
  onBeforeUnmount,
  nextTick,
  getCurrentInstance,
  watch,
} from "vue";
import dayjs from "dayjs";
// --------------------------引入用户信息-------------------------------
import { getDeptId, getUserId, reloginByUserId } from "@/utils/auth";

// --------------------------引用api接口-----start------------------------
import {
  fillWorkOrder,
  getMaintenanceDetail,
  getWorkOrderBOMs,
  getBomMaterialsByWorkOrderId,
} from "@/api/maintenance";
// --------------------------引用api接口-----end--------------------------
// --------------------------引用组件-----start---------------------------
import workOrderForm from "./components/work-order-form.vue";
import workOrderBoms from "./components/work-order-boms.vue";
import workOrderMaterials from "./components/work-order-materials.vue";
import materialsChoose from "@/components/materials/choose.vue";
// --------------------------引用组件-----end-----------------------------
// --------------------------引用全局变量$t-------------------------------
const { appContext } = getCurrentInstance();
const t = appContext.config.globalProperties.$t;

// ----------------------------选项卡----------------------------------
// 选项卡标题
const tabTitles = ref([
  t("workOrder.workOrderInfo"),
  t("workOrder.maintenanceWorkOrderList"),
  t("workOrder.materialList"),
]);
const currentTab = ref(0);
const styleType = ref("text");
const activeColor = ref("#004098");
const onClickTabItem = (e) => {
  // 如果要切换的选项卡是“物料列表”，则先判断当前选中的保养项是否关闭消耗物料（rule=1），如果是，则不允许切换到“物料列表”，并提示
  if (!onBeforeTabChange(e.currentIndex, currentBomData.value)) {
    return;
  }
  currentTab.value = e.currentIndex;
};
// 关闭物料消耗（rule=1）时，不允许切换到物料列表tab
const onBeforeTabChange = (index, bom) => {
  if (index === 2 && bom?.rule == 1) {
    uni.showToast({
      title: t("maintenanceWorkOrder.notConsumeMaterial"),
      icon: "none",
    });
    return false;
  }
  return true;
};
// ----------------------------提示信息弹窗----------------------------------
const messageGlobalRef = ref(null);
// 提示信息弹窗类型
const msgType = ref("success");
// 提示信息弹窗内容
const messageText = ref("");
// 提示信息弹窗方法
const showMessage = (type, message) => {
  msgType.value = type;
  messageText.value = message;
  messageGlobalRef.value.openMessage();
};

// -----------------------------表单----------------------------------
const mainWorkOrder = ref({
  name: "", // 工单名称
  outsourcingFlag: "0", // 保养类型(是否委外 0否 1是)
  actualStartTime: "", // 实际开始时间
  actualEndTime: "", // 实际结束时间
  remark: "", // 备注
  cost: "", // 保养费用
  otherCost: "", // 其他费用
  type: 2, //工单类型(1计划生成 2临时新建),
  deptId: null, // 部门id"
  responsiblePerson: getUserId(), // 负责人
});

// 获取子组件实例
const workOrderFormRef = ref(null);

// 提交方法中添加校验逻辑
const validateForm = async () => {
  // 调用子组件的校验方法
  const isValid = await workOrderFormRef.value.validate();

  if (isValid) {
    // 校验通过，执行提交逻辑
    console.log("子组件表单校验通过，校验通过的表单数据:", mainWorkOrder.value);
    // 判断mainWorkOrder.value中的实际保养结束时间是否大于实际保养开始时间
    if (
      mainWorkOrder.value.actualEndTime &&
      mainWorkOrder.value.actualStartTime &&
      mainWorkOrder.value.actualEndTime < mainWorkOrder.value.actualStartTime
    ) {
      uni.showToast({
        title: t("maintenanceWorkOrder.timeNotBeEarlier"),
        icon: "none",
      });
      mainWorkOrder.value.actualEndTime = "";
      return false;
    }
    return true;
  } else {
    // 校验失败，不执行提交
    console.log("表单校验失败");
    return false;
  }
};

// 计算保养费用
const calculateMaintenanceCost = () => {
  let totalCost = 0;

  mainWorkOrderBom.value.forEach((bom) => {
    // 条件1：关闭是否消耗物料（rule=1）
    const isNotConsumeMaterial = bom.rule == 1;
    // 检查是否设置了延保相关信息
    const hasDelaySetting = isBomDelaySet(bom);

    // 条件2：开启是否消耗物料（rule=0）且未设置延保信息
    if (!isNotConsumeMaterial && !hasDelaySetting) {
      // 遍历物料计算费用
      bom.deviceBomMaterials?.forEach((material) => {
        const quantity = Number(material.quantity) || 0;
        const unitPrice = Number(material.unitPrice) || 0;

        // 只计算消耗数量大于0的物料
        if (quantity > 0) {
          totalCost += quantity * unitPrice;
        }
      });
    }
  });

  // 更新工单保养费用（保留两位小数）
  mainWorkOrder.value.cost = totalCost.toFixed(2);
};

// ----------------------------------保养项-------------------------------
// 保养项列表
const mainWorkOrderBom = ref([]);
// 保养项列表原数据（提交用：不修改deviceBomMaterials）
const mainWorkOrderBomOriginal = ref([]);
// 保养项统计
const bomNumbers = reactive({
  total: 0, // 保养项总数
  maintained: 0, // 已保养项数
  notMaintained: 0, // 未保养项数
});
// 当前所选保养项
const currentBomData = ref(null);
// 切换当前保养项
const onSelectBom = (bom) => {
  console.log("onSelectBom", bom);
  // 检查选择的保养项是否关闭消耗物料（rule=1）,若关闭则提示且不跳转

  if (!onBeforeTabChange(2, bom)) {
    return;
  }

  // 更新当前所选保养项数据
  currentBomData.value = bom;
  // 更新展示的物料列表
  // 更新传递给子组件的物料列表
  materialList.value = bom.deviceBomMaterials || [];
  // 切换到物料列表tab
  currentTab.value = 2;
};

// 更新保养项统计数量（已保养和未保养）
const updateBomStatistics = () => {
  let total = mainWorkOrderBom.value.length;
  let maintained = 0;

  mainWorkOrderBom.value.forEach((bom) => {
    // 计算物料总数
    calculateMaterialCount(bom);

    // 判断是否为已保养项
    const isMaintained = checkIfMaintained(bom);
    if (isMaintained) {
      // 已保养项数增加
      maintained++;
      // 添加已保养标识
      bom.maintainedFlag = true;
    } else {
      // 添加未保养标识
      bom.maintainedFlag = false;
    }
  });

  bomNumbers.total = total;
  bomNumbers.maintained = maintained;
  bomNumbers.notMaintained = total - maintained;
};

/**
 * 检查保养项是否满足已保养条件
 * @param {Object} bom - 保养项数据
 * @returns {boolean} - 是否满足已保养条件
 * @description
 * 1.保养状态（status  0保养中  1保养完成）为保养完成时：
 *   1). 关闭是否消耗物料（rule=1）
 *   2). 开启是否消耗物料（rule=0）：存在物料列表，且所有物料的消耗数量均大于0
 * 2. 延保相关信息
 *    2.1 检查延迟保养规则是否启用
 *    2.2 若没有启用的规则，或启用规则但对应延迟值均不大于0
 *
 */
const checkIfMaintained = (bom) => {
  // 检查保养状态是否为保养完成
  const bomStatusCompleted = isBomStatusCompleted(bom);
  if (bomStatusCompleted) {
    // 检查是否关闭消耗物料
    const isNotConsumeMaterial = isBomNotConsumeMaterial(bom);

    // 检查物料消耗数量是否均大于0
    const allMaterialsValid = checkAllMaterialsValid(bom);
  }
  /**
   * 检查是否设置了延保相关信息
   * 1. 检查延迟保养规则是否启用:mileageRule,naturalDateRule,runningTimeRule(0启用 1停用)
   * 2. 若启用规则但对应延迟值均不大于0
   */
  const hasDelaySetting = isBomDelaySet(bom);

  // 满足任一条件即视为已保养
  return bomStatusCompleted || hasDelaySetting;
};
// 保养项 保养状态 是否完成
const isBomStatusCompleted = (bom) => {
  const isCompleted = bom.status == 1;
  // -----------添加物料保养状态标识------------
  bom.isStatusClosed = isCompleted;
    // 如果存在物料列表，将isStatusClosed存入每个物料项中
    if (bom.deviceBomMaterials.length > 0) {
    bom.deviceBomMaterials.forEach((material) => {
      material.isStatusClosed = isCompleted;
    });
  }
  return isCompleted;
};
// 保养项是否消耗物料
const isBomNotConsumeMaterial = (bom) => {
  const isNotConsumeMaterial = bom.rule == "1";
  bom.isNotConsumeMaterial = isNotConsumeMaterial;
  // 如果存在物料列表，将isNotConsumeMaterial存入每个物料项中
  if (bom.deviceBomMaterials.length > 0) {
    bom.deviceBomMaterials.forEach((material) => {
      material.isNotConsumeMaterial = isNotConsumeMaterial;
    });
  }
  return isNotConsumeMaterial;
};
// 保养项是否设置了延保信息
const isBomDelaySet = (bom) => {
  /**
   * 检查是否设置了延保相关信息
   * 1. 检查延迟保养规则是否启用:mileageRule,naturalDateRule,runningTimeRule(0启用 1停用)
   * 2. 若启用规则但对应延迟值均不大于0
   */
  const isAnyRuleActive =
    bom.mileageRule === 0 ||
    bom.naturalDateRule === 0 ||
    bom.runningTimeRule === 0;
  const hasDelaySetting =
    !isAnyRuleActive ||
    (isAnyRuleActive &&
      (bom.delayKilometers > 0 ||
        bom.delayNaturalDate > 0 ||
        bom.delayDuration > 0));

  // console.log("🚀 是否设置了延保相关信息:", hasDelaySetting);
  // 设置保养项是否设置了延保信息
  bom.isDelay = hasDelaySetting;

  // 如果存在物料列表，将isDelay存入每个物料项中
  if (bom.deviceBomMaterials.length > 0) {
    bom.deviceBomMaterials.forEach((material) => {
      // 添加物料是否延迟标志
      material.isDelay = hasDelaySetting;
    });
  }
  return hasDelaySetting;
};
// 检查所有物料消耗数量是否均大于0
const checkAllMaterialsValid = (bom) => {
  if (!bom.deviceBomMaterials || bom.deviceBomMaterials.length === 0) {
    return false;
  }

  return bom.deviceBomMaterials.every((material) => {
    const quantity = Number(material.quantity);
    return !isNaN(quantity) && quantity > 0;
  });
};

// 计算保养项中所有物料的消耗数量累计
const calculateMaterialCount = (bom) => {
  if (!bom.deviceBomMaterials || bom.deviceBomMaterials.length === 0) {
    bom.materialCount = 0;
    return;
  }
  // 物料数量为保养项下所有物料 消耗数量累计
  const total = bom.deviceBomMaterials.reduce((sum, material) => {
    const quantity = Number(material.quantity) || 0;
    return sum + quantity;
  }, 0);

  bom.materialCount = total;
};

// 更新保养项数量统计及保养费用
const updateBomStatisticsAndCost = () => {
  // 更新保养项统计数量（已保养和未保养）
  updateBomStatistics();
  // 更新保养费用
  calculateMaintenanceCost();
};

// ----------------------------------物料列表---------------------------------

// 所有物料列表
const materialListAll = ref([]);
// 获取的保养项物料列表
const materialByWorkOrderIdList = ref([]);
// 获取的保养项物料列表根据bomNodeId与id组合的对象
const materialByWorkOrderIdKeyAndList = ref({});
// 传递给子组件的物料列表
const materialList = ref([]);
// 是否展示所有物料
const allMaterialShow = ref(false);
// 新添加的物料项
const newMaterialItem = ref({
  id: null, //物料id
  bomNodeId: null, // 保养项id
  bomName: null, // 保养项名称
  materialCode: null, // 物料编码
  materialName: null, // 物料名称
  unit: null, // 物料单位
  unitPrice: 0, // 物料单价
  quantity: 0, // 物料消耗数量
  materialSource: t("workOrder.manualAdd"), // 物料来源
  isNew: true, // 是否是新添加的物料
});

// 查询保养工单已经选择的所有物料
const getBomsMaterialList = async (id) => {
  const getBomMaterialsByWorkOrderIdAsync = getBomMaterialsByWorkOrderId({
    workOrderId: id,
  });
  const bomMaterials = (await getBomMaterialsByWorkOrderIdAsync).data;
  if (bomMaterials && bomMaterials.length > 0) {
    materialByWorkOrderIdList.value = bomMaterials;
    // 根据bomNodeId与id组合保养项物料列表
    materialByWorkOrderIdList.value.forEach((material) => {
      const key = material.bomNodeId;
      if (materialByWorkOrderIdKeyAndList.value[key]) {
        materialByWorkOrderIdKeyAndList.value[key].push(material);
      } else {
        materialByWorkOrderIdKeyAndList.value[key] = [material];
      }
    });
  }
};

// 新增物料
const addMaterial = () => {
  /**
   * 新增物料
   * 1. 不直接在materialList.value中添加新物料是因为:
   *    在展示所有物料时添加的新物料时再次切换到展示当前物料，新增的物料不会更新到当前保养项中
   * 2. 将新添加的物料项放入当前保养项的物料列表第一个
   */

  currentBomData.value.deviceBomMaterials.unshift({
    ...newMaterialItem.value,
    bomNodeId: currentBomData.value.bomNodeId,
    bomName: currentBomData.value.name,
  });
  // 更新展示的物料列表
  changeMaterialListByShow();
  // 更新保养项数量统计及保养费用
  updateBomStatisticsAndCost();
};

// 删除物料
const onDeleteMaterial = (data) => {
  materialList.value.splice(data.index, 1);
  // 更新当前保养项的物料数量
  calculateMaterialCount(currentBomData.value);
  // 更新保养项数量统计及保养费用
  updateBomStatisticsAndCost();
};
// 选择物料
const materialsChooseRef = ref(null);
const onMaterialChoose = (item) => {
  console.log("onMaterialChoose", item);
  materialsChooseRef.value.open(item);
};
// 选择物料弹窗提交
const onMaterialChooseSubmit = (item) => {
  console.log("onMaterialChooseSubmit", item);
  /**
   * 1. 检查当前物料是否已存在
   *    保养项id(bomNodeId)、
   *    物料编码(materialCode)或物料名称(materialName)、
   *    成本中心id(costCenterId)、
   *    工厂id(factoryId)、
   *    单价(unitPrice)、
   *    库位id(storageLocationId)
   *    全部相同时视为同一物料
   * 2. 若已存在，则累加数量
   * 3. 若不存在，则新增物料
   */
  // 是否存在相同物料，若存在则累加数量，若不存在则新增
  const existMaterial = currentBomData.value.deviceBomMaterials.find(
    (material) => {
      const materialChooseKey = `${
        material.materialCode ? material.materialCode : material.materialName
      }_${material.costCenterId}_${material.factoryId}_${material.unitPrice}_${
        material.storageLocationId
      }`;
      return materialChooseKey === item.chooseKey;
    }
  );
  if (existMaterial) {
    existMaterial.quantity += item.quantity;
  } else {
    currentBomData.value.deviceBomMaterials.unshift({
      ...item,
      bomNodeId: currentBomData.value.bomNodeId, // 保养项id
      bomName: currentBomData.value.name, // 保养项名称
      isNew: false, // 是否是新添加的物料
    });
  }
  // 更新展示的物料列表
  changeMaterialListByShow();
  // 更新保养项数量统计及保养费用
  updateBomStatisticsAndCost();
};
// 切换展示的物料列表
const changeMaterialList = () => {
  // 切换展示所有物料状态
  allMaterialShow.value = !allMaterialShow.value;
  // 根据展示状态切换物料列表
  changeMaterialListByShow();
};

// 返回所有物料列表
const getAllMaterialList = () => {
  const list = mainWorkOrderBom.value
    .map((bom) => {
      if (bom.deviceBomMaterials) {
        return bom.deviceBomMaterials;
      }
    })
    .flat();
  return list;
};
// 根据物料展示状态(allMaterialShow)，切换展示的物料列表
const changeMaterialListByShow = () => {
  // allMaterialShow 为 true 时展示所有物料列表
  if (allMaterialShow.value) {
    materialList.value = getAllMaterialList();
  } else {
    // allMaterialShow 为 false 时展示当前所选保养项的物料列表
    materialList.value = currentBomData.value.deviceBomMaterials;
  }
};

// 保存物料列表
const saveMartialList = async () => {
  /**
   * 校验当前展示的物料列表
   *  1.物料列表为空时，提示请添加物料
   *  2.新增的物料(isNew=true)物料名称不能为空，单价不能为空，消耗数量>0
   *  3.已有的物料(isNew=false)单价不能为空，消耗数量>0
   * 记录所有不符合校验的物料保养项名称，拼接提示
   */
  console.log("保存物料列表：开始");
  // 校验物料列表是否为空
  if (materialList.value.length === 0) {
    uni.showToast({
      title: t("maintenanceWorkOrder.materialEmpty"),
      icon: "none",
    });
    return;
  }
  const invalidBomNames = [];
  materialList.value.map((material, index) => {
    // 校验新增的物料
    if (material.isNew) {
      if (
        !material.materialName ||
        !material.unitPrice ||
        !material.quantity ||
        material.quantity <= 0
      ) {
        invalidBomNames.push(
          material.bomName +
            ":" +
            (material.materialName
              ? material.materialName
              : t("workOrder.serialNumber") + "(" + (index + 1) + ")")
        );
      }
    } else {
      // 校验已有的物料
      if (!material.unitPrice || !material.quantity || material.quantity <= 0) {
        invalidBomNames.push(material.bomName + ":" + material.materialName);
      }
    }
  });
  // 去重
  const uniqueInvalidBomNames = [...new Set(invalidBomNames)];
  /**
   * 拆分提示
   * 若不符合校验的物料大于3，提示前3项，其余项用...表示
   * 若不符合保养项的数量小于3，则全部提示
   */
  if (uniqueInvalidBomNames.length > 0) {
    const msg =
      uniqueInvalidBomNames.slice(0, 3).join(";\n") +
      (uniqueInvalidBomNames.length > 3 ? "..." : "\n") +
      t("workOrder.materialInvalid");
    showMessage("error", msg);
    return;
  }
  // 校验通过，将tab切换到保养项列表并提示保存成功
  const msg = t("workOrder.currentMaterialList") + t("operation.saveSuccess");
  showMessage("success", msg);
  currentTab.value = 1;
  console.log("保存物料列表：结束");
};

// ----------------------------------工单提交---------------------------------
const submitWorkOrder = async () => {
  // 校验表单信息
  const formIsValid = await validateForm();
  if (!formIsValid) return;
  // 校验是否存在未保养项
  if (bomNumbers.notMaintained > 0) {
    uni.showToast({
      title: t("maintenanceWorkOrder.unFinishedMaintenanceItems"),
      icon: "none",
    });
    return;
  }
  // 处理提交的参数
  // 提取数据处理逻辑为独立函数 - 使用对象解构赋值代替 delete 操作，避免修改原始数据
  const processBomData = (bomItems) => {
    console.log("🚀 ~ processBomData ~ bomItems:", bomItems);
    console.log(
      "🚀 ~ processBomData ~ mainWorkOrderBomOriginal.value:",
      mainWorkOrderBomOriginal.value
    );
    return bomItems.map((item) => {
      const {
        materialCount,
        maintainedFlag,
        deviceBomMaterials,
        isDelay,
        isNotConsumeMaterial,
        ...rest
      } = item;
      // 查找原始数据中对应的deviceBomMaterials
      const originalDeviceBomMaterials = mainWorkOrderBomOriginal.value.find(
        (bom) => bom.bomNodeId === item.bomNodeId
      )?.deviceBomMaterials;
      // 用原始数据的deviceBomMaterials重新赋值给 rest.deviceBomMaterials
      rest.deviceBomMaterials = originalDeviceBomMaterials;

      return rest;
    });
  };
  const processMaterialData = (materialItems) => {
    return materialItems.map((item) => {
      const {
        bomName,
        isNew,
        bomDisabled,
        isDelay,
        isNotConsumeMaterial,
        isStatusClosed,
        ...rest
      } = item;
      // 将 materialName/name和materialCode/code保持一致
      rest.materialName = rest.materialName ? rest.materialName : rest.name;
      rest.name = rest.materialName;
      rest.materialCode = rest.materialCode ? rest.materialCode : rest.code;
      rest.code = rest.materialCode;
      return rest;
    });
  };

  // 删除mainWorkOrderBom.value中的maintainedFlag, materialCount字段
  const orderBom = processBomData([
    ...JSON.parse(JSON.stringify(mainWorkOrderBom.value)),
  ]);
  console.log("orderBom", orderBom);
  // 获取所有物料列表，删除bomName，isNew,bomDisabled字段
  const mainWorkOrderMaterials = getAllMaterialList();
  const orderMaterials = processMaterialData([...mainWorkOrderMaterials]);
  fillWorkOrder({
    mainWorkOrder: mainWorkOrder.value,
    mainWorkOrderBom: orderBom,
    mainWorkOrderMaterials: orderMaterials,
  })
    .then((res) => {
      console.log("fillWorkOrder", res);
      if (res.code == 0) {
        uni.showToast({
          title: t("operation.success"),
          icon: "none",
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 2000);
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      }
    })
    .catch((err) => {
      console.log("err", err);
    });
};
// ----------------------------工单详情初始化---------------------------------
const workOrderDetailInit = async (id) => {
  // 获取工单信息
  const getMaintenanceDetailAsync = getMaintenanceDetail({ id: id });
  mainWorkOrder.value = (await getMaintenanceDetailAsync).data;
  // 获取保养项信息
  const getWorkOrderBOMsAsync = getWorkOrderBOMs({ workOrderId: id });
  const data = (await getWorkOrderBOMsAsync).data;
  if (!data.length) return;
  // 备份保养项列表原数据（提交用：不修改deviceBomMaterials）
  mainWorkOrderBomOriginal.value = JSON.parse(JSON.stringify(data));

  //组合mainWorkOrderBom，合并保养项物料列表
  data.forEach((bom) => {
    // 合并保养项物料列表
    const bomKey = bom.bomNodeId;
    if (materialByWorkOrderIdKeyAndList.value[bomKey]) {
      bom.deviceBomMaterials = materialByWorkOrderIdKeyAndList.value[bomKey];
    }
    // 若保养项物料列表为空，则初始化空数组
    if (!bom.deviceBomMaterials) {
      bom.deviceBomMaterials = [];
    }
    // 若保养项不在保养项列表中，则添加到保养项列表
    if (
      !mainWorkOrderBom.value.some(
        (item) => item.bomNodeId === bom.bomNodeId && item.id === bom.id
      )
    ) {
      mainWorkOrderBom.value.push({
        ...bom,
        materialCount: 0,
      });
    }
    // 将保养项名称添加到对应的物料列表中
    if (bom.deviceBomMaterials) {
      bom.deviceBomMaterials.forEach((material) => {
        // 为物料添加保养项名称
        material.bomName = bom.name;
        // 为物料添加是否消耗物料标识(rule=0时为消耗物料,1时为不消耗物料)
        material.bomDisabled = bom.rule == 1;
        // 确保物料名称和物料编码不为空 且 materialName/name和materialCode/code保持一致
        material.materialName = material.materialName
          ? material.materialName
          : material.name;
        material.name = material.materialName;

        material.materialCode = material.materialCode
          ? material.materialCode
          : material.code;
        material.code = material.materialCode;
      });
    }
  });
  // 默认选中第一个保养项
  currentBomData.value = mainWorkOrderBom.value[0];
  // 更新传递给子组件的物料列表
  materialList.value = currentBomData.value.deviceBomMaterials || [];
  // 初始化统计数据
  updateBomStatistics();
};

onLoad(async (option) => {
  console.log("onLoad", option);
  // 通过userId刷新token
  await reloginByUserId(option.reloginUserId);
  // 查询保养工单已经选择的所有物料
  await getBomsMaterialList(option.id);
  // 初始化工单详情
  await workOrderDetailInit(option.id);
});
onReady(() => {
  console.log("onReady");
});
onMounted(() => {
  console.log("onMounted");
});
onBackPress(() => {
  console.log("onBackPress");
});
</script>

<style lang="scss" scoped>
@import "@/style/work-order-segmented.scss";
.page {
  padding-bottom: 0;
}
</style>
