<template>
  <view class="page repair">
    <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="maintain"
          :form-disabled="false"
          @chooseDevice="onChooseDevice"
          @chooseLocalSearch="onChooseLocalSearch"
          @chooseManufacturer="onSelectedManufacturer"
          @uploadImg="uploadImg"
          @deleteImg="deleteImg"
          @uploadOutFiles="uploadOutFiles"
          @deleteOutFiles="deleteOutFiles"
        />
      </view>
      <!-- 维修项列表 -->
      <view class="work-order-bom-list" v-show="currentTab === 1">
        <!-- 维修项列表操作栏 -->
        <uni-row
          class="list-header flex-row align-center justify-start"
          :gutter="10"
        >
          <!-- 选择维修项  -->
          <uni-col :span="9">
            <button
              class="list-header-item flex-row align-center justify-center"
              type="default"
              @click="onChooseRepair()"
            >
              <image
                src="~@/static/workOrder/xuanzhewuliao.png"
                mode="aspectFill"
              ></image>
              <text>
                {{ $t("operation.select")
                }}{{ $t("equipmentMaintenance.maintenanceItems") }}</text
              >
            </button>
          </uni-col>

          <!-- 新增维修项 -->
          <uni-col :span="9">
            <button
              class="list-header-item flex-row align-center justify-center"
              type="default"
              @click="onAddRepair()"
            >
              <image
                src="~@/static/workOrder/xinzengwuliao.png"
                mode="aspectFill"
              ></image>
              <text>
                {{ $t("operation.add")
                }}{{ $t("equipmentMaintenance.maintenanceItems") }}</text
              >
            </button>
          </uni-col>
        </uni-row>
        <view class="list-content">
          <work-order-boms
            :boms-data="maintainBom"
            :current-bom="currentBomData"
            @onSelectBom="onSelectBom"
            @deleteBom="ondeleteBom"
            @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'"
              @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'"
              @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">
      <uni-row
        class="footer-total flex-row align-center justify-between"
        v-if="currentTab < 2"
      >
        <uni-col
          :span="18"
          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("status.finished") }}</text>
            <text class="number">{{ bomNumbers.maintained }}</text>
            <text>{{ t("workOrder.item") }}</text>
          </view>
          <!-- 未完成xx项 -->
          <view class="total-item-text color-red">
            <text>{{ t("status.unfinished") }}</text>
            <text class="number">{{ bomNumbers.notMaintained }}</text>
            <text>{{ t("workOrder.item") }}</text>
          </view>
        </uni-col>

        <uni-col :span="6" class="total-btn">
          <button class="mini-btn" type="primary" @click="submitWorkOrder">
            {{ t("operation.submit") }}
          </button>
        </uni-col>
      </uni-row>
      <view class="footer-btn" v-else>
        <button class="mini-btn" type="primary" @click="saveMartialList">
          {{ t("operation.save") }}{{ t("workOrder.currentMaterialList") }}
        </button>
      </view>
    </view>
  </view>
  <!-- 选择维修项 -->
  <repair-multiple ref="repairMultipleRef" @repair-submit="onRepairSubmit" />
  <!-- 新增维修项 -->
  <repair-add ref="addRef" @add-set="onAddRepairSubmit"></repair-add>
  <!-- 选择物料弹窗 -->
  <materials-choose
    ref="materialsChooseRef"
    :deviceId="addMateriaItem.id"
    :bomNodeId="addMateriaItem.bomNodeId"
    :materialItem="addMateriaItem"
    :noAdd="true"
    @material-submit="onMaterialChooseSubmit"
  />
  <!-- 全局提示信息弹窗 -->
  <global-message-popup
    class="repair-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";
import {
  createRepair,
  getRepairApplicantList,
  getRepairProjectManagerList,
} from "@/api/repair.js";

// --------------------------引用api接口-----start------------------------
import {
  fillWorkOrder,
  getMaintenanceDetail,
  getWorkOrderBOMs,
  getBomMaterialsByWorkOrderId,
} from "@/api/maintenance";
import { uploadFile } from "@/api";
// --------------------------引用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";
import repairMultiple from "@/components/repair/multiple.vue";
import repairAdd from "@/components/repair/add.vue";
// --------------------------引用组件-----end-----------------------------
// --------------------------引用全局变量$t-------------------------------
const { appContext } = getCurrentInstance();
const t = appContext.config.globalProperties.$t;

// ----------------------------选项卡----------------------------------
// 选项卡标题
const tabTitles = ref([
  t("workOrder.workOrderInfo"),
  t("workOrder.repairWorkOrderList"),
  t("workOrder.materialList"),
]);
const currentTab = ref(0);
const styleType = ref("text");
const activeColor = ref("#004098");
const onClickTabItem = (e) => {
  console.log("🚀 ~ onClickTabItem ~ e:", e)
  // 如果要切换的选项卡是“物料列表”，则先判断当前选中的维修项是否关闭消耗物料（rule=1），如果是，则不允许切换到“物料列表”，并提示
  if (!onBeforeTabChange(e.currentIndex,currentBomData.value)) {
      return;
    }
  currentTab.value = e.currentIndex;
};
 // 关闭物料消耗（rule=1）时，不允许切换到物料列表tab
const onBeforeTabChange = (index,bom) => {
  console.log("🚀 ~ onBeforeTabChange ~ index,bom:", index,bom)
  if (index === 2 && bom?.rule == 1) {
    uni.showToast({
      title: t("equipmentMaintenance.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 bomNumbers = reactive({
  total: 0, // 维修项总数
  maintained: 0, // 已维修项数
  notMaintained: 0, // 未维修项数
});
// 当前所选维修项
const currentBomData = ref(null);
// 切换当前维修项
const onSelectBom = (bom) => {
  console.log("onSelectBom", bom);
  // 检查选择的维修项是否关闭消耗物料（rule=1）,若关闭则提示且不跳转
  if (bom.rule == "1") {
    uni.showToast({
      title: t("equipmentMaintenance.notConsumeMaterial"),
      icon: "none",
    });
    return;
  }

  // 更新当前所选维修项数据
  currentBomData.value = bom;
  // 更新展示的物料列表
  // 更新传递给子组件的物料列表
  materialList.value = bom.materials || [];
  // 切换到物料列表tab
  currentTab.value = 2;
  // 通过点击维修项进入物料列表时，切换到"当前物料"展示
  allMaterialShow.value = false;
};

// -----------------------------表单----------------------------------
const workOrderFormRef = ref(null);
//维修工单表单
const maintain = ref({
  deviceId: "",
  deviceName: "",
  type: "in", // 类型(是否委外 in 内部 out 外部)
  picList: [], //用于上传照片 提交时删除
  pics: [], // 用于存放上传后的照片地址 提交时使用
  outFilesList: [], // 用于上传委外相关附件 提交时删除
  outFiles: [], // 用于存放上传后的委外相关附件地址 提交时使用
});
const selectedDevices = ref({});
const onChooseDevice = (data) => {
  console.log("onChooseDevice", data);
  maintain.value.deviceId = data.id;
  maintain.value.deptId = data.deptId;
  maintain.value.deviceCode = data.deviceCode;
  maintain.value.deviceName = data.deviceName;
  console.log("onChooseDevice-maintain", maintain.value);
  // 将选择的设备赋值给selectedDevices
  selectedDevices.value = data;
  // 如果维修类型为OA委外，将设备的model值（规格型号）赋值给maintain的model
  if (maintain.value.type === "out") {
    maintain.value.model = data.model;
    // 同时将设备的enableDate值（启用日期）赋值给maintain的enableDate
    maintain.value.enableDate = data.enableDate;
  } else {
    // 否则将model清空
    maintain.value.model = "";
    // 同时将enableDate清空
    maintain.value.enableDate = "";
  }
};
// 供应商选择确认
const onSelectedManufacturer = (item) => {
  console.log("🚀 ~ onSelectedManufacturer ~ item:", item);
  maintain.value.supplier = item.name;
};
// 上传图片
const uploadImg = async (event) => {
  console.log("🚀 ~ upload ~ event:", event);
  console.log("🚀 ~ upload ~ event.tempFilePaths):", event.tempFilePaths);
  for (const path of event.tempFilePaths) {
    maintain.value.pics.push((await uploadFile(path)).data);
  }
  console.log("🚀 ~ upload ~ maintain.value.pics :", maintain.value.pics);
};
// 删除图片
const deleteImg = (event) => {
  console.log("🚀 ~ deleteImg ~ event:", event);
  maintain.value.pics.splice(event.index, 1);
  console.log("🚀 ~ deleteImg ~ maintain.value.pics:", maintain.value.pics);
};

// 上传委外相关附件
const uploadOutFiles = async (event) => {
  console.log("🚀 ~ uploadOutFiles ~ event:", event);
  console.log(
    "🚀 ~ uploadOutFiles ~ event.tempFilePaths):",
    event.tempFilePaths
  );
  for (const path of event.tempFilePaths) {
    maintain.value.outFiles.push((await uploadFile(path)).data);
  }
  console.log(
    "🚀 ~ uploadOutFiles ~ maintain.value.outFiles :",
    maintain.value.outFiles
  );
};
// 删除委外相关附件
const deleteOutFiles = (event) => {
  console.log("🚀 ~ deleteOutFiles ~ event:", event);
  maintain.value.outFiles.splice(event.index, 1);
  console.log(
    "🚀 ~ deleteOutFiles ~ maintain.value.outFiles:",
    maintain.value.outFiles
  );
};
// 本地搜索确认选择
const onChooseLocalSearch = (propKey, item) => {
  console.log("🚀 ~ onChooseLocalSearch ~ propKey, item:", propKey, item);
  // 根据propKey设置maintain的值
  maintain.value[propKey] = item.value;
};

// 维修项列表
const maintainBom = ref([]);
// 选择维修项
const repairMultipleRef = ref(null);

const onChooseRepair = () => {
  // 判断是否选择设备
  if (!maintain.value.deviceId) {
    uni.showToast({
      title: ` ${t("operation.please")}${t("device.selectDevice")}`,
      icon: "none",
    });
    return;
  }
  repairMultipleRef.value.open([maintain.value.deviceId]);
};

// 选择维修项提交
const onRepairSubmit = (data) => {
  console.log("onRepairSubmit", data);
  // 判断data数组中bomNodeId是否存在maintainBom数组中, 如果不存在, 则添加 并将materialSelected设为false
  data.forEach((bom) => {
    if (!maintainBom.value.some((item) => item.bomNodeId === bom.bomNodeId)) {
      maintainBom.value.push({
        ...bom,
        rule: data.rule || 0, //是否消耗物料  (0需要 1不需要)
        materialCount: 0, // 物料数量
        materials: [], // 物料明细
        workOrderBomOnlyKey: `${bom.deviceCode}_${bom.deviceName}_${bom.name}`, //手动拼接唯一标识
        materialSelected: false, //手动添加是否选择物料标识
      });
      if (bom.deviceBomMaterials && !bom.materials) {
        bom.materials = [];
        bom.deviceBomMaterials.forEach((material) => {
          bom.materials.push({
            ...material,
            bomName: bom.name,
            bomDisabled: bom.rule == 1, //是否消耗物料  (0需要 1不需要)
            materialName: material.materialName
              ? material.materialName
              : material.name, // 确保物料名称和物料编码不为空
            materialCode: material.materialCode
              ? material.materialCode
              : material.code,
          });
        });
      }
    }
  });
  console.log("onRepairSubmit-maintainBom", maintainBom.value);
  // 判断是否存在选择的维修项,若不存在，则将数组第一项设为当前维修项
  if (!currentBomData.value) {
    currentBomData.value = maintainBom.value[0];
  }
  // 更新维修项数量统计及保养费用
  updateBomStatisticsAndCost();
};
// 新增维修项
const addRef = ref(null);
// 新增维修项弹窗
const onAddRepair = () => {
  // 判断是否选择设备
  if (!maintain.value.deviceId) {
    uni.showToast({
      title: ` ${t("operation.please")}${t("device.selectDevice")}`,
      icon: "none",
    });
    return;
  }
  const info = {
    id: maintain.value.deviceId,
    deptId: maintain.value.deptId,
    deviceId: maintain.value.deviceId,
    deviceCode: maintain.value.deviceCode,
    deviceName: maintain.value.deviceName,
    bom: maintainBom.value,
  };
  addRef.value.open(info);
};
// 新增维修项提交
const onAddRepairSubmit = (data) => {
  console.log("onAddRepairSubmit", data);
  maintainBom.value.push({
    ...data,
    rule: data.rule || 0, //是否消耗物料
    materialCount: 0, // 物料数量
    materials: [], // 物料明细
    workOrderBomOnlyKey: `${data.deviceCode}_${data.deviceName}_${data.name}`, //手动拼接唯一标识
    materialSelected: false, //手动添加是否选择物料标识
  });
  // 判断是否存在选择的维修项,若不存在，则将数组第一项设为当前维修项
  if (!currentBomData.value) {
    currentBomData.value = maintainBom.value[0];
  }
  // 更新维修项数量统计及保养费用
  updateBomStatisticsAndCost();
};
// 删除维修项
const ondeleteBom = (bom) => {
  console.log("🚀 ~ ondeleteBom ~ bom:", bom);
  // 查找maintainBom中是否存在bom
  const index = maintainBom.value.findIndex(
    (item) => item.workOrderBomOnlyKey === bom.workOrderBomOnlyKey
  );
  if (index !== -1) {
    maintainBom.value.splice(index, 1);
    if (currentBomData.value.workOrderBomOnlyKey === bom.workOrderBomOnlyKey) {
      currentBomData.value = maintainBom.value[0] || {};
    }
    // 删除维修项后更新物料列表
    changeMaterialListByShow();
    // 更新维修项数量统计及保养费用
    updateBomStatisticsAndCost();
  }
};
// 物料选择
const materialsChooseRef = ref(null);
const addMateriaItem = ref({});
const onMaterialChoose = (item) => {
  console.log("onMaterialChoose", item);
  // 判断是否选择设备
  if (!maintain.value.deviceId) {
    uni.showToast({
      title: ` ${t("operation.please")}${t("device.selectDevice")}`,
      icon: "none",
    });
    return;
  }
  if (!item || !item.bomNodeId) {
    uni.showToast({
      title: ` ${t("operation.please")}${t("workOrder.selectConsumeMaterial")}`,
      icon: "none",
    });
    return;
  }
  addMateriaItem.value = 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.materials.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.materials.unshift({
      ...item,
      bomNodeId: currentBomData.value.bomNodeId, // 维修项id
      bomName: currentBomData.value.name, // 维修项名称
      isNew: false, // 是否是新添加的物料
    });
  }
  // 更新展示的物料列表
  changeMaterialListByShow();
  // 更新维修项数量统计及保养费用
  updateBomStatisticsAndCost();
};
// 保养工单 - 物料
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 changeMaterialList = () => {
  // 切换展示所有物料状态
  allMaterialShow.value = !allMaterialShow.value;
  // 根据展示状态切换物料列表
  changeMaterialListByShow();
};
// 返回所有物料列表
const getAllMaterialList = () => {
  const list = maintainBom.value
    .map((bom) => {
      if (bom.materials) {
        return bom.materials;
      }
    })
    .flat();
  return list;
};
// 根据物料展示状态(allMaterialShow)，切换展示的物料列表
const changeMaterialListByShow = () => {
  // allMaterialShow 为 true 时展示所有物料列表
  if (allMaterialShow.value) {
    materialList.value = getAllMaterialList();
  } else {
    // allMaterialShow 为 false 时展示当前所选维修项的物料列表
    materialList.value = currentBomData.value?.materials || [];
  }
};
// 新增物料
const addMaterial = () => {
  /**
   * 新增物料
   * 1. 不直接在materialList.value中添加新物料是因为:
   *    在展示所有物料时添加的新物料时再次切换到展示当前物料，新增的物料不会更新到当前维修项中
   * 2. 将新添加的物料项放入当前维修项的物料列表第一个
   */
  // 判断是否选择设备
  if (!maintain.value.deviceId) {
    uni.showToast({
      title: ` ${t("operation.please")}${t("device.selectDevice")}`,
      icon: "none",
    });
    return;
  }

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

// 更新维修项统计数量（已完成和未完成）
const updateBomStatistics = () => {
  let total = maintainBom.value.length;
  let maintained = 0;

  maintainBom.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;
  console.log("🚀 ~ 更新维修项统计数量 ~ bomNumbers:", bomNumbers);
};

/**
 * 检查维修项是否满足已保养条件
 * @param {Object} bom - 维修项数据
 * @returns {boolean} - 是否满足已保养条件
 * @description
 * 1. 关闭是否消耗物料（rule=1）
 * 2. 延保相关信息
 *    2.1 检查延迟保养规则是否启用
 *    2.2 若没有启用的规则，或启用规则但对应延迟值均不大于0
 * 3. 所有物料的消耗数量均大于0（如果需要消耗物料）
 *
 */
const checkIfMaintained = (bom) => {
  // 条件1：关闭是否消耗物料（rule=1）
  const isNotConsumeMaterial = isBomNotConsumeMaterial(bom);
  // console.log("🚀 ~ 是否消耗物料:", isNotConsumeMaterial);

  // console.log("🚀 ~ 是否设置了延保相关信息:", hasDelaySetting);
  // 条件3：所有物料的消耗数量均大于0（如果需要消耗物料）
  const allMaterialsValid = checkAllMaterialsValid(bom);
  // console.log("🚀 ~ 是否所有物料的消耗数量均大于0:", allMaterialsValid);

  // 满足任一条件即视为已保养
  return isNotConsumeMaterial || allMaterialsValid;
};
// 维修项是否消耗物料
const isBomNotConsumeMaterial = (bom) => {
  const isNotConsumeMaterial = bom.rule == "1";
  bom.isNotConsumeMaterial = isNotConsumeMaterial;
  // 如果存在物料列表，将isNotConsumeMaterial存入每个物料项中
  if (bom.materials.length > 0) {
    bom.materials.forEach((material) => {
      material.isNotConsumeMaterial = isNotConsumeMaterial;
    });
  }
  return isNotConsumeMaterial;
};

// 检查所有物料消耗数量是否均大于0
const checkAllMaterialsValid = (bom) => {
  if (!bom.materials || bom.materials.length === 0) {
    return false;
  }

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

// 计算维修项中所有物料的消耗数量累计
const calculateMaterialCount = (bom) => {
  if (!bom.materials || bom.materials.length === 0) {
    bom.materialCount = 0;
    return;
  }

  const total = bom.materials.reduce((sum, material) => {
    const quantity = Number(material.quantity) || 0;
    return sum + quantity;
  }, 0);

  bom.materialCount = total;
};
// 计算保养费用
const calculateMaintenanceCost = () => {
  let totalCost = 0;

  maintainBom.value.forEach((bom) => {
    // 条件1：关闭是否消耗物料（rule=1）
    const isNotConsumeMaterial = bom.rule == 1;
    // console.log("🚀计算保养费用 ~ 是否消耗物料:", isNotConsumeMaterial);
    // 条件2：开启是否消耗物料（rule=0）
    if (!isNotConsumeMaterial) {
      // 遍历物料计算费用
      bom.materials?.forEach((material) => {
        const quantity = Number(material.quantity) || 0;
        const unitPrice = Number(material.unitPrice) || 0;

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

  // 更新工单保养费用（保留两位小数）
  maintain.value.maintainFee = totalCost.toFixed(2);
  console.log("🚀计算保养费用 ~ 保养费用:", totalCost);
};

// 更新维修项数量统计及保养费用
const updateBomStatisticsAndCost = () => {
  console.log("🚀 ~ 更新维修项数量统计及保养费用 ~ bom:", maintainBom.value);
  // 更新维修项统计数量（已完成和未完成）
  updateBomStatistics();
  // 更新保养费用
  calculateMaintenanceCost();
};
// 删除物料
const onDeleteMaterial = (data) => {
  materialList.value.splice(data.index, 1);
  // 更新当前维修项的物料数量
  calculateMaterialCount(currentBomData.value);
  // 更新维修项数量统计及保养费用
  updateBomStatisticsAndCost();
};
// 保存物料列表
const saveMartialList = async () => {
  /**
   * 校验当前展示的物料列表
   *  1.物料列表为空时，提示请添加物料
   *  2.新增的物料(isNew=true)物料名称不能为空，单价不能为空，消耗数量>0
   *  3.已有的物料(isNew=false)单价不能为空，消耗数量>0
   * 记录所有不符合校验的物料维修项名称，拼接提示
   */
  console.log("保存物料列表：开始");
  console.log("🚀 ~ saveMartialList ~ materialList:", materialList.value);
  // 校验物料列表是否为空
  if (materialList.value.length === 0) {
    uni.showToast({
      title: t("maintenanceWorkOrder.materialEmpty"),
      icon: "none",
    });
    return;
  }
  const invalidBomNames = [];
  materialList.value.forEach((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)];
  console.log(
    "🚀 ~ saveMartialList ~ uniqueInvalidBomNames:",
    uniqueInvalidBomNames
  );
  /**
   * 拆分提示
   * 若不符合校验的物料大于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("保存物料列表：结束");
};

// ----------------------------提交工单------------------------------------
/**
 * 校验时间规则（maintainRules未覆盖的场景）
 * @returns {boolean} 校验结果
 */
const checkTimeRules = async () => {
  const { maintainStartTime, maintainEndTime, failureTime } = maintain.value;

  // 判断维修开始时间是否大于维修结束时间
  if (
    maintainStartTime &&
    maintainEndTime &&
    maintainStartTime > maintainEndTime
  ) {
    uni.showToast({ title: t("general.timeNotBeLater"), icon: "none" });
    return false;
  }
  // 维修开始时间不能早于故障时间
  if (failureTime && maintainStartTime && maintainStartTime < failureTime) {
    uni.showToast({ title: t("general.startTimeNotBeEarlier"), icon: "none" });
    return false;
  }
  // 维修结束时间不能早于故障时间
  if (failureTime && maintainEndTime && maintainEndTime < failureTime) {
    uni.showToast({ title: t("general.endTimeNotBeEarlier"), icon: "none" });
    return false;
  }

  return true;
};

const submitWorkOrder = async () => {
  // 校验表单信息
  const formIsValid = await workOrderFormRef.value.validate();
  console.log("🚀 ~ 保养工单信息校验结果 ~ formIsValid:", formIsValid);
  if (!formIsValid) return;
  // 4. 校验时间规则
  const isTimeValid = await checkTimeRules();
  if (!isTimeValid) return;
  // 5. 业务逻辑校验
  if (maintain.value.type === "in") {
    if (maintainBom.value.length === 0) {
      uni.showToast({
        title: `${t("operation.PleaseSelect")}${t(
          "equipmentMaintenance.maintenanceItems"
        )}`,
        icon: "none",
      });
      return;
    }
   // 校验是否存在未完成的维修项  维修类型为“内部维修”时
  if (bomNumbers.notMaintained > 0 && maintain.value.type == "in") {
    uni.showToast({
      title: t("equipmentMaintenance.unFinishedMaintenanceItems"),
      icon: "none",
    });
    return;
  }
  }
  // 6. 提交数据
  // 提取数据处理逻辑为独立函数 - 使用对象解构赋值代替 delete 操作，避免修改原始数据
  const processMaintainData = (maintainItems) => {
    const { picList, outFilesList, ...rest } = maintainItems;
    return rest;
  };
  // 删除maintainBom.value数组中的materialSelected和workOrderBomOnlyKey
  // 并且删除maintainBom.value.material数组中的chooseKey和workOrderBomOnlyKey
  // 形成一个新数组
  const orderBom = maintainBom.value.map((item) => {
    const newItem = Object.assign({}, item, {
      ifStop: item.ifStop ? true : false,
    });
    delete newItem.materialSelected;
    delete newItem.workOrderBomOnlyKey;
    delete newItem.maintainedFlag;
    delete newItem.isNotConsumeMaterial;

    newItem.materials = newItem.materials.map((materialItem) => {
      const newMaterialItem = {
        ...materialItem,
      };
      delete newMaterialItem.chooseKey;
      delete newMaterialItem.workOrderBomOnlyKey;
      delete newMaterialItem.picList;
      delete newMaterialItem.outFilesList;
      delete newMaterialItem.isNew;
      delete newMaterialItem.isNotConsumeMaterial;
      delete newMaterialItem.bomDisabled;
      delete newMaterialItem.bomName;

      return newMaterialItem;
    });
    return newItem;
  });
  console.log("orderBom", orderBom);

  console.log("🚀 ~ formSubmit ~ maintain.value:", maintain.value);
  const maintainData = processMaintainData(maintain.value);
  console.log("maintainData", maintainData);
  // 提交数据
  createRepair({
    maintain: {
      ...maintainData,
      status: maintain.value.type == "in" ? "finished" : "tx",
    },
    maintainMaterials: orderBom,
  })
    .then((res) => {
      console.log("createRepair", res);
      if (res.code == 0) {
        uni.showToast({
          title: t("operation.success"),
          icon: "success",
        });
        uni.navigateBack();
      } else {
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
      }
    })
    .catch((err) => {
      console.log("createRepair-err", err);
    });
};
// --------------------------------------------监听-------------------------------
// 监听设备变化
watch(
  () => maintain.value.deviceId,
  (newDeviceId, oldDeviceId) => {
    if (newDeviceId !== oldDeviceId) {
      // 1. 清空维修项与物料
      maintainBom.value = [];
      // 2. 重置总费用
      maintain.value.maintainFee = "";
      // 3. 委外类型下，重置规格型号（重新关联新设备的model）与启用日期enableDate
      if (maintain.value.type === "out") {
        maintain.value.model = selectedDevices.value.model || "";
        maintain.value.enableDate = selectedDevices.value.enableDate || "";
      }
      // 4. 重置表单校验（设备相关字段）
      nextTick(() => {
        repairFormRef.value?.clearValidate(["maintainBom", "maintainFee"]);
      });
    }
  }
);

// 监听维修类型数据变化，触发规则更新和校验重置
watch(
  () => maintain.value.type,
  (newVal, oldVal) => {
    console.log("维修类型变更：", oldVal, "->", newVal);
    // 维修类型为OA委外时，获取申请人列表和项目经理列表
    if (newVal == "out" && oldVal !== "out") {
      // 委外类型下，重置规格型号（重新关联新设备的model）与启用日期enableDate
      if (maintain.value.type === "out") {
        maintain.value.model = selectedDevices.value.model || "";
        maintain.value.enableDate = selectedDevices.value.enableDate || "";
      }
    } // 内部类型：清空委外特有字段
    else if (newVal === "in" && oldVal === "out") {
      const outFields = [
        "applyPersonId",
        "maintainClassify",
        "kmHour",
        "model",
        "enableDate",
        "supplier",
        "projectManager",
        "address",
        "outFiles",
        "maintainItem",
      ];
      outFields.forEach((field) => {
        if (field.includes("outFiles")) {
          maintain.value[field] = [];
        } else {
          maintain.value[field] = "";
        }
      });
    }
  }
);
// 监听维修项数据变化，
watch(
  () => maintainBom.value,
  (newVal, oldVal) => {
    console.log("维修项数据变更：", oldVal, "->", newVal);
  },
  { deep: true }
);
</script>

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