<template>
  <div class="add-building-modal">
    <!-- 标题栏 -->
    <div class="modal-header">
      <h2 class="title">{{form.isEdit ?"修改建筑信息": "新增建筑信息" }} </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="buildingStye"  class="form-item">
         <el-radio-group :disabled="form.isEdit" v-model="form.floorSort" @change="changeBuildinGradioGroup" class="radio-group">
            <el-radio :value="1">地上</el-radio>
            <el-radio :value="0">地下</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 建筑名称 -->
      <el-form-item label="楼层号" prop="floorNo" class="form-item">
        <el-input v-model="form.floorNo" placeholder="楼层号" disabled style="width: 240px"></el-input>
      </el-form-item>

      <!-- 建筑层数 -->
      <el-form-item label="楼层平面图" prop="floorPlan" class="form-item">
        <!-- 上传图片 -->
          <UpdataImg ref="floorUpdateloader" @getAvatar="getfloorPlan" :updataImageCount="1"></UpdataImg>
      </el-form-item>

      <!-- 是否有地下室 -->
      <el-form-item label="航线绑定" prop="pathBinding" class="form-item">
        <el-select v-model="form.airline" placeholder="选择可绑定的航线" style="width: 240px">
            <el-option
                v-for="item in form.airline"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
        </el-select>
      </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, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Close } from '@element-plus/icons-vue';
import UpdataImg from '../../systemmanage/components/updataImg.vue';
import { floorGetUpFloorSortAPI,floorGetDownFloorSortAPI,floorAddInfoAPI,floorUpdateAPI } from '@/api/floor.js';
import { message } from 'ant-design-vue';
import { useRoute,useRouter } from 'vue-router';
import useAppStore from '../../../store/module/app';

const useAppStoreInstance = useAppStore();
const route = useRoute();
const props = defineProps(['rowData','isBuildingEditDrawer']);
const emit = defineEmits(['closeAddDrawer','tableDataRefresh']);

// 表单引用
const addBuildingFormRef = ref(null);
// 提交加载状态
const submitting = ref(false);

// 表单数据
const form = reactive({
  floorSort: '',
//   楼层编号初始的时候要获取，数据类型 buildingNo：{label: '1层', value: '1'}
  floorNo:'',
  //   航线编号初始的时候要获取，数据类型floorPlan：{label: '航线1', value: '1'}
  floorPlan:'',
  airline:'',
  description:'',
  isEdit:false,
  floorId:'',
  

});

const changeBuildinGradioGroup = () => {
  console.log("改变了值", form.floorSort,useAppStoreInstance.PUSHPARAMETER);
  try {
    if (form.floorSort === 1) {
      // 获取楼层编号
      floorGetUpFloorSortAPI({buildId:useAppStoreInstance.PUSHPARAMETER.buildId}).then((res) => {
        console.log("获取楼层编号", res);
        form.floorNo = res.data+'层';

      })
    } else if (form.floorSort === 0) {
      floorGetDownFloorSortAPI({buildId:useAppStoreInstance.PUSHPARAMETER.buildId}).then((res) => {
        console.log("获取dixa楼层编号", res);
        form.floorNo = extractAndFormatNumber(''+ res.data)+'层';

      })

    } else  {
      message.error('参数传递失败',form.floorSort)
    }
  
  } catch (error) {
    console.log("自动获取新增序号失败", error);
  }
  // form.buildingStye = val;
};
const getfloorPlan = (url) => {
  console.log(url,"const url = URL.createObjectURL(url);");
    
  form.floorPlan = url;
};
// 表单验证规则
const rules = reactive({
  

 
});

function getFloorNumberFromDisplay(floorStr) {
  console.log(floorStr,"floorStr");
  // 如果是B1、B2等地下室楼层，转换为负数
  if (floorStr.startsWith('B')) {
    const floorNumber = parseInt(floorStr.substring(1));
    return 'B'+floorNumber;
  }
  // 如果是普通楼层（如1、2、13等），直接转换为数字
  else {
    return parseInt(floorStr);
  }
}

function extractAndFormatNumber(str) {
  // 使用正则表达式匹配数字（包括负号）
  const match = str.match(/-?\d+/);
  // console.log(parseInt( match[0]), "match");
  if (parseInt( match[0])<0) {
      if (match) {
      // 获取匹配到的数字（包括负号）
      const number = match[0];
      // 去掉负号，加上"B"前缀
      return "B" + Math.abs(parseInt(number));
    }
    
    // 如果没有匹配到数字，返回默认值
    return "B0";
  }else{
    console.log( "match大于0");
    return parseInt( match[0])
  }
  
}

function convertFloorToNumber(floorStr) {
  // 检查 floorStr 是否为 null 或 undefined
  if (floorStr == null) {
    console.warn("convertFloorToNumber: floorStr is null or undefined");
    return 0; // 或者返回其他默认值
  }
  // 确保 floorStr 是字符串类型
  floorStr = String(floorStr).trim();
  // 如果是 B1、B2 等地下室楼层，转换为负数
  if (floorStr.startsWith('B')) {
    const floorNumber = parseInt(floorStr.substring(1)) || 0;
    return -floorNumber;
  }
  // 如果是普通楼层（如 1、2、13 等），直接转换为数字
  else {
    return parseInt(floorStr) || 0;
  }
}
// 提交表单
const handleSubmit =  () => {
  try {
    submitting.value = true;
    const {airline,description,floorNo,floorPlan,floorId} = form;
    console.log("提交参数",airline,description,floorNo,floorPlan);
    // 准备提交数据
   

   
    if (!form.isEdit) {
       const submitData = {
          airline,description,floorNo:getFloorNumberFromDisplay(floorNo),floorPlan,
          floorSort:convertFloorToNumber(floorNo),
          buildId:useAppStoreInstance.PUSHPARAMETER.buildId
        };
         console.log('提交新增建筑数据:', submitData);
        floorAddInfoAPI(submitData).then(res => {
          console.log('新增建筑数据返回结果:', res);
          if (res.code === 200) {
            // ElMessage.success('建筑信息新增成功！');
            emit('tableDataRefresh');
            emit('closeAddDrawer');
            addBuildingFormRef.value.resetFields();
            floorUpdateloader.value.handleRemove()
          }
        }).catch(err => { 
            ElMessage.error('添加建筑错误',err);
          });
    }else { 
      console.log(emit, 'props.rowData');
      const submitData = {
          airline,description,floorNo:getFloorNumberFromDisplay(floorNo),floorPlan,
          floorId
        };
         console.log('修改提交建筑数据:', submitData);
        floorUpdateAPI(submitData).then(res => {
          console.log('新增建筑数据返回结果:', res);
          if (res.code === 200) {
            ElMessage.success('建筑信息修改成功！');
            emit('tableDataRefresh');
            emit('closeAddDrawer');
            addBuildingFormRef.value.resetFields();
            floorUpdateloader.value.handleRemove()
          }
        }).catch(err => { 
          ElMessage.error('修改建筑错误',err);
        });
    }
    
    
    
  } catch (error) {
    console.error('表单验证失败:', error);
    ElMessage.error('请完善表单信息后重试',error);
  } finally {
    submitting.value = false;
  }
};
const floorUpdateloader = ref(null);
// 取消操作
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消新增吗？已填写内容将不保存', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',  
    type: 'warning',
    center: true
  }).then(() => {
    console.log('取消新增');
    addBuildingFormRef.value.resetFields();
    floorUpdateloader.value.handleRemove()
    emit('closeAddDrawer');
    
  }).catch((err) => {
    console.log('报错了12',err);
  });
};

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


const initFormData = () => { 
  console.log("初始化表单数据",props.rowData);
  if (props.rowData) {
    form.floorSort = props.rowData.floorSort>0 ?1: 0; // 如果 rowData.floorSort 是 null/undefined，则使用默认值 0
    form.floorNo = props.rowData.floorNo ?? '';
    form.floorPlan = props.rowData.floorPlan === null ? ' ' : props.rowData.floorPlan ?? '';
    form.airline = props.rowData.airline ?? '';
    form.description = props.rowData.description === null ? ' 暂无描述 ' : props.rowData.description ?? '';
    form.isEdit = props.rowData.isEdit ?? false;
    form.floorId = props.rowData.floorId ;
  console.log('准备提交数据:',form); 
  }
  
};


// 监听变化
watch(() => props.isBuildingEditDrawer, (newVal, oldVal) => {
  console.log('抽屉已打开，监听变化');
  initFormData()
}, { immediate: true });

</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>