<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
          disabled
        />
      </el-form-item>



      <!-- 地下室层数 -->
      <el-form-item 
        label="地下室层数" 
        prop="basementCount"
        class="form-item"
 
      >
        <el-input 
          v-model="form.undergroundFloorNum" 
          placeholder="请输入地下室层数" 
          type="number"
          min="0"
          class="input-field"
          disabled
          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, onMounted, onActivated } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Close } from '@element-plus/icons-vue';
import { buildingUpdateApi } from '@/api/build';
// 表单引用
const addBuildingFormRef = ref(null);
// 提交加载状态
const submitting = ref(false);

const emit = defineEmits(['closeEditDrawer','tableDataRefresh']);

const props = defineProps(['rowData','isBuildingEditDrawer']);
watch(() => props.isBuildingEditDrawer, (newVal) => {
  if (newVal) {
    console.log('抽屉已打开，执行初始化代码');
    initFormData();
  }
});
// 表单数据
const form = reactive({
  buildCode: '',      // 建筑编号
  buildName: '',   // 建筑名称
  floorNum: null,    // 地上层数

  undergroundFloorNum: null, // 地下室层数
  description: ''      // 建筑功能描述
});

// 初始化表单数据
const initFormData = () => {
  if (!props.rowData) return;
  
  const {  ...rest } = props.rowData;
  
  // 映射状态值
  Object.assign(form, {
    ...rest,
    
  });
};


// 表单验证规则
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'] }
  ],
//   buildingFloorCount: [
//   { 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']
//   }
// ],
  // buildingBasementCount: [
  //   { required: true, message: '请输入地下室层数', trigger: ['blur', 'change'] },
  //   { 
  //     validator: (rule, value, callback) => {
  //       if (form.hasBasement === 1) {
  //         if (value === null || value === '') {
  //           callback(new Error('请输入地下室层数'));
  //         } else if (value < 0) {
  //           callback(new Error('层数不能为负数'));
  //         } else {
  //           callback();
  //         }
  //       } else {
  //         callback();
  //       }
  //     },
  //     trigger: ['blur', 'change']
  //   }
  // ]
});

// 提交表单
const handleSubmit =  () => {
  try {
    submitting.value = true;
    if (form.hasBasement === 2) { 
      rules.basementCount = [];
    }
    const {buildCode,buildId, buildName,description} = form;

    // 准备提交数据
    const submitData = {
     buildCode,buildId, buildName,description
    };
    buildingUpdateApi(submitData).then(res => { 
      if (res.code === 200) { 
       ElMessage.success('建筑信息更新成功！');
       emit('closeEditDrawer');
       emit('tableDataRefresh');
      }else{ 
       ElMessage.error('建筑信息更新响应代码错误！');
      }

    }).catch(err => { 
    })
    // console.log('提交新增建筑数据:', submitData);


    // ElMessage.success('建筑信息新增成功！');
    // // addBuildingFormRef.value.resetFields();
    // emit('closeEditDrawer');
    // emit('tableDataRefresh');
  } catch (error) {
    console.error('表单验证失败:', error);
    ElMessage.error('请完善表单信息后重试');
  } finally {
    submitting.value = false;
  }
};

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

onMounted(() => { 
  initFormData();
});
// 关闭弹窗
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;

  border-radius: 8px;


  // 标题栏样式
  .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 {

    height: 86%;
    .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>