<template>
  <div class="disaster-control-container">
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
      <template #isLoss>
        <el-radio-group v-model="ruleFormData.isLoss">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </template>
      <template #affectedRoom>
        <div class="affected-room-container">
          <el-form-item prop="buildingNo">
            <el-input v-model="ruleFormData.buildingNo" placeholder="楼号" />
          </el-form-item>
          <el-form-item prop="floorNo">
            <el-input v-model="ruleFormData.floorNo" placeholder="楼层" />
          </el-form-item>
          <el-form-item prop="roomNo">
            <el-input v-model="ruleFormData.roomNo" placeholder="房间号" />
          </el-form-item>
        </div>
      </template>
      <template #affectedImages>
        <UploadImages :maxCount="9" ref="uploadImagesRef" @uploadSuccess="handleUploadSuccess" />
      </template>
      <template #safetyLevel>
        <el-select v-model="ruleFormData.safetyLevel" placeholder="请选择影响安全评估">
          <el-option
            v-for="item in safetyLevelDice"
            :key="item.itemCode"
            :label="item.itemValue"
            :value="item.itemCode"
          />
        </el-select>
      </template>
      <template #isAffectWork>
        <el-select v-model="ruleFormData.isAffectWork" placeholder="请选择是否影响正常工作">
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </template>
      <template #lossAssessmentAmount>
        <el-input
          v-model="ruleFormData.estimatedLoss"
          placeholder="请输入损失评估金额"
          @input="handleEstimatedLossInput"
          @change="handleEstimatedLossChange"
        />
      </template>
      <template #priority>
        <el-select v-model="ruleFormData.priority" placeholder="请选择处置优先级">
          <el-option v-for="item in priorityDice" :key="item.itemCode" :label="item.itemValue" :value="item.itemCode" />
        </el-select>
      </template>
      <template #responsibleDeptId>
        <el-select v-model="ruleFormData.responsibleDeptId" placeholder="请选择整改责任部门" filterable>
          <el-option v-for="item in firstLevelDepts" :key="item.id" :label="item.deptName" :value="item.id" />
        </el-select>
      </template>
      <template #userGroupList>
        <GroupSelect v-model="ruleFormData.userGroupList" :groupOptions="groupOptions" />
      </template>
      <template #isPush>
        <el-radio-group v-model="ruleFormData.isPush">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </template>
    </BasicForm>
  </div>
</template>

<script setup lang="ts">
  import { useRoute } from 'vue-router';
  import { onMounted, ref, watch } from 'vue';
  import UploadImages from '@/components/UploadImages/UploadImages.vue';
  import BasicForm from '@/components/BasicForm.vue';
  import GroupSelect from '@/components/PersonGroup/components/GroupSelect.vue';
  import { useDisasterControlHook } from '../hook';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { useUserInfoHook, useDeptInfoHook } from '@/views/disaster/hooks';
  import { useGroupInfoHook } from '@/components/PersonGroup/hook/groupInfo';
  import type { LossReportItemFormData } from '@/types/disaster-control';
  import {
    LOSS_REPORT_ITEM_FORM_CONFIG_LOSS,
    LOSS_REPORT_ITEM_FORM_CONFIG_NO_LOSS,
    LOSS_REPORT_ITEM_FORM_DATA,
    LOSS_REPORT_ITEM_FROM_RULES,
  } from '../config';

  const { realname } = useUserInfoHook();
  const { groupOptions, getUserGroupList } = useGroupInfoHook();
  const { getFirstLevelDepts, firstLevelDepts } = useDeptInfoHook();
  const { safetyLevelDice, priorityDice, getSafetyLevelDict, getPriorityDict } = useDisasterControlHook();

  // // 处理损失评估金额输入，只允许输入数字和小数点，且小数点后最多10位
  const handleEstimatedLossInput = (value: string) => {
    // 允许数字开头、小数点结尾、小数点后最多10位数字的情况
    const regex = /^(\d+\.?|\.\d{1,10}|\d+\.\d{0,10})$/;

    // 如果是正在输入的状态（以小数点结尾），直接允许
    if (value.endsWith('.') && value.indexOf('.') === value.lastIndexOf('.')) {
      return;
    }

    if (!regex.test(value)) {
      // 尝试清理和修复输入值
      let cleanValue = value.replace(/[^\d.]/g, '');
      const dotParts = cleanValue.split('.');

      if (dotParts.length > 2) {
        // 保留第一个小数点和小数部分
        cleanValue = dotParts[0] + '.' + dotParts.slice(1).join('');
      }

      // 处理小数部分超过10位的情况
      const dotIndex = cleanValue.indexOf('.');
      if (dotIndex !== -1 && dotIndex < cleanValue.length - 11) {
        cleanValue = cleanValue.substring(0, dotIndex + 11);
      }

      if (cleanValue === '' || cleanValue === '.') {
        ruleFormData.estimatedLoss = null;
      } else {
        // 直接保存字符串形式，在提交表单时再转换为数字
        ruleFormData.estimatedLoss = cleanValue;
      }
    } else {
      // 输入合法，直接保存字符串
      ruleFormData.estimatedLoss = value;
    }
  };

  // // 处理失去焦点时，如果是小数点结尾则删除小数点
  const handleEstimatedLossChange = () => {
    // 检查当前值是否为字符串且以小数点结尾
    if (ruleFormData.estimatedLoss !== null) {
      const strValue = String(ruleFormData.estimatedLoss);
      if (strValue.endsWith('.')) {
        // 移除结尾的小数点，但仍保持为字符串
        ruleFormData.estimatedLoss = strValue.slice(0, -1);
      }
    }
  };

  const route = useRoute();
  const taskName = String(route.query.taskName);
  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<LossReportItemFormData>(
      LOSS_REPORT_ITEM_FORM_CONFIG_LOSS,
      LOSS_REPORT_ITEM_FORM_DATA,
      LOSS_REPORT_ITEM_FROM_RULES,
    );
  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const uploadImagesRef = ref<InstanceType<typeof UploadImages>>();
  const validateForm = async () => {
    if (!basicFormRef.value) return;
    const validateResult = await basicFormRef.value.validateForm();
    return validateResult;
  };
  const getFormData = () => {
    cloneRuleFormData();
    if (ruleFormData.isLoss) {
      const { createdBy, ...rest } = ruleFormData;
      return rest;
    }
    return {
      reportTaskName: ruleFormData.reportTaskName,
      isLoss: ruleFormData.isLoss,
    };
  };
  const handleUploadSuccess = (files: File[]) => {
    ruleFormData.uploadImages = files;
  };
  const initBasicFormData = () => {
    ruleFormData.reportTaskName = taskName;
    ruleFormData.createdBy = realname;
  };
  const initFormData = () => {
    uploadImagesRef.value?.removeAllImages();
    basicFormRef.value?.clearValidate();
    ruleFormData.estimatedLoss = '';
    ruleFormData.uploadImages = [];
    initBasicFormData();
    cloneRuleFormData();
  };
  defineExpose({
    validateForm,
    getFormData,
    initFormData,
  });
  onMounted(() => {
    initBasicFormData();
    getSafetyLevelDict();
    getPriorityDict();
    getFirstLevelDepts();
    getUserGroupList();
    cloneRuleFormData();
    beforeRouteLeave();
  });
  watch(
    () => ruleFormData.isLoss,
    (newVal) => {
      if (newVal) {
        ruleFormConfig.value = LOSS_REPORT_ITEM_FORM_CONFIG_LOSS;
      } else {
        ruleFormConfig.value = LOSS_REPORT_ITEM_FORM_CONFIG_NO_LOSS;
      }
    },
  );
</script>

<style scoped lang="scss">
  @use '../style/item-common.scss' as *;
</style>
