<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <el-form-item label="小区名称" prop="communityId">
        <el-select
          v-model="queryParams.communityId"
          placeholder="请选择小区"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="item in communityOptions"
            :key="item.id"
            :label="item.communityName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业主姓名" prop="ownerName">
        <el-input
          v-model="queryParams.ownerName"
          placeholder="请输入业主姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 查询
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 操作按钮栏 -->
  <ContentWrap>
    <div class="mb-15px">
      <el-button
        type="primary"
        plain
        @click="openForm('create')"
        v-hasPermi="['community:house:create']"
      >
        <Icon icon="ep:plus" class="mr-5px" /> 新建
      </el-button>
      <el-button
        type="primary"
        plain
        @click="handleImport"
        v-hasPermi="['community:house:import']"
      >
        <Icon icon="ep:upload" class="mr-5px" /> 导入
      </el-button>
      <el-button
        type="primary"
        plain
        @click="handleExport"
        :loading="exportLoading"
        v-hasPermi="['community:house:export']"
      >
        <Icon icon="ep:download" class="mr-5px" /> 导出
      </el-button>
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
        :header-cell-style="{
          background: '#1890ff',
          color: '#ffffff',
          textAlign: 'center',
          fontWeight: 'normal',
          fontSize: '14px',
          borderColor: '#1890ff'
        }"
        :cell-style="{
          textAlign: 'center',
          fontSize: '14px',
          color: '#333333',
          borderColor: '#ebeef5'
        }"
    >
    <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="80" />
      <el-table-column label="小区名称" align="center" prop="communityName" min-width="120" />
      <el-table-column label="楼号" align="center" prop="buildingNo" width="100" />
      <el-table-column label="单元号" align="center" prop="unitNo" width="100" />
      <el-table-column label="门牌号" align="center" prop="roomNo" width="100" />
      <el-table-column label="业主姓名" align="center" prop="ownerName" width="100" />
      <el-table-column label="业主联系方式" align="center" prop="ownerPhone" width="120">
        <template #default="scope">
          {{ formatPhone(scope.row.ownerPhone) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120px" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['community:house:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['community:house:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <HouseForm ref="formRef" @success="getList" />

  <!-- 导入弹窗 -->
  <ImportForm ref="importFormRef" @success="getList" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { HouseApi, House } from '@/api/community/house'
import { CommunityApi, CommunitySimpleVO } from '@/api/community/community'
import HouseForm from './HouseForm.vue'
import ImportForm from './ImportForm.vue'

/** 房屋信息主 列表 */
defineOptions({ name: 'House' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<House[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  communityId: undefined,
  ownerName: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const communityOptions = ref<CommunitySimpleVO[]>([]) // 小区选项列表

/** 格式化手机号（脱敏显示） */
const formatPhone = (phone: string) => {
  if (!phone) return '-'
  if (phone.length === 11) {
    return phone.substring(0, 3) + '****' + phone.substring(7)
  }
  return phone
}

/** 加载小区列表 */
const loadCommunityList = async () => {
  try {
    communityOptions.value = await CommunityApi.getCommunitySimpleList()
  } catch (error) {
    console.error('加载小区列表失败:', error)
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await HouseApi.getHousePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 导入操作 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await HouseApi.deleteHouse(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除房屋信息主 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await HouseApi.deleteHouseList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: House[]) => {
  checkedIds.value = records.map((item) => item.id!);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await HouseApi.exportHouse(queryParams)
    download.excel(data, '房屋信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  loadCommunityList()
  getList()
})
</script>
