<template>
  <div class="communityPage">
    <div class="searchBar">
      <a-form layout="inline" @keydown.enter="searchHandler">
        <a-form-item label="小区名称">
          <a-input
            v-model:value.trim="searchState.tenantName"
            placeholder="小区名称"
            :maxlength="300"
            show-count
            allow-clear
            @change="clearHandler"
          />
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button type="primary" @click="searchHandler"> 搜索 </a-button>
            <a-button @click="resetHandler"> 重置 </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <div class="tableCard">
      <div class="tableCard-header">
        <div class="tableCard-header-title">小区列表</div>
        <div class="tableCard-header-extra">
          <a-space>
            <a-button type="primary" @click="addCommunityHandler">添加小区</a-button>
          </a-space>
        </div>
      </div>
      <a-table
        :columns="columns"
        :data-source="listData"
        :loading="loading"
        :pagination="false"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'location'">
            <div>{{ record.location }}</div>
            <div>{{ record.address }}</div>
          </template>

          <template v-if="column.key === 'time'">
            <div>{{ record.createTime }}</div>
            <div>{{ record.updateTime }}</div>
          </template>

          <template v-if="column.key === 'action'">
            <!-- <a-button type="link" @click="viewHandler(record.tenantId, record.tenantName)"
              >设备树</a-button
            > -->
            <a-button type="link" :disabled="record.sort !== 1" @click="viewDevicelHandler(record)"
              >查看设备</a-button
            >
            <a-button type="link" :disabled="record.sort !== 1" @click="editlHandler(record)"
              >编辑小区</a-button
            >
            <a-button type="link" :disabled="record.sort !== 1" @click="adminlHandler(record)"
              >小区管理员</a-button
            >
          </template>
        </template>
      </a-table>

      <base-pagination
        v-if="listTotal > 0"
        v-model:current="current"
        v-model:pageSize="pageSize"
        :total="listTotal"
        @change="paginationChange"
        @showSizeChange="paginationSizeChange"
      ></base-pagination>
    </div>

    <add-community-modal
      v-model:open="addCommunityOpen"
      :title="addCommunityTitle"
      :type="addCommunityType"
      :data="addCommunityData"
      @success="searchHandler"
    ></add-community-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onActivated } from 'vue'
import * as tenantAPI from '@/api/tenant'
import type { TenantItem } from '@/api/tenant/types'
import { columns } from './const'
import { useSearch } from '@/hooks/useSearch'
import addCommunityModal from '../components/add/index.vue'
import { useRouter } from 'vue-router'

const router = useRouter()

defineOptions({
  name: 'CommunityIndex',
})

interface SearchData {
  tenantName: string // 租户名称、小区名称
}
// 默认搜索条件
const defaultSearch: SearchData = {
  tenantName: '',
}

const [searchState, resetHandler] = useSearch(defaultSearch, { afterReset: () => searchHandler() })

const listData = ref<TenantItem[]>()
const listTotal = ref<number>(0)
const current = ref<number>(1)
const pageSize = ref<number>(10)

// 分页变化
const paginationChange = (current: number, pageSize: number) => {
  console.log('change', current, pageSize)
  fetchList()
}
// 分页大小变化
const paginationSizeChange = (current: number, pageSize: number) => {
  console.log('showSizeChange', current, pageSize)
}

const loading = ref(false)
// 获取租户/小区列表
const fetchList = async () => {
  try {
    loading.value = true
    const res = await tenantAPI.queryTenant({
      pageNo: current.value,
      pageSize: pageSize.value,
      tenantName: searchState.tenantName,
    })
    console.log('✅获取到数据', res)
    const { rows, total } = res.data
    listData.value = rows
    try {
      listData.value = rows.map((item) => {
        return {
          ...item,
          location: [item.province, item.city, item.district]
            .map((i) => {
              return i?.split(',')[1] || ''
            })
            .join(' '),
        }
      })
    } catch (error) {
      console.log('❌', error)
    }
    listTotal.value = Number(total)
    loading.value = false
  } catch (err) {
    console.log('❌ 获取数据失败', err)
    loading.value = false
  }
}

onActivated(() => {
  fetchList()
})

// 搜索
const searchHandler = async () => {
  console.log('searchState', searchState)
  current.value = 1
  pageSize.value = 10
  await fetchList()
}

// 搜索条件变化时清空搜索结果
const clearHandler = (e: InputEvent) => {
  console.log('clearHandler', e, e.target, e.target?.value)
  if (!e.target?.value) {
    fetchList()
  }
}

const addCommunityOpen = ref(false)
const addCommunityTitle = ref('')
const addCommunityType = ref<'tenant' | 'admin'>('tenant')
const addCommunityData = ref<Partial<TenantItem | object>>({})
// 添加小区
const addCommunityHandler = () => {
  console.log('添加小区')
  addCommunityTitle.value = '添加小区'
  addCommunityType.value = 'tenant'
  addCommunityOpen.value = true
  addCommunityData.value = {}
}

// 维护管理员
const adminlHandler = (item: TenantItem) => {
  console.log('小区管理员', item)
  addCommunityTitle.value = `${item.tenantName} 管理员`
  addCommunityType.value = 'admin'
  addCommunityData.value = {
    tenantId: item.tenantId,
  }
  addCommunityOpen.value = true
}

// 查看设备
const viewDevicelHandler = (item: TenantItem) => {
  console.log('查看设备', item)
  router.push({
    name: 'deviceList',
    query: {
      tenantId: item.tenantId,
    },
  })
}

// 查看详情
// const viewHandler = (tenantId: string, name: string) => {
//   console.log('查看')
//   router.push({
//     name: 'communityDetail',
//     query: {
//       tenantId,
//       name,
//     },
//   })
// }

// 编辑小区
const editlHandler = (item: TenantItem) => {
  console.log('编辑', item)
  addCommunityTitle.value = '编辑小区'
  addCommunityType.value = 'tenant'
  addCommunityData.value = {
    tenantId: item.tenantId,
    tenantName: item.tenantName,
    tenantType: item.tenantType,
    pcdStrs: [item.province, item.city, item.district],
    address: item.address,
    remark: item.remark,
  }
  addCommunityOpen.value = true
}
</script>

<style scoped lang="less">
.communityPage {
  .searchBar {
    padding: 20px;
    background-color: #fff;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    .ant-form {
      flex-grow: 1;
    }
    :deep(.ant-form-inline .ant-form-item) {
      margin-bottom: 16px !important;
    }
  }

  .tableCard {
    background-color: #fff;

    &-header {
      display: flex;
      justify-content: space-between;
      padding: 20px;
      &-title {
        font-size: 18px;
        font-weight: 600;
      }
    }
  }
}
</style>
