<template>
  <Dialog v-model="dialogVisible" title="关联长者设置" width="56vw">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="mb-4">
      <el-form-item label="长者姓名：">
        <el-input v-model="queryParams.elderName" placeholder="请输入" clearable style="width: 20vw"/>
      </el-form-item>
      <el-form-item label="关联状态：">
        <el-select v-model="queryParams.relationStatus" placeholder="请选择" clearable style="width: 20vw">
          <el-option label="未关联" value="未关联" />
          <el-option label="已关联" value="已关联" />
        </el-select>
      </el-form-item>
      <el-form-item label="居住地址：">
        <el-cascader
          v-model="queryParams.areaCode"
          :options="areaTree"
          :props="defaultProps"
          placeholder="请选择省/市/街道"
          clearable
          style="width: 20vw;"
        />

      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 批量关联按钮 -->
    <div class="mb-4">
      <el-button type="primary" @click="handleBatchRelate" :disabled="!selectedIds.length">
        批量关联长者
      </el-button>
    </div>

    <!-- 长者列表 -->
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="elderName" label="长者姓名" />
      <el-table-column prop="sex" label="性别" width="80" >
        <template #default="scope">
          {{scope.row.sex=="1"?"男":"女"}}
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="80" />
      <el-table-column prop="phone" label="联系方式" />
      <el-table-column prop="currentLiveAddress" label="居住地址" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-button link type="primary" @click="handleRelate(scope.row)">
            关联长者
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="flex justify-end mt-4">
      <el-pagination
        v-model:current-page="queryParams.pageNo"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="getList"
        @current-change="getList"
      />
    </div>
  </Dialog>
</template>

<script lang="ts" setup>
import * as ElderApi from '@/api/living-home/elderly'
import * as AreaApi from '@/api/system/area'
import { defaultProps, handleTree } from '@/utils/tree'
import {getHomeElderlyList} from "@/api/living-home/elderly";

defineOptions({ name: 'RelateElderDialog' })

const message = useMessage() // 消息弹窗

const defaultProps = {
  children: 'children',
  label: 'name',
  value: 'id',
  isLeaf: 'leaf',
  emitPath: false,
  checkStrictly: true,
}


const dialogVisible = ref(false) // 弹窗显示状态
const loading = ref(false) // 加载状态
const list = ref<any[]>([]) // 长者列表
const total = ref(0) // 总数
const selectedIds = ref<number[]>([]) // 选中的长者ID
const servicePersonId = ref<number>() // 当前服务人员ID

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 20,
  elderName: '',
  relationStatus: '',
  areaCode: [],
  currentLiveAddress: ''
})

const queryFormRef = ref()
const areaTree = ref<any[]>([]) // 地区树数据

/** 加载地区树 */
const loadAreaTree = async () => {
  try {
    areaTree.value = await AreaApi.getAreaTree()
    //areaTree.value = handleTree(data)
  } catch (error) {
    console.error('加载地区树失败:', error)
  }
}

/** 打开弹窗 */
const open = async (id: number) => {
  servicePersonId.value = id
  dialogVisible.value = true
  await loadAreaTree()
  await getList()
}
defineExpose({ open })

/** 查询长者列表 */
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams,
      servicePersonId: servicePersonId.value
    }
    const data = await ElderApi.getHomeElderlyList(params)
    list.value = data.list || []
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

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

/** 重置 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.pageNo = 1
  getList()
}

/** 多选 */
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map((item) => item.id)
}

/** 单个关联 */
const handleRelate = async (row: any) => {
  try {
    await ElderApi.relateElder({
      servicePersonId: servicePersonId.value,
      elderId: row.id
    })
    message.success('关联成功')
    getList()
  } catch (error) {
    console.error('关联失败:', error)
  }
}

/** 批量关联 */
const handleBatchRelate = async () => {
  if (selectedIds.value.length === 0) {
    message.warning('请选择要关联的长者')
    return
  }
  try {
    await ElderApi.batchRelateElder({
      servicePersonId: servicePersonId.value,
      elderIds: selectedIds.value
    })
    message.success('批量关联成功')
    getList()
  } catch (error) {
    console.error('批量关联失败:', error)
  }
}
</script>
