<template>
  <scroll-view scroll-y="true" class="work-order-form">
    <view class="form-content">
      <uni-forms
        ref="repairFormRef"
        labelWidth="140px"
        :modelValue="formData"
        :rules="formDataRules"
        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"
            :styles="{ disableColor: '#fff' }"
            :placeholder="selectPlaceholder"
            v-model="formData.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="formData.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="formData.ifStop"
            :localdata="ifStopRange"
          >
          </uni-data-select>
        </uni-forms-item>

        <!-- 维修开始时间 维修类型是委外时不必填-->
        <uni-forms-item
          class="form-item"
          :label="$t('equipmentMaintenance.maintenanceStartTime')"
          name="maintainStartTime"
          :required="formData.type == 'out' ? false : true"
        >
          <!-- :end="dateMax" -->
          <uni-datetime-picker
            type="datetime"
            :border="false"
            returnType="timestamp"
            :placeholder="selectPlaceholder"
            :style="{
              color: formData.maintainStartTime ? '#333' : '#999',
              'font-size': formData.maintainStartTime
                ? '14px !important'
                : 'inherit !important',
            }"
            v-model="formData.maintainStartTime"
          >
          </uni-datetime-picker>
        </uni-forms-item>
        <!-- return-type="timestamp" -->
        <!-- 维修结束时间 维修类型是委外时不必填-->
        <uni-forms-item
          class="form-item"
          :label="$t('equipmentMaintenance.maintenanceEndTime')"
          name="maintainEndTime"
          :required="formData.type == 'out' ? false : true"
        >
          <!-- :end="dateMax" -->
          <uni-datetime-picker
            type="datetime"
            :border="false"
            returnType="timestamp"
            :placeholder="selectPlaceholder"
            :style="{
              color: formData.maintainEndTime ? '#333' : '#999',
              'font-size': formData.maintainEndTime
                ? '14px !important'
                : 'inherit !important',
            }"
            v-model="formData.maintainEndTime"
          >
          </uni-datetime-picker>
        </uni-forms-item>
        <!-- 故障时间 维修类型是委外时必填-->
        <uni-forms-item
          class="form-item"
          :label="$t('fault.faultTime')"
          name="failureTime"
          :required="formData.type == 'out' ? true : false"
        >
          <!-- :end="dateMax" -->
          <uni-datetime-picker
            type="datetime"
            :border="false"
            returnType="timestamp"
            :placeholder="selectPlaceholder"
            :style="{
              color: formData.failureTime ? '#333' : '#999',
              'font-size': formData.failureTime
                ? '14px !important'
                : 'inherit !important',
            }"
            v-model="formData.failureTime"
          >
          </uni-datetime-picker>
        </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="formData.failureInfluence"
            :placeholder="fillInPlaceholder"
          />
        </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="formData.failureSystem"
            :placeholder="fillInPlaceholder"
          />
        </uni-forms-item>
        <!-- 维修费用 维修类型=in 时展示 -->
        <uni-forms-item
          class="form-item"
          :label="$t('equipmentMaintenance.cost')"
          name="maintainFee"
          :required="false"
          v-if="formData.type == 'in'"
        >
          <uni-easyinput
            type="digit"
            style="text-align: right"
            :inputBorder="false"
            :clearable="true"
            :styles="{ disableColor: '#fff' }"
            v-model="formData.maintainFee"
            :disabled="formData.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="formData.picList"
            @select="uploadImg"
            @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="formData.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="formData.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="formData.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="formData.kmHour"
              :placeholder="fillInPlaceholder"
            />
          </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="formData.model"
              :placeholder="fillInPlaceholder"
            />
          </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="selectPlaceholder"
              :style="{
                color: formData.enableDate ? '#333' : '#999',
                'font-size': formData.enableDate
                  ? '14px !important'
                  : 'inherit !important',
              }"
              v-model="formData.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="formData.supplier"
              :placeholder="fillInPlaceholder"
            >
              <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
              type="digit"
              style="text-align: right"
              :inputBorder="false"
              :clearable="true"
              :styles="{ disableColor: '#fff' }"
              v-model="formData.maintainFee"
              :placeholder="fillInPlaceholder"
              :disabled="formData.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="formData.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="formData.address"
              :placeholder="fillInPlaceholder"
            />
          </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="formData.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="formData.maintainItem"
              :placeholder="fillInPlaceholder"
            />
          </uni-forms-item>
        </template>
        <!-- ----------------------------------- OA委外 end ------------------------  -->
        <!-- 故障描述 -->
        <uni-forms-item
          class="form-item"
          :label="$t('fault.description')"
          :required="true"
          name="description"
        >
          <uni-easyinput
            style="text-align: right"
            type="textarea"
            :autoHeight="true"
            :inputBorder="false"
            :clearable="true"
            :styles="{ disableColor: '#fff' }"
            v-model="formData.description"
            :placeholder="fillInPlaceholder"
          />
        </uni-forms-item>
        <!-- 维修描述 维修类型是委外时不必填-->
        <uni-forms-item
          class="form-item"
          :label="$t('equipmentMaintenance.description')"
          :required="formData.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="formData.maintainDescription"
            :placeholder="fillInPlaceholder"
          />
        </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="formData.solution"
            :placeholder="fillInPlaceholder"
          />
        </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="formData.remark"
            :placeholder="fillInPlaceholder"
          />
        </uni-forms-item>
      </uni-forms>
    </view>
  </scroll-view>
  <!-- 选择设备 -->
  <device-single ref="deviceSingleRef" @devide-submit="onChooseDevice" />
  <!-- 本地搜索 （选择申请人、项目经理） -->
  <local-search ref="localSearchRef" @choosed="onChooseLocalSearch" />
  <!-- 选择供应商 -->
  <supplier-choose
    ref="manufacturerPopupRef"
    @confirm="onSelectedManufacturer"
  />
</template>

<script setup>
import { onLoad, onReady, onBackPress } from "@dcloudio/uni-app";
import { ref, reactive, computed, getCurrentInstance, onMounted ,nextTick} from "vue";
import dayjs from "dayjs";

// -------------------------- 引入api接口 start--------------------------
import {
  createRepair,
  getRepairApplicantList,
  getRepairProjectManagerList,
} from "@/api/repair.js";
// -------------------------- 引入api接口 end  --------------------------
// --------------------------引用组件-----start---------------------------
import supplierChoose from "@/components/supplier/choose.vue";
import deviceSingle from "@/components/device/single.vue";
import localSearch from "@/components/local-search.vue";
// --------------------------引用组件-----end-----------------------------
// --------------------------引用全局变量$t-------------------------------
const { appContext } = getCurrentInstance();
const t = appContext.config.globalProperties.$t;
// --------------------------引用字典项-----------------------------------
import { useDataDictStore } from "@/store/modules/dataDict";
const { getIntDictOptions, getStrDictOptions } = useDataDictStore();

// -------------------------接收父组件传递的参数---------------------------
const props = defineProps({
  formData: {
    type: Object,
    default: () => {},
  },
  formDisabled: {
    type: Boolean,
    default: false,
  },
});

// -------------------------- 表单需要的数据 --------------------------
// 获取当前时间
const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
// 最大时间为当前时间
const dateMax = ref(now);

// 根据formDisabled动态返回表单placeholder - 填写
const fillInPlaceholder = computed(() => {
  return props.formDisabled ? " " : t("operation.PleaseFillIn");
});
// 根据formDisabled动态返回表单placeholder - 选择
const selectPlaceholder = computed(() => {
  return props.formDisabled ? " " : t("operation.PleaseSelect");
});
// 根据formDisabled动态返回表单required
const formItemRequired = computed(() => {
  return props.formDisabled ? false : true;
});

// --------------------------------------------------------------------
// 维修类型
const typeRange = getStrDictOptions("pms_main_type").map((item) => {
  return {
    ...item,
    text: item.label,
  };
});
console.log("🚀 ~ typeRange:", typeRange);
// 是否停机
const ifStopRange = getIntDictOptions("pms_boolean").map((item) => {
  return {
    ...item,
    text: item.label,
  };
});
// 维修类别
const maintainClassifyRange = getStrDictOptions("pms_maintain_classify").map(
  (item) => {
    return {
      ...item,
      text: item.label,
    };
  }
);
// 申请人
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 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);
  emit("chooseManufacturer", item);
};
// 本地搜索
const localSearchRef = ref(null);
// 打开本地搜索
const openLocalSearch = (list, propKey, title) => {
  localSearchRef.value.open({
    list,
    propKey,
    title,
    choosed: props.formData[propKey],
  });
};
// 本地搜索确认选择
const onChooseLocalSearch = (propKey, item) => {
  console.log("🚀 ~ onChooseLocalSearch ~ propKey, item:", propKey, item);
  emit("chooseLocalSearch", propKey, item);
};
// --------------------------------------------------------------------------
// 选择设备
const deviceSingleRef = ref(null);

const onAddDevice = () => {
  deviceSingleRef.value.open();
};
const onChooseDevice = (data) => {
  console.log("onChooseDevice", data);
  // if (data.hasSetMaintenanceBom === false) {
  //   uni.showToast({
  //     title: t("equipmentMaintenance.noMaintenanceItems"),
  //     icon: "none",
  //   });
  //   return;
  // }
  emit("chooseDevice", data);
};
// 上传图片
const uploadImg = (event) => {
  emit("uploadImg", event);
};
// 删除图片
const deleteImg = (event) => {
  emit("deleteImg", event);
};
// 上传委外相关附件
const uploadOutFiles = (event) => {
  emit("uploadOutFiles", event);
};
// 删除委外相关附件
const deleteOutFiles = (event) => {
  emit("deleteOutFiles", event);
};

// --------------------------------------------------------------------------
// 表单实例
const repairFormRef = ref(null);
// 表单校验规则
const formDataBaseRules = 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")}`,
      },
    ],
  },
  // 故障描述
  description: {
    rules:[
      {
        required: true,
        errorMessage: `${t("operation.PleaseFillIn")}${t(
          "fault.description"
        )}`,
      },
    ]
  },
  // 维修描述
  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 formDataRules = computed(() => {
  const rules = JSON.parse(JSON.stringify(formDataBaseRules.value));

  // 根据维修类型动态调整规则
  if (props.formData.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;
});

// 表单校验方法
const validate = async () => {
  // 同步最新的formDataRules（解决computed延迟）
  const latestRules = formDataRules.value;
  await nextTick(); // 等待DOM与规则同步
  repairFormRef.value.setRules(latestRules);
  console.log("基础校验通过（formDataRules已生效）");
  // 调用uni-forms的validate方法进行校验
  return await repairFormRef.value.validate();
};

// -------------------------- 生命周期函数 --------------------------
onMounted(() => {
  // 初始化获取申请人列表
  getApplicantList();
  // 初始化获取项目经理列表
  getProjectManagerList();
});

// -------------------------- 暴露给父组件的外部方法 --------------------------
defineExpose({
  validate,
});
// -------------------------- 事件派发 --------------------------
const emit = defineEmits([
  "chooseDevice",
  "chooseLocalSearch",
  "chooseManufacturer",
  "uploadImg",
  "deleteImg",
  "uploadOutFiles",
  "deleteOutFiles",
]);
</script>

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