<template>
  <a-form
    :model="formState"
    name="basic"
    :label-col="{ span: 9 }"
    :wrapper-col="{ span: 15 }"
    autocomplete="off"
    :layout="formState.layout"
    @finish="onFinish"
    @finishFailed="onFinishFailed"
  >
    <!-- 科技总投入 -->
    <a-form-item
      label="近三年科技总投入"
      name="total"
      :rules="[{ required: true, message: '请输入' }]"
    >
      <a-input-number 
        v-model:value="formState.total"  
        addon-after="万元"
        @change="calculateResult" 
        style="width: 200px"
      />
    </a-form-item>

    <div class="form-layout">
      <!-- 左侧：总提取比例 -->
      <div class="left-panel">
        <a-form-item label="总提取比例" name="factor" :rules="[{ required: true, message: '请输入!' }]">
          <a-input-number 
            v-model:value="formState.factor"  
            addon-after="%" 
            @change="calculateResult" 
            :min="0"
            :max="100"
            style="width: 150px"
          />
          <div class="result-display">
            <a-tag color="processing" style="height:30px; min-width: 100px; text-align: center; margin-top: 8px;">
              {{ formState.result !== null ? formState.result.toFixed(2) : '0.00' }}万元
            </a-tag>
            <div class="result-label">风险准备金</div>
          </div>
        </a-form-item>
      </div>

      <!-- 右侧：影响因素 -->
      <div class="right-panel">
        <!-- 比例总和显示 -->
        <a-form-item label="影响因素比例总和" :wrapper-col="{ span: 18 }">
          <a-tag :color="getTotalFactorColor" style="height:30px; font-size: 14px; min-width: 100px; text-align: center;">
            {{ totalFactors }}%
          </a-tag>
          <span style="margin-left: 10px; color: #666; font-size: 12px;">
            {{ totalFactors === 100 ? '✓ 比例配置完成' : totalFactors > 100 ? '✗ 比例超限' : '请继续配置' }}
          </span>
        </a-form-item>

        <!-- 影响因素列表 -->
        <a-form-item 
          label="业务中断影响" 
          name="factor1" 
          :rules="[{ validator: validateFactor }]"
          class="factor-item"
        >
          <div class="factor-input-group">
            <a-input-number 
              v-model:value="formState.factor1"  
              addon-after="%" 
              @change="calculateResult" 
              :min="0"
              :max="getMaxFactor(1)"
              :precision="2"
              style="width: 120px"
            />
            <a-tag color="blue" style="height:30px; margin-left:12px; min-width: 90px; text-align: center;">
              {{ formState.result1 !== null ? formState.result1.toFixed(2) : '0.00' }}万元
            </a-tag>
          </div>
        </a-form-item>

        <a-form-item 
          label="客户流失影响" 
          name="factor2" 
          :rules="[{ validator: validateFactor }]"
          class="factor-item"
        >
          <div class="factor-input-group">
            <a-input-number 
              v-model:value="formState.factor2"  
              addon-after="%" 
              @change="calculateResult" 
              :min="0"
              :max="getMaxFactor(2)"
              :precision="2"
              style="width: 120px"
            />
            <a-tag color="blue" style="height:30px; margin-left:12px; min-width: 90px; text-align: center;">
              {{ formState.result2 !== null ? formState.result2.toFixed(2) : '0.00' }}万元
            </a-tag>
          </div>
        </a-form-item>

        <a-form-item 
          label="收入减少影响" 
          name="factor3" 
          :rules="[{ validator: validateFactor }]"
          class="factor-item"
        >
          <div class="factor-input-group">
            <a-input-number 
              v-model:value="formState.factor3"  
              addon-after="%" 
              @change="calculateResult" 
              :min="0"
              :max="getMaxFactor(3)"
              :precision="2"
              style="width: 120px"
            />
            <a-tag color="blue" style="height:30px; margin-left:12px; min-width: 90px; text-align: center;">
              {{ formState.result3 !== null ? formState.result3.toFixed(2) : '0.00' }}万元
            </a-tag>
          </div>
        </a-form-item>

        <a-form-item 
          label="声誉影响" 
          name="factor4" 
          :rules="[{ validator: validateFactor }]"
          class="factor-item"
        >
          <div class="factor-input-group">
            <a-input-number 
              v-model:value="formState.factor4"  
              addon-after="%" 
              @change="calculateResult" 
              :min="0"
              :max="getMaxFactor(4)"
              :precision="2"
              style="width: 120px"
            />
            <a-tag color="blue" style="height:30px; margin-left:12px; min-width: 90px; text-align: center;">
              {{ formState.result4 !== null ? formState.result4.toFixed(2) : '0.00' }}万元
            </a-tag>
          </div>
        </a-form-item>

        <a-form-item 
          label="监管影响" 
          name="factor5" 
          :rules="[{ validator: validateFactor }]"
          class="factor-item"
        >
          <div class="factor-input-group">
            <a-input-number 
              v-model:value="formState.factor5"  
              addon-after="%" 
              @change="calculateResult" 
              :min="0"
              :max="getMaxFactor(5)"
              :precision="2"
              style="width: 120px"
            />
            <a-tag color="blue" style="height:30px; margin-left:12px; min-width: 90px; text-align: center;">
              {{ formState.result5 !== null ? formState.result5.toFixed(2) : '0.00' }}万元
            </a-tag>
          </div>
        </a-form-item>
      </div>
    </div>

    <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
      <a-button 
        type="primary" 
        html-type="submit"
        :disabled="totalFactors !== 100"
      >
        计算
      </a-button>
      <a-button style="margin-left: 10px" @click="resetFactors">
        重置比例
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { reactive, computed } from 'vue';
import { message } from 'ant-design-vue';

interface FormState {
layout: 'horizontal' | 'vertical' | 'inline';
total: number | null;
factor: number | null;
result: number | null; 
result1: number | null; 
result2: number | null; 
result3: number | null; 
result4: number | null; 
result5: number | null; 
factor1: number | null; 
factor2: number | null; 
factor3: number | null; 
factor4: number | null; 
factor5: number | null; 
}

const formState = reactive<FormState>({
layout: 'horizontal',
total: null,
factor: null,
result: 0.0,
result1: 0.0,
result2: 0.0,
result3: 0.0,
result4: 0.0,
result5: 0.0,
factor1: null,
factor2: null,
factor3: null,
factor4: null,
factor5: null,
});

// 计算所有影响因素的总和
const totalFactors = computed(() => {
const factors = [
  formState.factor1 || 0,
  formState.factor2 || 0,
  formState.factor3 || 0,
  formState.factor4 || 0,
  formState.factor5 || 0
];
return factors.reduce((sum, factor) => sum + factor, 0);
});

// 根据比例总和显示不同的颜色
const getTotalFactorColor = computed(() => {
if (totalFactors.value === 100) return 'success';
if (totalFactors.value > 100) return 'error';
return 'processing';
});

// 获取每个因素的最大可输入值（防止超过100%）
const getMaxFactor = (currentIndex: number) => {
const currentFactor = formState[`factor${currentIndex}` as keyof FormState] as number || 0;
const otherFactors = [1, 2, 3, 4, 5]
  .filter(i => i !== currentIndex)
  .map(i => formState[`factor${i}` as keyof FormState] as number || 0)
  .reduce((sum, factor) => sum + factor, 0);

return Math.max(0, 100 - otherFactors);
};

// 验证单个因素
const validateFactor = () => {
if (totalFactors.value > 100) {
  return Promise.reject(new Error('所有影响因素比例之和不能超过100%'));
}
return Promise.resolve();
};

// 自动计算函数
const calculateResult = () => {
// 计算总提取比例的结果
if (formState.total !== null && formState.factor !== null) {
  formState.result = formState.total * formState.factor / 100;
} else {
  formState.result = 0;
}

// 计算各个影响因素的结果
const factors = [1, 2, 3, 4, 5];
factors.forEach(index => {
  const factorKey = `factor${index}` as keyof FormState;
  const resultKey = `result${index}` as keyof FormState;
  
  if (formState.total !== null && formState[factorKey] !== null) {
    formState[resultKey] = formState.result * (formState[factorKey] as number) / 100;
  } else {
    formState[resultKey] = 0;
  }
});

// 如果比例超过100%，显示警告
if (totalFactors.value > 100) {
  message.warning('影响因素比例总和已超过100%，请调整');
}
};

// 重置所有影响因素比例
const resetFactors = () => {
formState.factor1 = null;
formState.factor2 = null;
formState.factor3 = null;
formState.factor4 = null;
formState.factor5 = null;
calculateResult();
};

const onFinish = (values: any) => {
if (totalFactors.value !== 100) {
  message.error('请确保所有影响因素比例之和等于100%');
  return;
}
console.log('Success:', values);
message.success('计算提交成功！');
};

const onFinishFailed = (errorInfo: any) => {
console.log('Failed:', errorInfo);
message.error('表单验证失败，请检查输入');
};


</script>

<style scoped>
.form-layout {
display: flex;
gap: 40px;
margin: 20px 0;
}

.left-panel {
flex: 0 0 300px;
border-right: 1px solid #f0f0f0;
padding-right: 40px;
}

.right-panel {
flex: 1;
}

.result-display {
margin-top: 16px;
text-align: center;
}

.result-label {
margin-top: 4px;
font-size: 12px;
color: #666;
}

.factor-item {
margin-bottom: 16px;
}

.factor-input-group {
display: flex;
align-items: center;
gap: 12px; /* 使用gap属性统一控制间距 */
}

/* 为输入框和标签之间提供足够的间距 */
.factor-input-group .ant-input-number {
margin-right: 0;
}

.factor-input-group .ant-tag {
flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
.form-layout {
  flex-direction: column;
  gap: 20px;
}

.left-panel {
  border-right: none;
  border-bottom: 1px solid #f0f0f0;
  padding-right: 0;
  padding-bottom: 20px;
  flex: none;
}

.factor-input-group {
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.factor-input-group .ant-tag {
  margin-left: 0 !important;
}
}
</style>