<template>
    <popup class="inline mr-3" :clickModalClose="false" :title="`选择${setTitle}`" :center="true"
        @close="handleClose(channelFormRef)" @open="handleOpen" @confirm="handleConfirm" width="1200px">
        <template #trigger>
            <slot></slot>
        </template>
        <component :is="setComponent" ref="componentRef" />
    </popup>
</template>

<script lang="ts" setup>
import { computed, ref, type PropType } from 'vue'
import type { ElForm, FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import distributeTable from './distributeTable.vue'
import userTable from './userTable.vue'
import { CHANNEL_INJECTION_KEY } from '@/config/symbol'
import { ChannelEnum } from '@/enums/modeEnum'

const props = defineProps({
    modelValue: Object as PropType<any>
})

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

const parent = inject(CHANNEL_INJECTION_KEY)
const channel = computed(() => parent?.channel.value)
const condition = computed(() => channel.value === ChannelEnum.DISTBUTOR)
const setTitle = computed(() => unref(condition) ? '分销员' : '指定用户')
const setComponent = computed(() => unref(condition) ? distributeTable : userTable) /**根据渠道切换组件 */
const selectObj = computed(() => parent?.selectObj?.value)

const selectData = ref<Record<number, any[]>>({})
const channelFormRef = ref<InstanceType<typeof ElForm>>()
const componentRef = ref()

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

const handleOpen = () => {
    selectedTable()
}
/**表格选中效果 */
function selectedTable() {
    setTimeout(() => {
        if (componentRef.value) {
            const tableData = componentRef.value.pager.lists as any[]
            const selectedIds = selectData.value[unref(channel)!]?.map(item => item.id) as number[]
            if (selectedIds) {
                const selectedList = tableData.filter(data => selectedIds.includes(data.id))
                tableData.forEach(data => {
                    componentRef.value.tableDataRef?.toggleRowSelection(data, false)
                })
                selectedList.forEach(item => {
                    componentRef.value.tableDataRef?.toggleRowSelection(item, true)
                })
            }
        }
    }, 50)
}
watch(() => unref(selectData), () => selectedTable(), { deep: true })
watch(() => componentRef.value && unref(componentRef).pager.page, () => {
    selectData.value[unref(channel)!]?.length && selectedTable()
})
</script>

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

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