<script setup lang="ts">
import { useRoute } from 'vue-router'
import type { ElTable } from 'element-plus'
import Pagination from '@/components/pagination/index.vue'
import { MAP_INJECTION_KEY, type Pager } from '@/config/symbol'

interface TableProps {
    zone: String
    pager: Pager
    selectData?: any[]
}
const props = withDefaults(defineProps<TableProps>(), {
    pager: {}
})
const emit = defineEmits(['update:selectData', 'update:pager'])

const route = useRoute()

const parentApi = inject(MAP_INJECTION_KEY)

const tableRef = ref<InstanceType<typeof ElTable>>()

const tableData = computed(() => props.pager?.lists)
const getLists = computed(() => props.pager?.getLists)
const pathName = computed(() => route.meta.activeMenu)
const originSelectData = computed(() => parentApi?.originSelectData?.value)
const pager = computed({
    get() {
        return props.pager
    },
    set(newVal) {
        emit('update:pager', newVal)
    }
})
/**定位 */
const handleLocation = (row: any) => {
    parentApi?.handleLocation(row)
}
/**删除 */
const handleDelete = (id: number) => {
    parentApi?.handleDelete(id)
}
/**选中 */
const handleSelectionChange = (val: any) => {
    emit('update:selectData', val)
}
/**初始化选中 */
watch(() => unref(tableData), (val) => {
    if (val.length && props.selectData?.length) {
        parentApi?.toggleRowSelection!(originSelectData.value)
    }
})
defineExpose({
    tableRef
})
</script>

<template>
    <div class="atable">
        <div class="atable__top">
            <span>{{ zone }}已有服务区域</span>
        </div>
        <div class="atable-bottom">
            <el-table ref="tableRef" :data="tableData" row-key="id" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" reserve-selection />
                <el-table-column prop="name" label="名称" />
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button link type="primary" @click="handleLocation(row)">定位</el-button>
                        <el-button v-if="!pathName" link type="danger" @click="handleDelete(row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <Pagination v-model="pager" @change="getLists" />
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.atable {
    background-color: #fff;
    // width: 450px;
}
</style>
