<template>
    <popup
        class="inline mr-3"
        :clickModalClose="false"
        title="选择服务"
        :center="true"
        @close="handleClose(serviceFormRef)"
        @confirm="handleConfirm"
        @open="handleOpen"
        width="1050px"
    >
        <template #trigger>
            <slot></slot>
        </template>
        <el-form :model="serviceForm" ref="serviceFormRef" :inline="true" label-width="auto">
            <el-form-item label="服务名称">
                <el-input
                    class="ls-input"
                    v-model="serviceForm.name"
                    placeholder="请输入"
                    clearable
                ></el-input>
            </el-form-item>
            <el-form-item label="服务分类">
                <el-select
                    v-model="serviceForm.categoryId"
                    placeholder="请选择"
                    class="ls-input"
                    clearable
                >
                    <el-option
                        v-for="category in categoryLists"
                        :key="category.id"
                        :label="category.name"
                        :value="category.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getLists">搜索</el-button>
                <el-button @click="resetParams">重置</el-button>
            </el-form-item>
        </el-form>

        <div>
            <el-table
                ref="tableDataRef"
                :data="pager.lists"
                row-key="id"
                border
                style="width: 100%"
                @selection-change="handleSelectionChange"
                height="500"
            >
                <el-table-column
                    type="selection"
                    width="50"
                    :reserve-selection="true"
                ></el-table-column>
                <el-table-column
                    property="name"
                    label="服务名称"
                    min-width="200"
                    show-overflow-tooltip
                />
                <el-table-column property="image" label="服务图片" min-width="100">
                    <template #default="scope">
                        <div class="flex items-center">
                            <el-image
                                style="width: 48px; height: 48px"
                                :src="scope.row.image"
                                :fit="'cover'"
                            />
                        </div>
                    </template>
                </el-table-column>
                <el-table-column property="category" label="服务分类" min-width="160" />
            </el-table>
        </div>
        <div class="flex justify-end mt-3">
            <pagination v-model="pager" @change="getLists" />
        </div>
    </popup>
</template>

<script lang="ts" setup>
import { computed, watchEffect, ref, reactive } from 'vue'
import type { ElForm, ElTable, FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import Pagination from '@/components/pagination/index.vue'
import { usePaging } from '@/hooks/usePaging'
import { apiServiceLists } from '@/api/service/lists'
import { deepClone } from '@/utils/util'
import { CHANNEL_INJECTION_KEY } from '@/config/symbol'

interface serviceFormObj {
    name?: string
    status?: number | string
    categoryId: number | string
}
const props = withDefaults(
    defineProps<{
        modelValue: any
    }>(),
    {
        modelValue: []
    }
)

const emit = defineEmits(['update:modelValue'])

const parent = inject(CHANNEL_INJECTION_KEY)
const categoryLists = computed(() => parent?.categoryLists.value)

const serviceFormRef = ref<InstanceType<typeof ElForm>>()
const tableDataRef = ref<InstanceType<typeof ElTable>>()
const selectData = ref<Array<object> | null>(props.modelValue)
const serviceForm = reactive<serviceFormObj>({
    name: '',
    status: '',
    categoryId: ''
})

const { pager, getLists, resetPage, resetParams } = usePaging({
    size: 10,
    fetchFun: apiServiceLists,
    params: serviceForm
})

// 表格多选选择的数据
const handleSelectionChange = (val: Event | any) => {
    selectData.value = val
}

// 弹窗关闭
const handleClose = (formEl: FormInstance | undefined): void => {
    if (!formEl) return
    formEl.resetFields()
}
// 确认选择
const handleConfirm = (): void => {
    // 深度克隆防止数据串到父组件
    emit('update:modelValue', deepClone(selectData.value))
}

getLists()

watchEffect(() => {
    selectData.value = props.modelValue
})

const handleOpen = () => {
    nextTick(() => selectTable())
}
/**表格选中效果 */
function selectTable() {
    setTimeout(() => {
        const tableData = pager.lists
        const selectedIds = props.modelValue?.map((item: any) => item.id) as number[]
        const selectedList = tableData.filter(data => selectedIds.includes(data.id))
        /**避免tableDataRef为undefined */
        tableData.forEach(data => {
            tableDataRef.value?.toggleRowSelection(data, false)
        })
        selectedList.forEach(item => {
            tableDataRef.value?.toggleRowSelection(item, true)
        })
    }, 50)
}
watch(
    () => props.modelValue,
    () => selectTable(),
    { deep: true }
)
watch(
    () => pager.page,
    () => props.modelValue.length && selectTable()
)
</script>

<style lang="scss" scoped>
.ls-input {
    width: 240px;
}

:deep(.el-table__inner-wrapper) {
    height: 365px;
    overflow-y: scroll;
    overflow-x: hidden;
}
</style>
