<template>
  <div>
    <!-- 基于 Element UI 新增和修改弹窗 -->
    <el-dialog
        :title="!dataForm.id ? '添加' : '修改'"
        :close-on-click-modal="false"
        :visible.sync="visible">
      <!-- 新增和修改表单 -->
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataSubmit()" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="楼栋编号" prop="buildingNo">
            <el-input v-model="dataForm.buildingNo" placeholder="楼栋编号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总层数" prop="totalFloors">
            <el-input-number v-model="dataForm.totalFloors" placeholder="总层数" :min="1" :precision="0" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单元数" prop="unitCount">
            <el-input-number v-model="dataForm.unitCount" placeholder="单元数" :min="1" :precision="0" style="width: 100%"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="楼栋类型" prop="buildingType">
            <el-select v-model="dataForm.buildingType" placeholder="请选择楼栋类型" style="width: 100%">
              <el-option
                v-for="dict in dict.type.building_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="备注" type="textarea"></el-input>
      </el-form-item>
      </el-form>

      <!-- 房屋列表 -->
      <div v-if="houseList.length > 0" class="house-list-container">
        <div class="house-list-title">房屋列表</div>
        <el-table :data="houseList" style="width: 100%">
          <el-table-column prop="unitNo" label="单元号" width="100"></el-table-column>
          <el-table-column prop="floorNo" label="楼层号" width="100"></el-table-column>
          <el-table-column prop="houseNo" label="房号" width="120"></el-table-column>
          <el-table-column prop="houseType" label="户型" width="120"></el-table-column>
          <el-table-column prop="usableArea" label="实用面积" width="100"></el-table-column>
          <el-table-column prop="propertyType" label="产权类型">
            <template slot-scope="scope">
              <dict-tag v-if="dict.type.property_type && dict.type.property_type.length > 0" :options="dict.type.property_type" :value="scope.row.propertyType"/>
              <span v-else>{{ scope.row.propertyType }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="houseStatus" label="房屋状态">
            <template slot-scope="scope">
              <dict-tag v-if="dict.type.house_status && dict.type.house_status.length > 0" :options="dict.type.house_status" :value="scope.row.houseStatus"/>
              <span v-else>{{ scope.row.houseStatus }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="propertyCertNo" label="房产证号" width="150"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="editHouse(scope.row, scope.$index)">修改</el-button>
              <el-button type="text" size="small" @click="deleteHouse([scope.row.id])">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <!-- 如果是编辑状态，显示房屋管理相关按钮 -->
        <el-button type="info" @click="addHouseHandle">新增房屋</el-button>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataSubmit()">确定</el-button>
      </span>
    </el-dialog>

    <!-- 房屋新增/修改弹窗 -->
    <PmhouseAddAndUpdate
      ref="pmhouseAddUpdate"
      :visible="houseVisible"
      :default-building-id="dataForm.id"
      :default-project-id="dataForm.projectId"
      @close="houseVisible = false"
      @refresh-data-list="refreshHouseList"
      @add-house-to-list="addHouseToList"
    />
  </div>
</template>

<script>
  import * as api from '@/api/pmbuilding.js'
  import * as houseApi from '@/api/pmhouse.js'
  import PmhouseAddAndUpdate from '../houser/pmhouse-add-and-update.vue'
  export default {
    dicts: ['project_status','building_type','property_type','house_status'],
    components: {
      PmhouseAddAndUpdate
    },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      defaultProjectId: {
        type: [String, Number],
        default: ''
      }
    },
    data () {
      return {
        dataForm: {
          id: '' ,
          projectId: '' ,
          buildingNo: '' ,
          totalFloors: '' ,
          unitCount: '' ,
          buildingType: '' ,
          remark: '' ,
        },
        // 房屋列表数据
        houseList: [],
        // 房屋新增/修改弹窗显示状态
        houseVisible: false,
        dataRule: {
          buildingNo: [
            { required: true, message: '楼栋编号  为必填项', trigger: 'blur' }
          ],
          totalFloors: [
            { required: true, message: '总层数  为必填项', trigger: 'blur' }
          ],
          unitCount: [
            { required: true, message: '单元数  为必填项', trigger: 'blur' }
          ],
          buildingType: [
            { required: true, message: '楼栋类型  为必填项', trigger: 'blur' }
          ],
          remark: [
            { required: false, message: '请输入备注', trigger: 'blur' }
          ],
        }
      }
    },
    watch: {
      // 监听默认项目ID变化，自动设置到表单中
      defaultProjectId: {
        handler (newVal) {
          if (newVal && !this.dataForm.id) {
            this.dataForm.projectId = newVal
          }
        },
        immediate: true
      },
      // 监听visible变化，当对话框关闭时重置表单
      visible (newVal) {
        if (!newVal) {
          this.$emit('close')
        }
      }
    },
    methods: {
      init (id, buildingData) { // 初始化表单验证规则
        this.$nextTick(function() {
          // 重置表单
          if (this.$refs['dataForm']) {
            this.$refs['dataForm'].resetFields()
          }

          // 初始化dataForm
          this.dataForm = {
            id: '',
            projectId: this.defaultProjectId || '',
            buildingNo: '',
            totalFloors: '',
            unitCount: '',
            buildingType: '',
            remark: ''
          }

          // 清空房屋列表
          this.houseList = []

          // 如果提供了完整的楼栋数据，直接使用（编辑模式）
          if (buildingData) {
            this.dataForm = JSON.parse(JSON.stringify(buildingData))
            // 确保项目ID正确
            if (this.defaultProjectId) {
              this.dataForm.projectId = this.defaultProjectId
            }
            // 加载房屋列表
            this.loadHouseList(this.dataForm.id)
          }
          // 如果只有id，从API加载数据（编辑模式但没有完整数据）
          else if (id) {
            this.dataForm.id = id
            api.pmbuildingDetailApi(id).then(function(res) {
              // 合并API返回的数据到dataForm
              Object.assign(this.dataForm, res)
              // 确保projectId正确
              if (this.defaultProjectId) {
                this.dataForm.projectId = this.defaultProjectId
              }
              // 加载房屋列表
              this.loadHouseList(this.dataForm.id)
            }.bind(this))
          }
        }.bind(this))
      },
      // 加载房屋列表
      loadHouseList (buildingId) {
        if (!buildingId) return

        // 调用房屋API获取该楼栋下的房屋列表
        houseApi.pmhouseListApi({ buildingId: buildingId }).then(res => {
          this.houseList = res.list || []
        }).catch(err => {
          this.$message.error('加载房屋列表失败')
          console.error(err)
        })
      },

      // 新增房屋
      addHouseHandle () {
        this.houseVisible = true
        // 重置房屋表单
        this.$nextTick(() => {
          this.$refs.pmhouseAddUpdate.init(null)
        })
      },

      // 编辑房屋
      editHouse (row, index) {
        // 打开房屋编辑弹窗
        this.houseVisible = true
        // 等待弹窗渲染完成后初始化数据
        this.$nextTick(() => {
          this.$refs.pmhouseAddUpdate.init(row.id, row)
        })
      },

      // 删除房屋
      deleteHouse (ids) {
        this.$confirm(`确定要删除${ids.length > 1 ? '这些房屋' : '该房屋'}吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          houseApi.pmhouseDeleteApi(ids).then(() => {
            this.$message.success('删除成功')
            // 重新加载房屋列表
            this.loadHouseList(this.dataForm.id)
            // 通知父组件刷新房屋列表
            this.$emit('refreshHouseList')
          }).catch(err => {
            this.$message.error('删除失败')
            console.error(err)
          })
        }).catch(() => {
          // 用户取消删除
        })
      },

      // 刷新房屋列表
      refreshHouseList () {
        // 重新加载当前楼栋的房屋列表
        this.loadHouseList(this.dataForm.id)
        // 通知父组件刷新房屋列表
        this.$emit('refreshHouseList')
      },

      // 添加房屋到列表（用于楼栋未保存时的临时存储）
      addHouseToList (houseData) {
        // 深拷贝房屋数据，避免引用问题
        const newHouse = JSON.parse(JSON.stringify(houseData))
        // 新增房屋时将id设置为null，以便后端自动生成
        newHouse.id = null
        // 添加到房屋列表
        this.houseList.push(newHouse)
      },
      // 表单数据提交
      dataSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // 深拷贝数据，避免引用问题
            const buildingData = JSON.parse(JSON.stringify(this.dataForm))
            // 确保id为字符串类型，避免类型转换问题
            if (buildingData.id === '') {
              buildingData.id = null
            }

            // 将临时保存的房屋数据添加到楼栋数据中
            buildingData.pmHouses = this.houseList.filter(house => {
              // 只包含未保存到数据库的房屋（id为null）
              return house.id === null
            })

            // 无论是新增还是编辑，都将数据传递给父组件
            this.$emit('addBuildingToList', buildingData)
            this.$message.success(buildingData.id ? '修改成功' : '添加成功')
            this.$emit('close')
          }
        })
      }
    }
  }
</script>

<style scoped>
.house-list-container {
  margin-top: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.house-list-title {
  padding: 8px 16px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-weight: bold;
  color: #303133;
}
</style>
