<template>
  <view class="page repair">
    <scroll-view scroll-y="true" class="detail">
      <view class="form-content">
        <uni-forms
          ref="repairFormRef"
          labelWidth="140px"
          :modelValue="maintain"
          :rules="maintainRules"
          err-show-type="toast"
        >
          <!-- 设备 -->
          <uni-forms-item
            class="form-item"
            :label="$t('maintenanceWorkOrder.equipment')"
            name="deviceName"
            :required="true"
          >
            <uni-easyinput
              style="text-align: right"
              :inputBorder="false"
              :clearable="false"
              :disabled="true"
              :styles="{ disableColor: '#fff' }"
              :placeholder="$t('operation.PleaseSelect')"
              v-model="maintain.deviceName"
              @focus="onAddDevice"
            />
          </uni-forms-item>
          <!-- 维修类型 -->
          <uni-forms-item
            class="form-item"
            :label="$t('equipmentMaintenance.maintenanceType')"
            name="type"
            :required="true"
          >
            <uni-data-select
              :clear="false"
              v-model="maintain.type"
              :localdata="typeRange"
            >
            </uni-data-select>
          </uni-forms-item>
          <!-- 是否停机 -->
          <uni-forms-item
            class="form-item"
            :label="$t('equipmentMaintenance.isStop')"
            name="ifStop"
            :required="true"
          >
            <uni-data-select
              :clear="false"
              v-model="maintain.ifStop"
              :localdata="ifStopRange"
            >
            </uni-data-select>
          </uni-forms-item>

          <!-- 维修开始时间 维修类型是委外时不必填-->
          <uni-forms-item
            class="form-item"
            :label="$t('equipmentMaintenance.maintenanceStartTime')"
            name="maintainStartTime"
            :required="maintain.type == 'out' ? false : true"
          >
            <!-- :end="dateMax" -->
            <uni-datetime-picker
              type="datetime"
              :border="false"
              :start="maintain.failureTime"
              returnType="timestamp"
              :placeholder="$t('operation.PleaseSelect')"
              :style="{
                color: maintain.maintainStartTime ? '#333' : '#999',
                'font-size': maintain.maintainStartTime
                  ? '14px !important'
                  : 'inherit !important',
              }"
              v-model="maintain.maintainStartTime"
            >
            </uni-datetime-picker>
          </uni-forms-item>
          <!-- return-type="timestamp" -->
          <!-- 维修结束时间 维修类型是委外时不必填-->
          <uni-forms-item
            class="form-item"
            :label="$t('equipmentMaintenance.maintenanceEndTime')"
            name="maintainEndTime"
            :required="maintain.type == 'out' ? false : true"
          >
            <!-- :end="dateMax" -->
            <uni-datetime-picker
              type="datetime"
              :border="false"
              :start="maintain.failureTime"
              returnType="timestamp"
              :placeholder="$t('operation.PleaseSelect')"
              :style="{
                color: maintain.maintainEndTime ? '#333' : '#999',
                'font-size': maintain.maintainEndTime
                  ? '14px !important'
                  : 'inherit !important',
              }"
              v-model="maintain.maintainEndTime"
            />
          </uni-forms-item>
          <!-- 故障时间 维修类型是委外时必填-->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.faultTime')"
            name="failureTime"
            :required="maintain.type == 'out' ? true : false"
          >
            <!-- :end="dateMax" -->
            <uni-datetime-picker
              type="datetime"
              :border="false"
              returnType="timestamp"
              :disabled="true"
              :placeholder="$t('operation.PleaseSelect')"
              :style="{
                color: maintain.failureTime ? '#333' : '#999',
                'font-size': maintain.failureTime
                  ? '14px !important'
                  : 'inherit !important',
              }"
              v-model="maintain.failureTime"
            />
          </uni-forms-item>
          <!-- 故障影响 -->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.faultImpact')"
            name="failureInfluence"
            :required="false"
          >
            <uni-easyinput
              style="text-align: right"
              :inputBorder="false"
              :clearable="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.failureInfluence"
              :placeholder="$t('operation.PleaseFillIn')"
            />
          </uni-forms-item>
          <!-- 故障系统 -->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.faultSystem')"
            name="failureSystem"
            :required="false"
          >
            <uni-easyinput
              style="text-align: right"
              :inputBorder="false"
              :clearable="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.failureSystem"
              :placeholder="$t('operation.PleaseFillIn')"
            />
          </uni-forms-item>
          <!-- 维修费用 维修类型是委外时可填 -->
          <uni-forms-item
            class="form-item"
            :label="$t('equipmentMaintenance.cost')"
            name="maintainFee"
            :required="false"
            v-if="maintain.type == 'in'"
          >
            <uni-easyinput
              style="text-align: right"
              :inputBorder="false"
              :clearable="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.maintainFee"
              :disabled="maintain.type == 'out' ? false : true"
            />
          </uni-forms-item>
          <!-- 图片 -->
          <uni-forms-item
            class="form-item"
            :label="$t('general.picture')"
            name="picList"
            :required="false"
          >
            <uni-file-picker
              file-mediatype="image"
              mode="grid"
              :auto-upload="false"
              :limit="9"
              :imageStyles="{ border: false }"
              v-model="maintain.picList"
              @select="upload"
              @delete="deleteImg"
            >
              <template #default>
                <view
                  class="flex-col align-center justify-center"
                  style="width: 60px; height: 60px; background-color: #f4f4f4"
                >
                  <uni-icons type="plusempty" color="#ACACAC" size="12" />
                </view>
              </template>
            </uni-file-picker>
          </uni-forms-item>
          <!-- 类型是out(OA委外)时，触发oa流程  -->
          <template v-if="maintain.type == 'out'">
            <!-- 申请人 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.applicant')"
              :required="true"
              name="applyPersonId"
            >
              <uni-data-select
                :clear="false"
                :disabled="true"
                v-model="maintain.applyPersonId"
                :localdata="applyPersonRange"
                @click="
                  openLocalSearch(
                    applyPersonRange,
                    'applyPersonId',
                    $t('equipmentMaintenance.applicant')
                  )
                "
              >
              </uni-data-select>
            </uni-forms-item>
            <!-- 维修类别 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.classify')"
              :required="true"
              name="maintainClassify"
            >
              <uni-data-select
                :clear="false"
                v-model="maintain.maintainClassify"
                :localdata="maintainClassifyRange"
              >
              </uni-data-select>
            </uni-forms-item>
            <!-- 运行公里/小时 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.runningKilometersPerHour')"
              :required="false"
              name="kmHour"
            >
              <uni-easyinput
                style="text-align: right"
                :inputBorder="false"
                :clearable="true"
                :styles="{ disableColor: '#fff' }"
                v-model="maintain.kmHour"
                :placeholder="$t('operation.PleaseFillIn')"
              />
            </uni-forms-item>
            <!-- 规格型号 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.specificationModel')"
              :required="true"
              name="specificationModel"
            >
              <uni-easyinput
                style="text-align: right"
                :inputBorder="false"
                :clearable="true"
                :styles="{ disableColor: '#fff' }"
                v-model="maintain.model"
                :placeholder="$t('operation.PleaseFillIn')"
              />
            </uni-forms-item>
            <!-- 启用日期 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.enableDate')"
              :required="true"
              name="enableDate"
            >
              <uni-datetime-picker
                type="date"
                :border="false"
                returnType="string"
                :placeholder="$t('operation.PleaseSelect')"
                :style="{
                  color: maintain.enableDate ? '#333' : '#999',
                  'font-size': maintain.enableDate
                    ? '14px !important'
                    : 'inherit !important',
                }"
                v-model="maintain.enableDate"
              >
              </uni-datetime-picker>
            </uni-forms-item>
            <!-- 供应商 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.supplier')"
              :required="true"
              name="supplier"
            >
              <uni-easyinput
                style="text-align: right"
                :inputBorder="false"
                :clearable="true"
                :styles="{ disableColor: '#fff' }"
                v-model="maintain.supplier"
                :placeholder="$t('operation.PleaseFillIn')"
              >
                <template #right>
                  <button
                    class="mini-btn"
                    type="primary"
                    size="mini"
                    @click="onManufacturerChoose"
                  >
                    {{ $t("operation.PleaseSelect") }}
                  </button>
                </template>
              </uni-easyinput>
            </uni-forms-item>
            <!-- 维修费用 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.cost')"
              :required="true"
              name="maintainFee"
            >
              <uni-easyinput
                style="text-align: right"
                :inputBorder="false"
                :clearable="true"
                :styles="{ disableColor: '#fff' }"
                v-model="maintain.maintainFee"
                :placeholder="$t('operation.PleaseFillIn')"
                :disabled="maintain.type == 'out' ? false : true"
              />
            </uni-forms-item>
            <!-- 项目经理 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.projectManager')"
              :required="true"
              name="projectManager"
            >
              <uni-data-select
                :clear="false"
                :disabled="true"
                v-model="maintain.projectManager"
                :localdata="projectManagerRange"
                @click="
                  openLocalSearch(
                    projectManagerRange,
                    'projectManager',
                    $t('equipmentMaintenance.projectManager')
                  )
                "
              >
              </uni-data-select>
            </uni-forms-item>
            <!-- 维修地点 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.maintenanceLocation')"
              :required="false"
              name="address"
            >
              <uni-easyinput
                style="text-align: right"
                :inputBorder="false"
                :clearable="true"
                :styles="{ disableColor: '#fff' }"
                v-model="maintain.address"
                :placeholder="$t('operation.PleaseFillIn')"
              />
            </uni-forms-item>
            <!-- 委外相关附件 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.outsourceRelatedAttachments')"
              :required="false"
              name="outFilesList"
            >
              <uni-file-picker
                :clear="false"
                :limit="9"
                file-mediatype="all"
                v-model="maintain.outFilesList"
                @select="uploadOutFiles"
                @delete="deleteOutFiles"
              >
              </uni-file-picker>
            </uni-forms-item>
            <!-- 维修项目 -->
            <uni-forms-item
              class="form-item"
              :label="$t('equipmentMaintenance.maintenanceItem')"
              :required="true"
              name="maintainItem"
            >
              <uni-easyinput
                style="text-align: right"
                type="textarea"
                :autoHeight="true"
                :inputBorder="false"
                :clearable="true"
                :styles="{ disableColor: '#fff' }"
                v-model="maintain.maintainItems"
                :placeholder="$t('operation.PleaseFillIn')"
              />
            </uni-forms-item>
          </template>
          <!-- ----------------------------------- OA委外 end ------------------------  -->
          <!-- 故障描述 -->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.description')"
            :required="false"
            name="description"
          >
            <uni-easyinput
              style="text-align: right"
              type="textarea"
              :autoHeight="true"
              :inputBorder="false"
              :clearable="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.description"
              :placeholder="$t('operation.PleaseFillIn')"
            />
          </uni-forms-item>
          <!-- 维修描述 维修类型是委外时不必填-->
          <uni-forms-item
            class="form-item"
            :label="$t('equipmentMaintenance.description')"
            :required="maintain.type == 'out' ? false : true"
            name="maintainDescription"
          >
            <uni-easyinput
              style="text-align: right"
              type="textarea"
              :autoHeight="true"
              :inputBorder="false"
              :clearable="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.maintainDescription"
              :placeholder="$t('operation.PleaseFillIn')"
            />
          </uni-forms-item>
          <!-- 解决办法 -->
          <uni-forms-item
            class="form-item"
            :label="$t('fault.solution')"
            :required="false"
            name="solution"
          >
            <uni-easyinput
              style="text-align: right"
              type="textarea"
              :autoHeight="true"
              :inputBorder="false"
              :clearable="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.solution"
              :placeholder="$t('operation.PleaseFillIn')"
            />
          </uni-forms-item>
          <!-- 备注 -->
          <uni-forms-item
            class="form-item"
            :label="$t('operation.remark')"
            :required="false"
            name="remark"
          >
            <uni-easyinput
              style="text-align: right"
              type="textarea"
              :autoHeight="true"
              :inputBorder="false"
              :clearable="true"
              :styles="{ disableColor: '#fff' }"
              v-model="maintain.remark"
              :placeholder="$t('operation.PleaseFillIn')"
            />
          </uni-forms-item>
        </uni-forms>
        <uni-row class="form-item flex-row align-center">
          <!-- 选择维修项 -->
          <uni-col :span="9">
            <button
              class="add-btn"
              size="mini"
              type="primary"
              @click="onChooseRepair()"
            >
              <uni-icons type="paperplane-filled" color="white"></uni-icons>
              {{ $t("operation.select")
              }}{{ $t("equipmentMaintenance.maintenanceItems") }}
            </button>
          </uni-col>
          <uni-col :span="2"> </uni-col>
          <!-- 新增维修项 -->
          <uni-col :span="9">
            <button
              class="add-btn yellow"
              size="mini"
              type="default"
              @click="onAddRepair()"
            >
              <uni-icons type="plusempty" color="white"></uni-icons>
              {{ $t("operation.add")
              }}{{ $t("equipmentMaintenance.maintenanceItems") }}
            </button>
          </uni-col>
        </uni-row>
        <view class="device-section" v-for="bom in maintainBom">
          <!-- 设备编码 -->
          <view class="item-module">
            <view class="item-content flex-row align-center justify-between">
              <view class="item-title">
                <span class="item-title-width"
                  >{{ $t("device.deviceCode") }}:</span
                >
              </view>
              <view class="item-title">
                <span>{{ bom.deviceCode }}</span>
              </view>
            </view>
            <view class="module-border"> </view>
          </view>
          <!-- 设备名称 -->
          <view class="item-content flex-row align-center justify-between">
            <view class="item-title">
              <span class="item-title-width"
                >{{ $t("device.deviceName") }}:</span
              >
            </view>
            <view class="item-title">
              <span>{{ bom.deviceName }}</span>
            </view>
          </view>
          <!-- 维修项 -->
          <view class="item-content flex-row align-center justify-between">
            <view class="item-title">
              <span class="item-title-width"
                >{{ $t("equipmentMaintenance.maintenanceItems") }}:</span
              >
            </view>
            <view class="item-title">
              <span>{{ bom.name }}</span>
            </view>
          </view>
          <!-- 物料数量 -->
          <view class="item-content flex-row align-center justify-between">
            <view class="item-title">
              <span class="item-title-width"
                >{{ $t("workOrder.materialCount") }}:</span
              >
            </view>
            <view class="item-title">
              <span>{{ bom.materialCount }}</span>
            </view>
          </view>
          <!-- 操作按钮 -->
          <view class="item-opera flex-row justify-end">
            <!-- 删除 -->
            <button type="primary" :plain="true" @click="ondeleteBom(bom)">
              {{ $t("operation.delete") }}
            </button>
            <!-- 选择物料 -->
            <button type="primary" :plain="true" @click="onMaterialChoose(bom)">
              {{ $t("workOrder.selectMaterial") }}
            </button>
            <button
              type="primary"
              :plain="false"
              @click="onMaterialView(bom)"
              v-if="bom.materialSelected"
            >
              {{ $t("workOrder.materialDetails") }}
            </button>
          </view>
        </view>
      </view>
    </scroll-view>
    <button
      class="submit-btn"
      type="primary"
      @click="formSubmit(repairFormRef)"
    >
      {{ $t("operation.submit") }}
    </button>
  </view>
  <!-- 选择设备 -->
  <device-single ref="deviceSingleRef" @devide-submit="onChooseDevice" />
  <!-- 本地搜索 （选择申请人、项目经理） -->
  <local-search ref="localSearchRef" @choosed="onChooseLocalSearch" />
  <!-- 选择供应商 -->
  <supplier-choose
    ref="manufacturerPopupRef"
    @confirm="onSelectedManufacturer"
  />
  <!-- 选择维修项 -->
  <repair-multiple ref="repairMultipleRef" @repair-submit="onRepairSubmit" />
  <!-- 新增维修项 -->
  <repair-add ref="addRef" @add-set="onRepairEmit"></repair-add>
  <!-- :deptId="addMateriaItem.deptId" -->
  <!-- 选择物料 -->
  <materialsChoose
    ref="materialsChooseRef"
    :deviceId="addMateriaItem.id"
    :bomNodeId="addMateriaItem.bomNodeId"
    :materialItem="addMateriaItem"
    @material-submit="materialSubmit"
  />
  <!-- 查看物料详情 -->
  <materials-view ref="materialsViewRef" />
</template>

<script setup>
import { onLoad, onReady, onBackPress } from "@dcloudio/uni-app";
import {
  reactive,
  ref,
  watch,
  computed,
  watchEffect,
  onMounted,
  onBeforeUnmount,
  nextTick,
  getCurrentInstance,
} from "vue";
import {
  getRepairDetail,
  updateRepair,
  getRepairApplicantList,
  getRepairProjectManagerList,
} from "@/api/repair.js";
import { getRandomNumber } from "@/utils/methods";
import dayjs from "dayjs";
import { uploadFile } from "@/api";

import deviceSingle from "@/components/device/single.vue";
import supplierChoose from "@/components/supplier/choose.vue";
import repairMultiple from "@/components/repair/multiple.vue";
import repairAdd from "@/components/repair/add.vue";
import materialsChoose from "@/components/materials/choose.vue";
import materialsView from "@/components/materials/view.vue";
import localSearch from "@/components/local-search.vue";

import { useDataDictStore } from "@/store/modules/dataDict";
import { reloginByUserId } from "@/utils/auth";
const { getDataDictList } = useDataDictStore();
// 引用全局变量$t
const { appContext } = getCurrentInstance();
const t = appContext.config.globalProperties.$t;

// 获取维修类型
const typeDict = getDataDictList("pms_main_type");
// 遍历typeDict，新增text字段 值为label
typeDict.forEach((item) => {
  item.text = item.label;
});
console.log("typeDict", typeDict);
// 维修类型
const typeRange = ref(typeDict);
// 是否停机
const ifStopRange = ref([
  {
    value: 1,
    text: t("operation.yes"),
  },
  {
    value: 0,
    text: t("operation.no"),
  },
]);
// 申请人
const applyPersonRange = ref([]);
// 获取申请人列表
const getApplicantList = async () => {
  // id参数创建的时候传undefined，详情的时候需要传入工单的创建人creator
  const res = await getRepairApplicantList({
    id: "",
  });
  if (res.code == 0) {
    applyPersonRange.value = res.data.map((item) => {
      return {
        value: item.oaId,
        text: item.lastname,
      };
    });
    // console.log(
    //   "🚀 ~ getApplicantList ~ applyPersonRange.value:",
    //   applyPersonRange.value
    // );
  }
};
// 维修类别列表
const maintainClassifyRange = getDataDictList("pms_maintain_classify").map(
  (item) => {
    return {
      value: item.value,
      text: item.label,
    };
  }
);
console.log("🚀 ~ maintainClassifyRange:", maintainClassifyRange);

// 项目经理
const projectManagerRange = ref([]);
// 获取项目经理列表
const getProjectManagerList = async () => {
  // id参数创建的时候传undefined，详情的时候需要传入工单的创建人creator
  const res = await getRepairProjectManagerList({
    id: "",
  });
  if (res.code !== 0) {
    uni.showToast({
      title: res.msg,
      icon: "error",
    });
    return;
  }
  projectManagerRange.value = res.data.map((item) => {
    return {
      value: item.oaId,
      text: item.lastname,
    };
  });
  // console.log(
  //   "🚀 ~ getProjectManagerList ~ projectManagerRange.value:",
  //   projectManagerRange.value
  // );
};

// 供应商选择
const manufacturerPopupRef = ref(null);
const onManufacturerChoose = () => {
  console.log(
    "🚀 ~ onManufacturerChoose ~ onManufacturerChoose:",
    onManufacturerChoose
  );
  manufacturerPopupRef.value.open("bottom");
};
// 供应商选择确认
const onSelectedManufacturer = (item) => {
  console.log("🚀 ~ onSelectedManufacturer ~ item:", item);
  maintain.value.supplier = item.name;
};

// 获取当前时间
const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
const dateMax = ref(now);

const maintainId = ref("");
const getData = () => {
  getRepairDetail({
    id: maintainId.value,
  }).then((res) => {
    console.log("getRepairDetail", res);
    res.data.ifStop = res.data.ifStop ? 1 : 0;
    const { maintainBomDOS, ...rest } = res.data;
    maintain.value = rest;

    // 判断maintain.value中是否存在pics字段，如果不存在则将pics字段转换为数组
    if (!maintain.value.pics) {
      maintain.value.pics = [];
    }
    // 判断maintain.value中是否存在outFiles字段，如果不存在则将outFiles字段转换为数组
    if (!maintain.value.outFiles) {
      maintain.value.outFiles = [];
    }
    // 判断维修类型是否为OA委外，如果是则获取申请人列表和项目经理列表
    if (maintain.value.type == "out") {
      getApplicantList();
      getProjectManagerList();
    }

    if (maintainBomDOS.length) {
      // 遍历维修项,将设备名称和设备编码添加到维修项中
      maintainBom.value = maintainBomDOS.map((bom) => {
        bom.deviceName = res.data.deviceName;
        bom.deviceCode = res.data.deviceCode;
        bom = {
          ...bom,
          workOrderBomOnlyKey: `${bom.deviceCode}_${bom.deviceName}_${bom.name}`, //手动拼接唯一标识
        };
        console.log("maintainBom.value = maintainBomDOS-bom", bom);
        // 判断是否存在物料明细
        if (bom?.materials?.length) {
          // 计算物料数量
          bom.materialCount = bom.materials.reduce((total, item) => {
            return total + item.materialCount;
          }, 0);
          bom.materialSelected = true;
          // 遍历物料明细，拼接chooseKey
          bom.materials.forEach((material) => {
            material.chooseKey = `${material.materialCode}_${material.costCenterId}_${material.factoryId}_${material.unitPrice}_${material.storageLocationId}`;
          });
        } else {
          bom = {
            ...bom,
            materialCount: 0, // 物料数量
            materials: [], // 物料明细
            materialSelected: false, //手动添加是否选择物料标识
          };
          console.log("maintainBom.value = maintainBomDOS-bom -else", bom);
        }
        return bom;
      });
    }
    console.log("maintainBom", maintainBom.value);
  });
};
onLoad(async (option) => {
  await reloginByUserId(option.reloginUserId);

  maintainId.value = option.id;
  getData();
});
onReady(() => {});
//维修工单
const maintain = ref({
  deviceId: "",
  deviceName: "",
  type: "", // 类型(是否委外 in 内部 out 外部)
  picList: [], //用于上传照片 提交时删除
  pics: [], // 用于存放上传后的照片地址 提交时使用
  outFilesList: [], // 用于上传委外相关附件 提交时删除
  outFiles: [], // 用于存放上传后的委外相关附件地址 提交时使用
});
// 选择设备
const deviceSingleRef = ref(null);
const selectedDevices = ref({});
const onAddDevice = () => {
  deviceSingleRef.value.open();
};
const onChooseDevice = (data) => {
  console.log("onChooseDevice", data);
  maintain.value.deviceId = data.id;
  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 upload = async (event) => {
  console.log("🚀 ~ upload ~ event:", event);
  console.log("🚀 ~ upload ~ event.tempFilePaths):", event.tempFilePaths);
  for (const path of event.tempFilePaths) {
    console.log("🚀 ~ upload ~ maintain.value.pics:", maintain.value);
    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 localSearchRef = ref(null);
// 打开本地搜索
const openLocalSearch = (list, propKey, title) => {
  localSearchRef.value.open({
    list,
    propKey,
    title,
    choosed: maintain.value[propKey],
  });
};
// 本地搜索确认选择
const onChooseLocalSearch = (propKey, item) => {
  console.log("🚀 ~ onChooseLocalSearch ~ propKey, item:", propKey, item);
  // 根据propKey设置maintain的值
  maintain.value[propKey] = item.value;
};

// 选择维修项
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 maintainBom = ref([]);
// 选择维修项提交
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,
        materialCount: 0, // 物料数量
        materials: [], // 物料明细
        workOrderBomOnlyKey: `${bom.deviceCode}_${bom.deviceName}_${bom.name}`, //手动拼接唯一标识
        materialSelected: false, //手动添加是否选择物料标识
      });
    }
  });
  console.log("onRepairSubmit-maintainBom", maintainBom.value);
};

// 删除维修项
const ondeleteBom = (bom) => {
  // 查找maintainBom中是否存在bom
  const index = maintainBom.value.findIndex(
    (item) => item.workOrderBomOnlyKey === bom.workOrderBomOnlyKey
  );
  if (index !== -1) {
    maintainBom.value.splice(index, 1);
  }
};
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,
    deviceId: maintain.value.deviceId,
    deviceCode: maintain.value.deviceCode,
    deviceName: maintain.value.deviceName,
    bom: maintainBom.value,
  };
  addRef.value.open(info);
};
const onRepairEmit = (data) => {
  console.log("onRepairEmit", data);
  maintainBom.value.push({
    ...data,
    materialCount: 0, // 物料数量
    materials: [], // 物料明细
    workOrderBomOnlyKey: `${data.deviceCode}_${data.deviceName}_${data.name}`, //手动拼接唯一标识
    materialSelected: false, //手动添加是否选择物料标识
  });
};

// 物料选择
const materialsChooseRef = ref(null);
const addMateriaItem = ref({});
const onMaterialChoose = (item) => {
  console.log("onMaterialChoose", item);
  addMateriaItem.value = item;
  materialsChooseRef.value.open(item);
};
// 保养工单 - 物料
const maintainMaterials = ref([]);
const materialSubmit = (material) => {
  console.log("material - submit", material);
  // 查找maintainBom.value中与addMateriaItem.value中workOrderBomOnlyKey相同的bom
  const bom = maintainBom.value.find(
    (item) => item.workOrderBomOnlyKey === material.workOrderBomOnlyKey
  );
  console.log("materialSubmit-bom", bom);
  if (bom) {
    // 若bom中的materials数组中存在与material中chooseKey相同的物料，则更新数量，否则添加物料并修改bom中的是否选择物料
    // 计算materials中所有物料的数量，并赋值给bom.materialCount
    // 计算maintainBom中所有materials数组中所有物料的费用并赋值给maintain.value.maintainFee
    // maintain.value.maintainFee保留两位小数
    const index = bom.materials.findIndex(
      (item) => item.chooseKey === material.chooseKey
    );
    if (index !== -1) {
      bom.materials[index].quantity =
        parseFloat(bom.materials[index].quantity) +
        parseFloat(material.quantity);
    } else {
      bom.materials.push({
        ...material,
        // bomNodeId: addMateriaItem.value.bomNodeId,
        // name: addMateriaItem.value.name,
        // code: addMateriaItem.value.code
      });
      // 修改是否选择物料
      bom.materialSelected = true;
    }
    // 计算materials中所有物料的数量，并赋值给bom.materialCount
    bom.materialCount = bom.materials.reduce((total, item) => {
      return parseFloat(total) + parseFloat(item.quantity);
    }, 0);
    // 计算maintainBom中所有materials数组中所有物料的费用并赋值给maintain.value.maintainFee
    maintain.value.maintainFee = maintainBom.value.reduce((total, item) => {
      return (
        total +
        item.materials.reduce((subTotal, subItem) => {
          return (
            parseFloat(subTotal) +
            parseFloat(subItem.quantity) * parseFloat(subItem.unitPrice)
          );
        }, 0)
      );
    }, 0);
    // maintain.value.maintainFee保留两位小数
    maintain.value.maintainFee = maintain.value.maintainFee.toFixed(2);
    console.log("maintain.value.maintainFee", maintain.value.maintainFee);

    console.log("materialSubmit-maintainBom", maintainBom.value);
  }
};

const materialsViewRef = ref(null);
const onMaterialView = (item) => {
  console.log("onMaterialView", item);

  uni.navigateTo({
    url: "/pages/material/view",
    success: () => {
      setTimeout(() => {
        uni.$emit("material-view", item.materials);
      }, 300); // 延迟300ms，根据实际情况调整
    },
  });
};

const repairFormRef = ref(null);
const maintainBaseRules = ref({
  // 设备名称
  deviceName: {
    rules: [
      {
        required: true,
        errorMessage: `${t("operation.PleaseSelect")}${t(
          "maintenanceWorkOrder.equipment"
        )}`,
      },
    ],
  },
  // 维修类型
  type: {
    rules: [
      {
        required: true,
        errorMessage: `${t("operation.PleaseSelect")}${t(
          "equipmentMaintenance.maintenanceType"
        )}`,
      },
    ],
  },
  // 是否停机
  ifStop: {
    rules: [
      {
        required: true,
        errorMessage: `${t("operation.PleaseSelect")}${t(
          "equipmentMaintenance.isStop"
        )}`,
      },
    ],
  },
  // 维修开始时间
  maintainStartTime: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseSelect")}${t(
          "equipmentMaintenance.maintenanceStartTime"
        )}`,
      },
      {
        validator: (rule, value, callback, source) => {
          if (source.maintainEndTime && value > source.maintainEndTime) {
            callback(new Error(`${t("general.timeNotBeLater")}`));
          } else {
            callback();
          }
        },
      },
    ],
  },
  // 维修结束时间
  maintainEndTime: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseSelect")}${t(
          "equipmentMaintenance.maintenanceEndTime"
        )}`,
      },
      {
        validator: (rule, value, callback, source) => {
          if (source.maintainStartTime && value < source.maintainStartTime) {
            callback(new Error(`${t("general.timeNotBeEarlier")}`));
          } else {
            callback();
          }
        },
      },
    ],
  },
  // 故障时间
  failureTime: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseSelect")}${t("fault.faultTime")}`,
      },
    ],
  },
  // 维修描述
  maintainDescription: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseFillIn")}${t(
          "equipmentMaintenance.description"
        )}`,
      },
    ],
  },
  // 以下是OA委外的校验规则 type = out
  // 申请人
  applyPersonId: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseSelect")}${t(
          "equipmentMaintenance.applicant"
        )}`,
      },
    ],
  },
  // 维修类别
  maintainClassify: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseSelect")}${t(
          "equipmentMaintenance.classify"
        )}`,
      },
    ],
  },
  // 规格型号
  model: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseFillIn")}${t(
          "equipmentMaintenance.specificationModel"
        )}`,
      },
    ],
  },
  // 启用日期
  enableDate: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseSelect")}${t(
          "equipmentMaintenance.enableDate"
        )}`,
      },
    ],
  },
  // 供应商
  supplier: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseFillIn")}${t(
          "equipmentMaintenance.supplier"
        )}`,
      },
    ],
  },
  // 维修费用
  maintainFee: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseFillIn")}${t(
          "equipmentMaintenance.cost"
        )}`,
      },
    ],
  },
  // 项目经理
  projectManager: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseSelect")}${t(
          "equipmentMaintenance.projectManager"
        )}`,
      },
    ],
  },
  // 维修项目
  maintenanceItem: {
    rules: [
      {
        required: false,
        errorMessage: `${t("operation.PleaseFillIn")}${t(
          "equipmentMaintenance.maintenanceItem"
        )}`,
      },
    ],
  },
});

// 动态计算校验规则
const maintainRules = computed(() => {
  const rules = JSON.parse(JSON.stringify(maintainBaseRules.value));

  // 根据维修类型动态调整规则
  if (maintain.value.type === "out") {
    // 委外维修：维修开始/结束时间可选，故障时间必填
    rules.maintainStartTime.rules[0].required = false;
    rules.maintainEndTime.rules[0].required = false;
    rules.failureTime.rules[0].required = true;
    rules.maintainDescription.rules[0].required = false;
    // oa委外：申请人、维修类别、规格型号、启用日期、供应商、维修费用、项目经理、维修项目必填
    rules.applyPersonId.rules[0].required = true;
    rules.maintainClassify.rules[0].required = true;
    rules.model.rules[0].required = true;
    rules.enableDate.rules[0].required = true;
    rules.supplier.rules[0].required = true;
    rules.maintainFee.rules[0].required = true;
    rules.projectManager.rules[0].required = true;
    rules.maintenanceItem.rules[0].required = true;
  } else {
    // 非委外维修：维修开始/结束时间必填，故障时间可选
    rules.maintainStartTime.rules[0].required = true;
    rules.maintainEndTime.rules[0].required = true;
    rules.failureTime.rules[0].required = false;
    rules.maintainDescription.rules[0].required = true;
    // 非委外：申请人、维修类别、规格型号、启用日期、供应商、维修费用、项目经理、维修项目非必填
    rules.applyPersonId.rules[0].required = false;
    rules.maintainClassify.rules[0].required = false;
    rules.model.rules[0].required = false;
    rules.enableDate.rules[0].required = false;
    rules.supplier.rules[0].required = false;
    rules.maintainFee.rules[0].required = false;
    rules.projectManager.rules[0].required = false;
    rules.maintenanceItem.rules[0].required = false;
  }

  return rules;
});

// 监听设备变化
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") {
      // 获取申请人列表
      getApplicantList();
      // 获取项目经理列表
      getProjectManagerList();
      // 委外类型下，重置规格型号（重新关联新设备的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",
        "maintainItems",
      ];
      outFields.forEach((field) => (maintain.value[field] = ""));
      // 重置委外字段校验
      nextTick(() => {
        repairFormRef.value?.clearValidate(outFields);
      });
    }

    // 重置相关字段的值和校验状态
    resetFieldsByTypeChange(newVal, oldVal);
  }
);
// 根据类型变更重置字段
const resetFieldsByTypeChange = (newType, oldType) => {
  // 如果类型没有变化或不是初始化阶段，则不执行重置
  if (newType === oldType && oldType !== undefined) return;

  // 重置时间字段
  if (
    (newType === "out" && oldType !== "out") ||
    (newType !== "out" && oldType === "out")
  ) {
    // // 重置时间字段值
    // if (newType === 'out') {
    // 	maintain.value.maintainStartTime = ''
    // 	maintain.value.maintainEndTime = ''
    // 	maintain.value.maintainDescription = ''
    // } else {
    // 	maintain.value.failureTime = ''
    // }

    // 重置表单校验状态
    nextTick(() => {
      repairFormRef.value?.clearValidate([
        "maintainStartTime",
        "maintainEndTime",
        "failureTime",
        "maintainDescription",
      ]);
    });
  }
};

/**
 * 校验时间规则（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 formSubmit = async (formEl) => {
  if (!formEl) return;
  try {
    // 1. 清除旧错误状态
    formEl.clearValidate();

    // 2. 同步最新的maintainRules（解决computed延迟）
    const latestRules = maintainRules.value;
    await nextTick(); // 等待DOM与规则同步
    formEl.setRules(latestRules);
    // 3. 执行表单基础校验（maintainRules生效）
    await formEl.validate();
    console.log("基础校验通过（maintainRules已生效）");
    // 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;
      }
      // 判断已选择的维修项是否添加物料
      for (let i = 0; i < maintainBom.value.length; i++) {
        if (maintainBom.value[i].materials.length === 0) {
          uni.showToast({
            title: `${maintainBom.value[i].deviceCode}-${
              maintainBom.value[i].name
            }${t("maintenanceWorkOrder.materialUnselected")}`,
            icon: "none",
          });
          return;
        }
      }
    }

    // 删除maintainBom.value数组中的materialSelected和workOrderBomOnlyKey
    // 并且删除maintainBom.value.material数组中的chooseKey和workOrderBomOnlyKey
    // 形成一个新数组
    const orderBom = maintainBom.value.map((item) => {
      const newItem = {
        ...item,
        ifStop: item.ifStop ? true : false,
      };
      delete newItem.materialSelected;
      delete newItem.workOrderBomOnlyKey;
      newItem.materials = newItem.materials.map((materialItem) => {
        const newMaterialItem = {
          ...materialItem,
        };
        delete newMaterialItem.chooseKey;
        delete newMaterialItem.workOrderBomOnlyKey;
        delete newMaterialItem.picList;
        return newMaterialItem;
      });
      return newItem;
    });
    console.log("orderBom", orderBom);

    // 保留两位小数

    updateRepair({
      maintain: {
        ...maintain.value,
        status: maintain.value.type == "in" ? "finished" : "tx",
      },
      maintainMaterials: orderBom,
    })
      .then((res) => {
        console.log("updateRepair-res", 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("updateRepair-err", err);
      });
  } catch (err) {
    // 8. 校验失败处理（明确错误来源）
    console.log("提交失败：", err);
    const errorMsg = err[0]?.errorMessage || t("operation.formValidateFailed");
    uni.showToast({ title: errorMsg, icon: "none" });
  }
};

onMounted(() => {
  // 监听子页面提交的事件
  console.log("onMounted");
  // uni.$on('multiple-devide-submit', (data) => {
  // 	console.log('接收到子页面数据:', data);
  // 	selectedDevices.value = data
  // 	onDeviceBomList()
  // });
});
onBeforeUnmount(() => {
  // 移除监听
  console.log("onBeforeUnmount");
  // uni.$off('multiple-devide-submit');
});
</script>

<style lang="scss" scoped>
@import "@/style/work-order-detail.scss";
</style>
