<template>
  <div>
    <div style="margin-bottom: 10px;">
      <el-button type="primary" size="small" @click="addBuilding">新增楼栋</el-button>
    </div>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      :row-key="'id'"
      style="width: 100%;">
      <el-table-column
        prop="buildingNo"
        header-align="center"
        align="center"
        label="楼栋编号"
        width="120">
      </el-table-column>
      <el-table-column
        prop="totalFloors"
        header-align="center"
        align="center"
        label="总层数"
        width="100">
      </el-table-column>
      <el-table-column
        prop="unitCount"
        header-align="center"
        align="center"
        label="单元数"
        width="100">
      </el-table-column>
      <el-table-column
        prop="buildingType"
        header-align="center"
        align="center"
        label="楼栋类型">
        <template slot-scope="scope">
          <dict-tag v-if="dict.type.building_type && dict.type.building_type.length > 0" :options="dict.type.building_type" :value="scope.row.buildingType"/>
          <span v-else>{{ scope.row.buildingType }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        header-align="center"
        align="center"
        label="备注">
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="180"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="editBuilding(scope.row.id)">{{ '修改' }}</el-button>
          <el-button type="text" size="small" @click="viewHouses(scope.row.id, scope.row.buildingNo)">{{ '查看房屋' }}</el-button>
          <el-button type="text" size="small" @click="deleteBuilding(scope.row.id)" style="color: #f56c6c;">{{ '删除' }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="showSearch"
      hide-on-single-page
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 房屋管理弹窗 -->
    <el-dialog
      :title="'房屋管理 - ' + selectedBuildingNo"
      :close-on-click-modal="false"
      :visible.sync="houseDialogVisible"
      width="80%"
      :append-to-body="true"
      :before-close="handleHouseDialogClose">
      <div>
        <div style="margin-bottom: 10px;">
          <el-button type="primary" size="small" @click="addHouse">新增房屋</el-button>
        </div>
        <el-table
          :data="houseDataList"
          border
          v-loading="houseDataListLoading"
          :row-key="'id'"
          style="width: 100%;">
          <el-table-column
            prop="unitNo"
            header-align="center"
            align="center"
            label="单元号"
            width="100">
          </el-table-column>
          <el-table-column
            prop="floorNo"
            header-align="center"
            align="center"
            label="楼层号"
            width="100">
          </el-table-column>
          <el-table-column
            prop="houseNo"
            header-align="center"
            align="center"
            label="房号"
            width="120">
          </el-table-column>
          <el-table-column
            prop="houseType"
            header-align="center"
            align="center"
            label="户型"
            width="120">
          </el-table-column>
          <el-table-column
            prop="usableArea"
            header-align="center"
            align="center"
            label="实用面积"
            width="100">
          </el-table-column>
          <el-table-column
            prop="propertyType"
            header-align="center"
            align="center"
            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"
            header-align="center"
            align="center"
            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"
            header-align="center"
            align="center"
            label="房产证号"
            width="150">
          </el-table-column>
          <el-table-column
            prop="remark"
            header-align="center"
            align="center"
            label="备注">
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="150"
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="editHouse(scope.row.id)">{{ '修改' }}</el-button>
              <el-button type="text" size="small" @click="deleteHouse(scope.row.id)" style="color: #f56c6c;">{{ '删除' }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="showSearch"
          hide-on-single-page
          @size-change="houseSizeChangeHandle"
          @current-change="houseCurrentChangeHandle"
          :current-page="housePageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="housePageSize"
          :total="houseTotalPage"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>
      <!-- 房屋表单弹窗, 新增数据和修改数据 -->
      <PmhouseAddOrUpdate
        ref="pmhouseAddOrUpdate"
        :visible="houseFormVisible"
        :defaultBuildingId="selectedBuildingId"
        @close="houseFormVisible = false"
        @refreshDataList="getHouseDataList"
      ></PmhouseAddOrUpdate>
    </el-dialog>
    <!-- 楼栋管理弹窗 -->
    <PmbuildingAddOrUpdate
      ref="pmbuildingAddOrUpdate"
      :visible="buildingFormVisible"
      :defaultProjectId="projectId"
      @close="buildingFormVisible = false"
      @refreshDataList="getDataList"
    ></PmbuildingAddOrUpdate>
  </div>
</template>

<script>
  import * as api from '@/api/pmbuilding.js'
  import * as houseApi from '@/api/pmhouse.js'
  import PmhouseAddOrUpdate from '../houser/pmhouse-add-and-update.vue'
  import PmbuildingAddOrUpdate from '../building/pmbuilding-add-and-update.vue'
  export default {
    components: {
      PmhouseAddOrUpdate,
      PmbuildingAddOrUpdate
    },
    dicts: ['building_type', 'property_type', 'house_status'],
    props: {
      projectId: {
        type: [String, Number],
        default: ''
      }
    },
    data () {
      return {
        showSearch: true,
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataForm: {
          buildingNo: '',
          buildingType: ''
        },
        addOrUpdateVisible: false,
        buildingVisible: false,
        // 房屋管理相关
        houseDialogVisible: false,
        selectedBuildingId: null,
        selectedBuildingNo: '',
        houseDataList: [],
        housePageIndex: 1,
        housePageSize: 10,
        houseTotalPage: 0,
        houseDataListLoading: false,
        houseFormVisible: false,
        // 楼栋管理相关
        buildingFormVisible: false
      }
    },
    mounted () {
      this.getDataList()
    },
    methods: {
      getDataList () {
        this.dataListLoading = true
        const params = {
          page: this.pageIndex,
          limit: this.pageSize,
          projectId: this.projectId
        }
        api.pmbuildingListApi(params).then(res => {
          this.dataListLoading = false
          this.dataList = res.list || []
          this.totalPage = res.count || 0
          // 如果房屋管理弹窗是打开的，重新加载房屋列表数据
          if (this.houseDialogVisible && this.selectedBuildingId) {
            this.getHouseDataList()
          }
        }).catch(e => {
          this.dataListLoading = false
        })
      },
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      addBuilding () {
        this.buildingFormVisible = true
        if (this.$refs.pmbuildingAddOrUpdate) {
          this.$refs.pmbuildingAddOrUpdate.init(0)
        }
      },
      editBuilding (id) {
        this.buildingFormVisible = true
        if (this.$refs.pmbuildingAddOrUpdate) {
          this.$refs.pmbuildingAddOrUpdate.init(id)
        }
      },
      deleteBuilding (id) {
        this.$confirm(`确定要删除该楼栋吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          api.pmbuildingDeleteApi([id]).then(() => {
            this.$message.success('删除成功')
            this.getDataList()
          }).catch(err => {
            // this.$message.error('删除失败')
            // console.error(err)
          })
        }).catch(() => {
          // 用户取消删除
        })
      },
      viewHouses (buildingId, buildingNo) {
        this.selectedBuildingId = buildingId
        this.selectedBuildingNo = buildingNo
        this.houseDialogVisible = true
        this.housePageIndex = 1
        this.getHouseDataList()
      },

      // 处理房屋弹窗关闭
      handleHouseDialogClose(done) {
        this.houseDialogVisible = false
      },

      // 新增房屋
      addHouse() {
        this.houseFormVisible = true
        if (this.$refs.pmhouseAddOrUpdate) {
          this.$refs.pmhouseAddOrUpdate.init(0)
        }
      },

      // 编辑房屋
      editHouse(id) {
        this.houseFormVisible = true
        if (this.$refs.pmhouseAddOrUpdate) {
          this.$refs.pmhouseAddOrUpdate.init(id)
        }
      },

      // 删除房屋
      deleteHouse(id) {
        this.$confirm('确定要删除这条房屋记录吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          houseApi.pmhouseDeleteApi([id]).then(() => {
            this.$message.success('删除成功')
            this.getHouseDataList()
          }).catch(() => {
            // this.$message.error('删除失败')
          })
        }).catch(() => {})
      },

      // 获取房屋数据列表
      getHouseDataList() {
        this.houseDataListLoading = true
        const params = {
          page: this.housePageIndex,
          limit: this.housePageSize,
          buildingId: this.selectedBuildingId
        }

        houseApi.pmhouseListApi(params).then((res) => {
          this.houseDataListLoading = false
          if (res.data && 'list' in res.data) {
            this.houseDataList = res.data.list || []
            this.houseTotalPage = res.data.total || 0
          } else if ('list' in res) {
            this.houseDataList = res.list || []
            this.houseTotalPage = res.total || 0
          } else {
            // 其他格式
            this.houseDataList = []
            this.houseTotalPage = 0
          }
        }).catch((error) => {
          this.houseDataListLoading = false
          this.houseDataList = []
          this.houseTotalPage = 0
        })
      },

      // 房屋每页数
      houseSizeChangeHandle(val) {
        this.housePageSize = val
        this.housePageIndex = 1
        this.getHouseDataList()
      },

      // 房屋当前页
      houseCurrentChangeHandle(val) {
        this.housePageIndex = val
        this.getHouseDataList()
      }
    }
  }
</script>

<style scoped>
.house-list-container {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f9fafc;
}

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