<template>
  <div class="add-building-modal">
    <!-- 标题栏 -->
    <div class="modal-header">
      <h2 class="title">新增建筑</h2>
      <el-icon class="close-icon" @click="handleClose" size="20">
        <Close />
      </el-icon>
    </div>

    <!-- 表单主体 -->
    <el-form 
      ref="addBuildingFormRef" 
      :model="form" 
      :rules="rules" 
      label-width="120px" 
      label-position="left"
      class="add-building-form"
      status-icon
    >
      <!-- 建筑编号 -->
      <el-form-item label="建筑编号" prop="buildCode" class="form-item">
        <el-input 
          v-model="form.buildCode" 
          placeholder="请输入建筑编号" 
          class="input-field"
          clearable
        />
      </el-form-item>

      <!-- 建筑名称 -->
      <el-form-item label="建筑名称" prop="buildName" class="form-item">
        <el-input 
          v-model="form.buildName" 
          placeholder="请输入建筑名称" 
          class="input-field"
          clearable
        />
      </el-form-item>

      <!-- 建筑层数 -->
      <el-form-item label="建筑层数(地上)" prop="floorNum" class="form-item">
        <el-input 
          v-model="form.floorNum" 
          placeholder="请输入地上层数" 
          type="number"
          min="0"
          class="input-field"
          clearable
        />
      </el-form-item>

      <!-- 是否有地下室 -->
      <el-form-item label="是否含有地下室" prop="hasBasement" class="form-item">
        <el-radio-group v-model="form.hasBasement" class="radio-group">
          <el-radio :label="1" class="radio-btn">是</el-radio>
          <el-radio :label="2" class="radio-btn">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 地下室层数 -->
      <el-form-item 
        label="地下室层数" 
        prop="undergroundFloorNum"
        class="form-item"
        :rules="form.hasBasement === 1 ? rules.basementCount : []"
      >
        <el-input 
          v-model="form.undergroundFloorNum" 
          :placeholder ="`${form.hasBasement === 1 ? '请输入地下室层数' : '无地下室'}`"
          type="number"
          min="0"
          class="input-field"
          :disabled="form.hasBasement !== 1"
          clearable
        />
      </el-form-item>

      <!-- 建筑功能描述 -->
      <el-form-item label="建筑功能描述" prop="description" class="form-item">
        <el-input 
          v-model="form.description" 
          type="textarea" 
          placeholder="请输入建筑功能描述" 
          :rows="3" 
          class="textarea-field"
          show-word-limit
          maxlength="200"
        />
      </el-form-item>
    </el-form>

    <!-- 底部按钮 -->
    <div class="modal-footer">
      <el-button @click="handleCancel" class="cancel-btn" size="default">取消</el-button>
      <el-button 
        @click="handleSubmit" 
        type="primary" 
        class="confirm-btn"
        size="default"
        :loading="submitting"
      >
        确认
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Close } from '@element-plus/icons-vue';
import { buildingAddApi } from '../../../api/build';
// 表单引用
const addBuildingFormRef = ref(null);
// 提交加载状态
const submitting = ref(false);

const emit = defineEmits(['closeAddDrawer','handleRefreshInfoFn']);

// 表单数据
const form = reactive({
  buildCode: '',      // 建筑编号
  buildName: '',   // 建筑名称
  floorNum: null,    // 地上层数
  hasBasement: 1,      // 是否含有地下室 (1:是, 2:否)
  undergroundFloorNum: null, // 地下室层数
  description: ''      // 建筑功能描述
});

// 表单验证规则
const rules = reactive({
  buildCode: [
    { required: true, message: '请输入建筑编号', trigger: ['blur', 'change'] },
    { min: 2, max: 20, message: '编号长度在2-20个字符之间', trigger: ['blur', 'change'] }
  ],
  buildName: [
    { required: true, message: '请输入建筑名称', trigger: ['blur', 'change'] },
    {  message: '名称长度在2-50个字符之间', trigger: ['blur', 'change'] }
  ],
  floorNum: [
  { required: true, message: '请输入地上层数', trigger: ['blur', 'change'] },
  { 
    validator: (rule, value, callback) => {
      if (value === null || value === '') {
        callback(new Error('请输入地上层数'));
      } else if (isNaN(value)) {
        callback(new Error('请输入有效数字'));
      } else if (value < 0) {
        callback(new Error('层数不能为负数'));
      } else {
        callback();
      }
    },
    trigger: ['blur', 'change']
  }
]
});

// 提交表单
const handleSubmit =  () => {
  try {
    submitting.value = true;
    if (form.hasBasement === 2) { 
      rules.basementCount = [];
    }
    // 准备提交数据
    const submitData = {
      ...form,
      undergroundFloorNum:form.hasBasement === 1 ? form.undergroundFloorNum : 0
    };

    console.log('提交新增建筑数据:', submitData);
    buildingAddApi(submitData).then(res => {
      if (res.code === 200) { 
       ElMessage.success('建筑信息新增成功！');
       addBuildingFormRef.value.resetFields();
       emit('closeAddDrawer');
       emit('tableDataRefresh');
      }else{ 
       ElMessage.error('建筑信息新增响应代码错误！');
      }
       
    }).catch(err => { 
      ElMessage.error('添加建筑错误',err);
    });
  } catch (error) {
    console.error('表单验证失败:', error);
    // ElMessage.error('请完善表单信息后重试');
  } finally {
    submitting.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消新增吗？已填写内容将不保存', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',  
    type: 'warning',
    center: true
  }).then(() => {
    emit('closeAddDrawer');
    addBuildingFormRef.value.resetFields();
    
  }).catch(() => {});
};

// 关闭弹窗
const handleClose = () => {
  addBuildingFormRef.value.resetFields();
  handleCancel();
};
</script>

<style scoped lang="scss">
.add-building-modal {
  width: 100%;
  max-width: 520px;
  padding: 15px;
  box-sizing: border-box;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

  // 标题栏样式
  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    .title {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }

    .close-icon {
      cursor: pointer;
      color: #909399;
      transition: all 0.2s;
      padding: 4px;
      border-radius: 50%;

      &:hover {
        color: #f56c6c;
        background-color: #fef0f0;
      }
    }
  }

  // 表单样式
  .add-building-form {
  
    .form-item {
      margin-bottom: 18px;
      
      :deep(.el-form-item__label) {
        color: #606266;
        font-weight: normal;
      }
    }

    .input-field, .textarea-field {
      width: 100%;
      max-width: 380px;
      
      :deep(.el-input__inner) {
        height: 36px;
        line-height: 36px;
        border-radius: 4px;
      }
      
      :deep(.el-textarea__inner) {
        min-height: 100px !important;
        border-radius: 4px;
      }
    }

    // 单选框样式
    .radio-group {
      display: flex;
      gap: 20px;
      
      .radio-btn {
        margin: 0;
        
        :deep(.el-radio__label) {
          padding-left: 6px;
          font-size: 14px;
        }
      }
    }
  }

  // 底部按钮样式
  .modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 16px;
    margin-top: 24px;
    padding-top: 20px;
    border-top: 1px solid #f0f0f0;

    .cancel-btn {
      width: 90px;
      height: 36px;
      border-radius: 4px;
      color: #606266;
      border-color: #dcdfe6;
      
      &:hover {
        color: #409eff;
        border-color: #c6e2ff;
        background-color: #ecf5ff;
      }
    }
    
    .confirm-btn {
      width: 90px;
      height: 36px;
      border-radius: 4px;
      background-color: #409eff;
      border-color: #409eff;
      
      &:hover {
        background-color: #66b1ff;
        border-color: #66b1ff;
      }
      
      &:active {
        background-color: #3a8ee6;
        border-color: #3a8ee6;
      }
    }
  }

  // 响应式适配
  @media (max-width: 768px) {
    padding: 16px;
    max-width: 100%;

    .add-building-form {
      .input-field, .textarea-field {
        max-width: 100% !important;
      }
      
      .radio-group {
        gap: 16px;
      }
    }
    
    .modal-footer {
      justify-content: center;
      gap: 12px;
    }
  }
}
</style>