<template>
  <div class="room-form-container" v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="small">
      <el-tabs v-model="activeTab">
        <!-- 基础信息 Tab -->
        <el-tab-pane label="基础信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="项目" prop="projectId">
                <el-select v-model="form.projectId" placeholder="请选择项目" style="width: 100%" :disabled="isEdit"
                  @change="handleProjectChange">
                  <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="楼宇" prop="buildingId">
                <el-select v-model="form.buildingId" placeholder="请选择楼宇" style="width: 100%" :disabled="isEdit"
                  @change="handleBuildingChange">
                  <el-option v-for="item in buildingOptions" :key="item.id" :label="item.buildingName"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="楼层" prop="floorId">
                <el-select v-model="form.floorId" placeholder="请选择楼层" style="width: 100%" :disabled="isEdit">
                  <el-option v-for="item in floorOptions" :key="item.id" :label="item.floorName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="房号" prop="roomNumber">
                <el-input v-model="form.roomNumber" placeholder="请输入房号" :disabled="isEdit" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="房间数字编号" prop="roomDigitalNumber">
                <el-input v-model="form.roomDigitalNumber" placeholder="请输入房间数字编号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="房源管理编号" prop="roomManageNumber">
                <el-input v-model="form.roomManageNumber" placeholder="请输入房源管理编号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="建筑面积" prop="buildingArea">
                <el-input v-model="form.buildingArea" placeholder="请输入建筑面积">
                  <template slot="append">m²</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计租面积" prop="rentalArea">
                <el-input v-model="form.rentalArea" placeholder="请输入计租面积">
                  <template slot="append">m²</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计费面积" prop="billingArea">
                <el-input v-model="form.billingArea" placeholder="请输入计费面积">
                  <template slot="append">m²</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="套内面积" prop="innerArea">
                <el-input v-model="form.innerArea" placeholder="请输入套内面积">
                  <template slot="append">m²</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="虚拟房源" prop="isVirtual">
                <el-radio-group v-model="form.isVirtual">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="房源交付时间" prop="deliveryTime">
                <el-date-picker v-model="form.deliveryTime" type="date" placeholder="请选择房源交付时间" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="绑定业主" prop="ownerId">
                <el-select v-model="form.ownerId" placeholder="请选择业主" filterable remote reserve-keyword
                  :remote-method="remoteSearchOwner" :loading="ownerLoading" style="width: 100%">
                  <el-option v-for="item in ownerOptions" :key="item.id" :label="item.ownerName" :value="item.id">
                    <span style="float: left">{{ item.ownerName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>

        </el-tab-pane>

        <!-- 招商信息 Tab -->
        <el-tab-pane label="招商信息" name="merchant">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="产权性质" prop="propertyNature">
                <el-select v-model="form.propertyNature" placeholder="请选择产权性质" style="width: 100%"
                  @change="handleInputChange">
                  <el-option label="自持" value="1" />
                  <el-option label="承租" value="2" />
                  <el-option label="自持+承租" value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="租赁状态" prop="rentalStatus">
                <el-select v-model="form.rentalStatus" placeholder="请选择租赁状态" style="width: 100%" disabled
                  @change="handleInputChange">
                  <el-option label="待租" value="1" />
                  <el-option label="已租" value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="房源状态" prop="roomStatus">
                <el-select v-model="form.roomStatus" placeholder="请选择房源状态" style="width: 100%"
                  @change="handleInputChange">
                  <el-option label="公开" value="1" />
                  <el-option label="关闭" value="2" />
                  <el-option label="私密" value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="房源类型" prop="roomType">
                <el-select v-model="form.roomType" placeholder="请选择房源类型" style="width: 100%"
                  @change="handleInputChange">
                  <el-option label="办公" value="1" />
                  <el-option label="商业" value="2" />
                  <el-option label="仓储" value="3" />
                  <el-option label="厂房" value="4" />
                  <el-option label="多经" value="5" />
                  <el-option label="公寓" value="6" />
                  <el-option label="住宅" value="7" />
                  <el-option label="其它" value="8" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="房源备案号" prop="roomRecordNumber">
                <el-input v-model="form.roomRecordNumber" placeholder="请输入房源备案号" @input="handleInputChange" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="层高" prop="height">
                <el-input v-model="form.height" placeholder="请输入层高" @input="handleInputChange">
                  <template slot="append">m</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="房源标签" prop="tagIds">
                <el-select v-model="form.tagIds" placeholder="请选择房源标签" multiple style="width: 100%"
                  @change="handleInputChange">
                  <el-option v-for="tag in tagOptions" :key="tag.id" :label="tag.tagName" :value="tag.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="招商状态" prop="businessStatus">
                <el-select v-model="form.businessStatus" placeholder="请选择招商状态" style="width: 100%"
                  @change="handleInputChange">
                  <el-option label="招商" value="1" />
                  <el-option label="不招商" value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="可租日期" prop="availableDate">
                <el-date-picker v-model="form.availableDate" type="date" placeholder="请选择可租日期" style="width: 100%"
                  @change="handleInputChange" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="装修情况" prop="decorationStatus">
              <el-select v-model="form.decorationStatus" placeholder="请选择装修情况" style="width: 100%"
                @change="handleInputChange">
                <el-option label="精装" value="1" />
                <el-option label="简装" value="2" />
                <el-option label="毛坯" value="3" />
                <el-option label="标准交付" value="4" />
                <el-option label="豪装" value="5" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="报价" prop="price">
              <el-input v-model="form.price" placeholder="请输入报价" @input="handleInputChange">
                <el-select slot="append" v-model="form.priceUnit" style="width: 100px" @change="handleInputChange">
                  <el-option label="元/㎡·天" value="1" />
                  <el-option label="元/㎡·月" value="2" />
                  <el-option label="元/月" value="3" />
                  <el-option label="元/天" value="4" />
                  <el-option label="元/年" value="5" />
                </el-select>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="底价" prop="floorPrice">
              <el-input v-model="form.floorPrice" placeholder="请输入底价" @input="handleInputChange">
                <el-select slot="append" v-model="form.floorPriceUnit" style="width: 100px" @change="handleInputChange">
                  <el-option label="元/㎡·天" value="1" />
                  <el-option label="元/㎡·月" value="2" />
                  <el-option label="元/月" value="3" />
                  <el-option label="元/天" value="4" />
                  <el-option label="元/年" value="5" />
                </el-select>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="荷载值" prop="loadValue">
              <el-input v-model="form.loadValue" placeholder="请输入荷载值" @input="handleInputChange" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="房源招商编号" prop="businessNumber">
              <el-input v-model="form.businessNumber" placeholder="请输入房源招商编号" @input="handleInputChange" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="招商条件" prop="businessCondition">
              <el-input v-model="form.businessCondition" placeholder="请输入招商条件" @input="handleInputChange" />
            </el-form-item>
          </el-col>


          </el-row>
          <el-form-item label="房源图片" prop="imageUrls">
            <el-upload :action="uploadUrl" list-type="picture-card" :headers="uploadHeaders" :file-list="imageList"
              :on-preview="handlePictureCardPreview" :on-success="handleImageSuccess" :on-remove="handleImageRemove"
              multiple>
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
        </el-tab-pane>

        <!-- 拓展信息 Tab -->
        <el-tab-pane label="拓展信息" name="extension">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="使用率" prop="usageRate">
                <el-input v-model="form.usageRate" placeholder="例如：2+1" @input="handleInputChange" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="办公格局" prop="officeLayout">
                <el-input v-model="form.officeLayout" placeholder="请输入办公格局" @input="handleInputChange" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="窗面朝向" prop="windowOrientation">
                <el-input v-model="form.windowOrientation" placeholder="例如：南" @input="handleInputChange" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="免租期" prop="rentFreePeriod">
                <el-input v-model="form.rentFreePeriod" placeholder="例如：前2个月" @input="handleInputChange" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="最短租期" prop="minLeaseTerm">
                <el-input v-model="form.minLeaseTerm" placeholder="例如：12个月" @input="handleInputChange" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="工位数量下限" prop="workstationMin">
                <el-input-number v-model="form.workstationMin" :min="0" :controls="false" placeholder="请输入最少工位数量"
                  @change="handleInputChange" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工位数量上限" prop="workstationMax">
                <el-input-number v-model="form.workstationMax" :min="0" :controls="false" placeholder="请输入最多工位数量"
                  @change="handleInputChange" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="户型图说明" prop="floorPlanDesc">
            <el-input v-model="form.floorPlanDesc" type="textarea" :rows="3" placeholder="请输入户型图说明"
              @input="handleInputChange" />
          </el-form-item>

          <el-form-item label="户型图" prop="floorPlanImageUrls">
            <el-upload :action="uploadUrl" list-type="picture-card" :headers="uploadHeaders"
              :file-list="floorPlanImageList" :on-preview="handlePictureCardPreview"
              :on-success="handleFloorPlanImageSuccess" :on-remove="handleFloorPlanImageRemove" multiple>
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>

      <div class="form-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { getRoom, addRoom, updateRoom, listProjects, listBuildings, listFloors, listRoomTags, listOwners } from '@/api/room'
import { getProjectList,getTagByType } from '@/api/project'
import { getBuildingList, getFloorList,getFloorListByBuilding} from '@/api/building'
export default {
  name: 'RoomForm',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    roomId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 当前激活的选项卡
      activeTab: 'basic',
      // 业主搜索加载中
      ownerLoading: false,
      // 对话框图片URL
      dialogImageUrl: '',
      // 图片预览对话框
      dialogVisible: false,
      // 项目选项
      projectOptions: [],
      // 楼宇选项
      buildingOptions: [],
      // 楼层选项
      floorOptions: [],
      // 标签选项
      tagOptions: [],
      // 业主选项
      ownerOptions: [],
      // 房源图片列表
      imageList: [],
      // 户型图列表
      floorPlanImageList: [],
      // 上传URL
      uploadUrl: process.env.VUE_APP_BASE_API + '/room/upload',
      // 上传请求头
      uploadHeaders: {},
      // 表单对象
      form: {
        projectId: undefined,
        buildingId: undefined,
        floorId: undefined,
        roomNumber: '',
        roomDigitalNumber: '',
        roomManageNumber: '',
        buildingArea: '',
        rentalArea: '',
        billingArea: '',
        innerArea: '',
        isVirtual: '0',
        deliveryTime: '',
        ownerId: undefined,
        propertyNature: '1',
        rentalStatus: '1',  // 默认待租
        roomStatus: '1',   // 默认公开
        roomType: '',
        roomRecordNumber: '',
        height: '',
        loadValue: '',
        tagIds: [],
        imageUrls: [],
        businessStatus: '1', // 默认招商
        availableDate: '',
        decorationStatus: '4', // 默认标准交付
        price: '',
        priceUnit: '2',  // 默认元/㎡·月
        floorPrice: '',
        floorPriceUnit: '2',  // 默认元/㎡·月
        businessNumber: '',
        businessCondition: '',
        rentFreePeriod: '',
        minLeaseTerm: '',
        usageRate: '',
        officeLayout: '',
        windowOrientation: '',
        workstationMin: null,
        workstationMax: null,
        floorPlanDesc: '',
        floorPlanImageUrls: []
      },
      // 表单校验规则
      rules: {
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        buildingId: [{ required: true, message: '请选择楼宇', trigger: 'change' }],
        floorId: [{ required: true, message: '请选择楼层', trigger: 'change' }],
        roomNumber: [{ required: true, message: '请输入房号', trigger: 'blur' }],
        roomDigitalNumber: [{ required: true, message: '请输入房间数字编号', trigger: 'blur' }],
        rentalArea: [{ required: true, message: '请输入计租面积', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getProjectOptions()
    this.getTagOptions()
    if (this.isEdit && this.roomId) {
      this.getRoomDetail()
    }
  },
  watch: {
    // 监听activeTab变化，切换tab时强制更新组件
    activeTab() {
      this.$nextTick(() => {
        // 强制更新表单，确保数据同步
        this.$forceUpdate()
      })
    }
  },
  methods: {
    /** 获取房源详情 */
    getRoomDetail() {
      this.loading = true
      getRoom(this.roomId).then(response => {
        if (response.code === '0000000000000000') {
          this.form = { ...response.data }

          // 处理业务信息字段
          if (response.data.businessInfo) {
            this.form.rentalStatus = response.data.businessInfo.rentalStatus
            this.form.businessStatus = response.data.businessInfo.businessStatus
            this.form.availableDate = response.data.businessInfo.availableDate
            this.form.decorationStatus = response.data.businessInfo.decorationStatus
            this.form.price = response.data.businessInfo.price
            this.form.priceUnit = response.data.businessInfo.priceUnit
            this.form.floorPrice = response.data.businessInfo.floorPrice
            this.form.floorPriceUnit = response.data.businessInfo.floorPriceUnit
            this.form.businessNumber = response.data.businessInfo.businessNumber
            this.form.businessCondition = response.data.businessInfo.businessCondition
          }

          // 处理扩展信息字段
          if (response.data.extendInfo) {
            this.form.roomRecordNumber = response.data.extendInfo.roomRecordNumber
            this.form.usageRate = response.data.extendInfo.usageRate
            this.form.officeLayout = response.data.extendInfo.officeLayout
            this.form.windowOrientation = response.data.extendInfo.windowOrientation
            this.form.rentFreePeriod = response.data.extendInfo.rentFreePeriod
            this.form.minLeaseTerm = response.data.extendInfo.minLeaseTerm
            this.form.workstationMin = response.data.extendInfo.workstationMin
            this.form.workstationMax = response.data.extendInfo.workstationMax
            this.form.floorPlanDesc = response.data.extendInfo.floorPlanDesc
            if (response.data.extendInfo.tags) {
              this.form.tagIds = response.data.extendInfo.tags.split(',')
            }
          }

          // 处理图片数据
          this.form.imageUrls = []
          if (response.data.roomImages && Array.isArray(response.data.roomImages) && response.data.roomImages.length > 0) {
            this.form.imageUrls = response.data.roomImages.map(item => item.imageUrl)
            this.imageList = response.data.roomImages.map((item, index) => {
              return { name: '图片' + (index + 1), url: item.imageUrl }
            })
          }

          // 处理户型图数据
          this.form.floorPlanImageUrls = []
          if (response.data.floorPlanImages && Array.isArray(response.data.floorPlanImages) && response.data.floorPlanImages.length > 0) {
            this.form.floorPlanImageUrls = response.data.floorPlanImages.map(item => item.imageUrl)
            this.floorPlanImageList = response.data.floorPlanImages.map((item, index) => {
              return { name: '户型图' + (index + 1), url: item.imageUrl }
            })
          }

          // 加载关联数据
          this.getProjectOptions().then(() => {
            if (this.form.projectId) {
              this.getBuildingOptions(this.form.projectId).then(() => {
                if (this.form.buildingId) {
                  this.getFloorOptions(this.form.buildingId)
                }
              })
            }
          })

          // 如果有业主ID，获取业主详情
          if (this.form.ownerId) {
            this.getOwnerDetail(this.form.ownerId)
          }
        } else {
          this.$message.error(response.msg || '获取房源详情失败')
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /** 获取项目选项 */
    getProjectOptions() {
      getProjectList({ pageSize: 100 }).then(res => {
        if (res.code === '0000000000000000') {
          this.projectOptions = res.data.list.map(item => {
            return { id: item.id, projectName: item.projectName }
          })
        }
      })
    },

    /** 获取楼宇选项 */
    getBuildingOptions(projectId) {
      if (!projectId) {
        this.buildingOptions = []
        this.form.buildingId = undefined
        this.floorOptions = []
        this.form.floorId = undefined
        return
      }
      const params = {
        projectId: projectId,
        pageNum: 1,
        pageSize: 100,
      }
      getBuildingList(params).then(response => {
        if (response.code === '0000000000000000') {
          this.buildingOptions = response.data.list || []
        } else {
          this.$message.error(response.msg || '获取楼宇列表失败')
        }
      })
    },

    /** 获取楼层选项 */
    getFloorOptions(buildingId) {
      if (!buildingId) {
        this.floorOptions = []
        this.form.floorId = undefined
        return
      }
      return listFloors(buildingId).then(response => {
        if (response.code === '0000000000000000') {
          this.floorOptions = response.data || []
        } else {
          this.$message.error(response.msg || '获取楼层列表失败')
        }
      })
    },

    /** 获取房源标签选项 */
    getTagOptions() {
      getTagByType({ tagType: "房源标签", tagName: "房源标签" }).then(res => {
        this.tagOptions = res.data
      }).catch(() => {
        this.tagOptions = [
          { id: '1', tagName: '标签1' },
          { id: '2', tagName: '标签2' }
        ]
      })
    },

    /** 获取业主详情 */
    getOwnerDetail(ownerId) {
      listOwners({ id: ownerId }).then(response => {
        if (response.code === '0000000000000000' && response.data && response.data.length > 0) {
          this.ownerOptions = response.data
        }
      })
    },

    /** 远程搜索业主 */
    remoteSearchOwner(query) {
      if (query) {
        this.ownerLoading = true
        listOwners({ keyword: query }).then(response => {
          this.ownerLoading = false
          if (response.code === '0000000000000000') {
            this.ownerOptions = response.data
          } else {
            this.ownerOptions = []
          }
        }).catch(() => {
          this.ownerLoading = false
        })
      } else {
        this.ownerOptions = []
      }
    },

    /** 项目选择改变事件 */
    handleProjectChange(projectId) {
      // 清空楼宇和楼层的选择
      this.form.buildingId = undefined
      this.form.floorId = undefined
      this.buildingOptions = []
      this.floorOptions = []

      if (projectId) {
        this.getBuildingOptions(projectId)
      }
    },

    /** 楼宇选择改变事件 */
    handleBuildingChange(buildingId) {
      // 清空楼层的选择
      this.form.floorId = undefined
      this.floorOptions = []


      if (buildingId) {
        getFloorListByBuilding(buildingId).then(response => {
          if (response.code === '0000000000000000') {
            this.floorOptions = response.data || []
          } else {
            this.$message.error(response.msg || '获取楼层列表失败')
          }
        })
      }
    },

    /** 图片预览 */
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    /** 房源图片上传成功 */
    handleImageSuccess(response, file, fileList) {
      if (response.code === '0000000000000000') {
        this.form.imageUrls.push(response.data.imageUrl)
        this.imageList = fileList.map(file => {
          if (file.response) {
            return { name: file.name, url: file.response.data.imageUrl }
          } else {
            return { name: file.name, url: file.url }
          }
        })
      } else {
        this.$message.error('图片上传失败')
      }
    },

    /** 房源图片删除 */
    handleImageRemove(file, fileList) {
      const url = file.url || (file.response && file.response.data.url)
      this.form.imageUrls = this.form.imageUrls.filter(item => item !== url)
      this.imageList = fileList
    },

    /** 户型图上传成功 */
    handleFloorPlanImageSuccess(response, file, fileList) {
      if (response.code === '0000000000000000') {
        this.form.floorPlanImageUrls.push(response.data.imageUrl)
        this.floorPlanImageList = fileList.map(file => {
          if (file.response) {
            return { name: file.name, url: file.response.data.imageUrl }
          } else {
            return { name: file.name, url: file.url }
          }
        })
      } else {
        this.$message.error('户型图上传失败')
      }
    },

    /** 户型图删除 */
    handleFloorPlanImageRemove(file, fileList) {
      const url = file.url || (file.response && file.response.data.url)
      this.form.floorPlanImageUrls = this.form.floorPlanImageUrls.filter(item => item !== url)
      this.floorPlanImageList = fileList
    },

    /** 提交表单 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true

          // 准备提交数据
          const formData = {
            id: this.form.id,
            projectId: this.form.projectId,
            buildingId: this.form.buildingId,
            floorId: this.form.floorId,
            roomNumber: this.form.roomNumber,
            roomDigitalNumber: this.form.roomDigitalNumber,
            roomManageNumber: this.form.roomManageNumber,
            buildingArea: this.form.buildingArea,
            rentalArea: this.form.rentalArea,
            billingArea: this.form.billingArea,
            innerArea: this.form.innerArea,
            isVirtual: this.form.isVirtual,
            deliveryTime: this.formatDate(this.form.deliveryTime),
            ownerId: this.form.ownerId,
            propertyNature: this.form.propertyNature,
            height: this.form.height,
            loadValue: this.form.loadValue,
            roomStatus: this.form.roomStatus,
            roomType: this.form.roomType,
            remark: this.form.remark,

            // 业务信息
            businessInfo: {
              rentalStatus: this.form.rentalStatus,
              businessStatus: this.form.businessStatus,
              availableDate: this.formatDate(this.form.availableDate),
              decorationStatus: this.form.decorationStatus,
              price: this.form.price,
              priceUnit: this.form.priceUnit,
              floorPrice: this.form.floorPrice,
              floorPriceUnit: this.form.floorPriceUnit,
              businessNumber: this.form.businessNumber,
              businessCondition: this.form.businessCondition
            },

            // 扩展信息
            extendInfo: {
              roomRecordNumber: this.form.roomRecordNumber,
              usageRate: this.form.usageRate,
              officeLayout: this.form.officeLayout,
              windowOrientation: this.form.windowOrientation,
              rentFreePeriod: this.form.rentFreePeriod,
              minLeaseTerm: this.form.minLeaseTerm,
              workstationMin: this.form.workstationMin,
              workstationMax: this.form.workstationMax,
              floorPlanDesc: this.form.floorPlanDesc,
              tags: this.form.tagIds ? this.form.tagIds.join(',') : ''
            },

            // 图片信息
            roomImages: this.form.imageUrls ? this.form.imageUrls.map((url, index) => {
              return {
                imageUrl: url,
                imageType: '房源图片',
                sortOrder: index
              }
            }) : [],

            // 户型图信息
            floorPlanImages: this.form.floorPlanImageUrls ? this.form.floorPlanImageUrls.map((url, index) => {
              return {
                imageUrl: url,
                imageType: '户型图',
                sortOrder: index
              }
            }) : []
          }

          const method = this.isEdit ? updateRoom : addRoom
          method(formData).then(response => {
            if (response.code === '0000000000000000') {
              this.$message.success(this.isEdit ? '修改成功' : '新增成功')
              this.$emit('refreshList')
              this.$emit('close')
            } else {
              this.$message.error(response.msg || (this.isEdit ? '修改失败' : '新增失败'))
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },

    /** 取消按钮 */
    cancel() {
      this.$emit('close')
    },

    /** 格式化日期为 YYYY-MM-DD */
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = (d.getMonth() + 1).toString().padStart(2, '0')
      const day = d.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    /** 处理输入变化 */
    handleInputChange() {
      this.$forceUpdate()
    }
  }
}
</script>

<style lang="scss" scoped>
.room-form-container {
  padding: 10px;

  .el-form {
    margin-top: 10px;
  }

  .form-footer {
    text-align: center;
    margin-top: 20px;
  }

  ::v-deep .el-form-item__label {
    width: 120px !important;
    text-align: right;
  }

  ::v-deep .el-select .el-input.is-focus .el-input__inner {
    border-color: #409EFF;
  }

  ::v-deep .el-input-group__append {
    padding: 0;

    .el-select {
      margin: 0;
    }

    .el-select .el-input__inner {
      border: none;
      background-color: #f5f7fa;
    }
  }

  ::v-deep .el-upload-list--picture-card .el-upload-list__item {
    width: 120px;
    height: 120px;
  }

  ::v-deep .el-upload--picture-card {
    width: 120px;
    height: 120px;
    line-height: 120px;
  }

  ::v-deep .el-input-number {
    width: 100%;
  }

  ::v-deep .el-input-number .el-input__inner {
    text-align: left;
  }
}
</style>