<template>
  <div class="emergency-supply-container">
    <BasicForm ref="formRef" :formData="ruleFormData" :formRules="customFormRules" :formConfig="ruleFormConfig">
      <template #requiredQuantity>
        <el-input
          v-model="ruleFormData.requiredQuantity"
          placeholder="请输入应备数量"
          @input="(value:string) => handleInputNumber(value,'require')"
          @change="handleChangeQuantity"
        />
      </template>
      <template #currentQuantity>
        <el-input
          v-model="ruleFormData.currentQuantity"
          placeholder="请输入当前数量"
          @input="(value:string) => handleInputNumber(value,'current')"
          :disabled="Boolean(!ruleFormData.requiredQuantity)"
        />
      </template>
      <template #park>
        <el-select v-model="ruleFormData.park" placeholder="请选择园区" filterable disabled>
          <el-option v-for="item in parkDice" :key="item.itemCode" :label="item.itemValue" :value="item.itemCode" />
        </el-select>
      </template>
      <template #location>
        <el-select v-model="ruleFormData.location" placeholder="请输入地点" filterable>
          <el-option v-for="item in locationDice" :key="item.itemCode" :label="item.itemValue" :value="item.itemCode" />
        </el-select>
      </template>
      <template #keeperName>
        <el-select
          v-model="ruleFormData.keeperName"
          placeholder="请输入保管人姓名"
          value-key="id"
          filterable
          remote
          :remote-method="remoteMethod"
          :loading="loading"
          @change="editKeeper"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.id"
            :label="`${item.realname}（${item.username}）${item.deptName}`"
            :value="item"
          />
        </el-select>
      </template>
    </BasicForm>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue';
  import BasicForm from '@/components/BasicForm.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { useEmergencyHook } from '@/views/emergency/src/hoos';
  import { useEmergencySuppliesHook } from '../hook';
  import type { EditEmergencyItemForm } from '@/types/emergency-supplier';
  import type { QueryUserInfoByUserNameRes } from '@/types/person-group/type';
  import { type FormRules } from 'element-plus';
  import { getEmergencySupplyDetail } from '@/api/emergency-supplier';
  import { EDIT_EMERGENCY_ITEM_FROM_CONFIG, EDIT_EMERGENCY_ITEM_DATA, EDIT_EMERGENCY_ITEM_RULES } from '../config';

  const props = defineProps<{
    id: number;
  }>();
  const formRef = ref();
  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<EditEmergencyItemForm>(
      EDIT_EMERGENCY_ITEM_FROM_CONFIG,
      EDIT_EMERGENCY_ITEM_DATA,
      EDIT_EMERGENCY_ITEM_RULES,
    );

  // 验证当前数量不大于应备数量
  const validateQuantity = (rule: any, value: any, callback: any) => {
    if (value === '' || value === null || value === undefined) {
      callback();
      return;
    }

    const currentQuantity = Number(value);
    const requiredQuantity = Number(ruleFormData.requiredQuantity);

    if (currentQuantity > requiredQuantity) {
      callback(new Error('当前数量不能大于应备数量'));
    } else {
      callback();
    }
  };

  // 扩展原有的表单规则，添加自定义验证
  const customFormRules = computed<FormRules>(() => {
    return {
      ...formRules,
      currentQuantity: [
        { required: true, message: '请输入当前数量', trigger: 'blur' },
        { validator: validateQuantity, trigger: 'blur' },
      ],
    };
  });

  const handleInputNumber = (value: string, type: 'require' | 'current') => {
    const onlyNumber = value.replace(/[^\d]/g, '');
    const num = onlyNumber === '' ? null : Number(onlyNumber);
    if (type === 'require') {
      ruleFormData.requiredQuantity = num;
    } else {
      ruleFormData.currentQuantity = num;
    }
  };

  const handleChangeQuantity = () => {
    if (ruleFormData.currentQuantity === null) return;
    formRef.value?.validateField('currentQuantity');
  };

  const { getEmergencyEventDict, getEmergencyEvent } = useEmergencyHook();
  const {
    getEmergencySupplyDict,
    getEmergencySupply,
    parkDice,
    getParkDict,
    locationDice,
    getLocationDict,
    handleChangePark,
    userOptions,
    loading,
    remoteMethod,
  } = useEmergencySuppliesHook();
  const getEmergencySupplyInfo = async () => {
    const res = await getEmergencySupplyDetail(props.id);
    for (const key in res) {
      ruleFormData[key] = res[key as keyof typeof res];
      ruleFormData.emergencyTypeName = getEmergencyEvent(res.emergencyType) || '';
      ruleFormData.supplyTypeName = getEmergencySupply(res.supplyType) || '';
    }
    getLocationDict(ruleFormData.park as 'zhangjiang_park' | 'dachang_park');
    cloneRuleFormData();
  };
  const editKeeper = (value: QueryUserInfoByUserNameRes) => {
    if (!value) return;
    ruleFormData.keeperName = value.realname;
    ruleFormData.keeperId = value.id;
  };
  const handleValidate = async () => {
    if (!formRef.value) return;
    const validateResult = await formRef.value.validateForm();
    return validateResult;
  };
  const getFormData = () => {
    cloneRuleFormData();
    return ruleFormData;
  };
  onMounted(() => {
    getEmergencyEventDict().then(async () => {
      await getEmergencySupplyDict();
      await getEmergencySupplyInfo();
    });
    getParkDict();
    beforeRouteLeave();
  });
  defineExpose({
    handleValidate,
    getFormData,
  });
</script>

<style lang="scss" scoped>
  @use '../styles/info.scss' as *;
</style>
