<template>
    <info-card
        class="card transfer-table"
        shadow="never"
        border
        :config="{ customHeader: true }"
    >
        <!-- 头部 -->
        <template #header>
            <div
                v-if="topOperations.isTwoRow"
                style="display: flex; justify-content: space-between; align-items: center"
            >
                <el-tooltip
                    :content="title"
                    placement="top"
                >
                    <div
                        class="titleMore"
                        :style="{'margin-right': '15px'}"
                    >{{ $t(title) }}
                    </div>
                </el-tooltip>
                <div v-if="topOperations.iconList">
                    <el-tooltip
                        v-for="(itemIcon, i) in topOperations.iconList"
                        :key="i"
                        :content="itemIcon.content"
                        placement="top"
                    >
                        <el-button
                            size="small"
                            :icon="itemIcon.icon"
                            @click="itemIcon.method"
                        >{{ $t(itemIcon.title) }}
                        </el-button>
                    </el-tooltip>
                </div>

            </div>
            <div
                :style="{display:topOperations.isTwoRow?'block':'flex', justifyContent: 'space-between'}"
            >
                <span
                    v-if="!topOperations.isTwoRow"
                    class="titleMore"
                    :style="{'margin-right': '15px'}"
                >{{ $t(title) }}
                </span>
                <fuzzy-matching
                    v-if="!topOperations.isFuzzyMatch===false || topOperations.isTwoRow"
                    ref="fuzzyMatch"
                    :style="topOperations.isTwoRow?{display:'inline-block', 'line-height':'50px'}:{}"
                    :field="field"
                    :totalData="listData"
                    @getfuzzyMatching="matchResult"
                />
                <div
                    class="btn"
                >
                    <template
                        v-for="(btn) of topOperations.list"
                        :key="btn"
                    >
                        <el-button
                            v-if="topOperations.isButton && topOperations.isTwoRow && btn.show?.()"
                            :icon="btn.icon"
                            :disabled="btn.disabled?.()"
                            :size="btn.size || 'small' "
                            :type=" btn.type || '' "
                            @click="btn.method"
                        >
                            {{ $t(btn.label) }}
                        </el-button>
                        <el-tooltip
                            v-else-if="(btn.isShow ? btn.isShow?.() :  true)"
                            :content="$t(btn.label)"
                            placement="top"
                        >

                            <el-icon
                                size="18px"
                                @click="btn.method"
                            >
                                <component :is="btn.icon"></component>
                            </el-icon>
                        </el-tooltip>
                    </template>
                    <el-tooltip
                        v-if="topOperations.allAdd"
                        :content="$t('addAll')"
                        placement="top"
                    >
                        <el-icon
                            size="18px"
                            @click="addAll"
                        >
                            <Finished/>
                        </el-icon>
                    </el-tooltip>
                    <el-tooltip
                        v-if="topOperations.add"
                        :content="$t('add')"
                        placement="top"
                    >
                        <el-icon
                            size="18px"
                            @click="add"
                        >
                            <Plus/>
                        </el-icon>
                    </el-tooltip>
                    <el-tooltip
                        v-if="topOperations.delete"
                        :content="$t('delete')"
                        placement="top"
                    >
                        <el-icon
                            size="18px"
                            @click="deleteSelected"
                        >
                            <Delete/>
                        </el-icon>
                    </el-tooltip>
                    <el-tooltip
                        v-if="topOperations.isSortField"
                        :content="$t('sort')"
                        placement="top"
                    >
                        <el-icon
                            size="18px"
                            @click="sortField"
                        >
                            <Sort/>
                        </el-icon>
                    </el-tooltip>
                </div>
            </div>
        </template>
        <table-btn
            ref="tableRef"
            :key="upKey"
            :list="result"
            :columns="columns"
            :operates="operations"
            :options="tableOption"
            @handleSelectionChange="handleSelectionChange"
            @handleOneRowClick="handleOneRowClick"
            @handleCurrentChange="handleCurrentChange"
            @scrollLoadAllList="loadMore"
            @scrollLoad="loadMore"
            @dropEnd="dropEndTable"
        />
        <!--        <pagination-->
        <!--            :parameter="parameter"-->
        <!--            :totalNumber="result.length"-->
        <!--            :pagerCount="pagerCount"-->
        <!--            :stateFlag="false"-->
        <!--            @changeTableData="changeTableData"-->
        <!--        />-->
    </info-card>
</template>
<script lang="ts" setup>
import infoCard from '../infoCard/infoCard.vue'
import tableBtn from '../table/table.vue'
import pagination from '../table/pagination.vue'
import fuzzyMatching from '../fuzzyMatching/fuzzyMatching.vue'
import { Delete, Sort, Plus, Finished } from '@element-plus/icons-vue'
import { reactive, ref, computed, watch, onMounted } from 'vue'
import {
    deleteObject,
    getFieldValue,
    deepCopy,
    ObjectInterface
} from '../../script/util'

let props = defineProps({
    title: {
        type: String,
        default: 'selectedData'
    },
    searchField: {
        type: String,
        default: ''
    },
    listData: {
        type: Array as any,
        default: () => []
    },
    columns: {
        type: Array as any,
        default: () => []
    },
    operations: {
        type: Object as any,
        default: () => {
        }
    },
    topOperations: {
        type: Object,
        default: () => {
            return {}
        }
    },
    tableConfig: {
        type: Object,
        default: () => {
            return {}
        }
    },
    pagerCount: {
        type: Number,
        default: 7
    }
})
let emits = defineEmits(['deleted', 'handleSelectData', 'loadMore', 'dropEnd', 'handleOneRowClick', 'handleFilterTableData'])
const tableRef = ref()
let field = computed(() => {
    return props.searchField
})

watch(props.listData, (newValue: ObjectInterface[], old: ObjectInterface[]) => {
    init()
})
const upKey = ref()
let tableOption = reactive<any>({
    i18n: true,
    isAllList: true,
    listSize: 20,
    rowKey: props.tableConfig.rowKey, // table主键
    isDrop: props.tableConfig.isDrop || false, // table行是否可拖拽
    selectable: props.tableConfig.selectable, // 行是否可以被选中
    height: props.operations?.height || props.operations?.height?.() || '350px',
    // maxHeight: '500px',
    // minHeight: '120px',
    size: 'default',
    isHideSet: true,
    mutiSelect: props.operations?.mutiSelect !== false
})
onMounted(() => {
    setTimeout(() => {
        Object.assign(tableOption, props.tableConfig)
        init()
    }, 0)
})
let result = reactive<any[]>([])
let fuzzyMatch = ref()
let init = () => {
    result.length = 0
    const matchKeyword = fuzzyMatch.value?.keyword
    if (matchKeyword) {
        let result = fuzzyMatch.value?.filterResult()
        result.push(...result)
    } else {
        result.push(...props.listData)
    }
}

let selectData = reactive<ObjectInterface[]>([])
// 删除已选择
let deleteSelected = () => {
    selectData.forEach((row: ObjectInterface) => {
        deleteItem(row)
    })
    emits('deleted', props.listData)
}
let parameter = reactive({
    pageSize: 8,
    pageNum: 1
})
// 删除当前条
let deleteItem = (row: ObjectInterface) => {
    deleteObject(row[field.value], result, field.value)
    deleteObject(row[field.value], props.listData, field.value)
    // 重新计算当前页
    if (parameter.pageNum >= result.length / parameter.pageSize) {
        parameter.pageNum = result.length === 0 ? 1 : Math.ceil(result.length / parameter.pageSize)
    }
}
let matchResult = (data: []) => {
    parameter.pageNum = 1
    result.length = 0
    if (props.tableConfig?.isAllList) {
        tableRef.value.partition = true
    }
    result.push(...data)
    upKey.value++
    emits('handleFilterTableData', result) // 返回过滤结果
}
let handleSelectionChange = (val: ObjectInterface) => {
    selectData = val ? deepCopy(val) : []
    emits('handleSelectData', val)
}
let handleCurrentChange = (val: ObjectInterface) => {
    selectData = val ? [deepCopy(val)] : []
}
let handleOneRowClick = (row: ObjectInterface, column, event) => {
    emits('handleOneRowClick', row, column, event)
}
let add = () => {
    emits('handleSelectData', selectData)
}
let addAll = () => {
    emits('handleSelectData', result)
}
let isSort = ref(-1)
// 排序
let sortField = () => {
    isSort.value = -isSort.value
    let orderBy = (a: any, b: any) => {
        const val1 = getFieldValue(a, field.value).toLowerCase()
        const val2 = getFieldValue(b, field.value).toLowerCase()
        return val1 > val2 ? isSort.value : -isSort.value
    }
    result.sort(orderBy)
}
let changeTableData = () => {
}
// 加载更多回调
let loadMore = (e: any) => {
    emits('loadMore', e, result)
}
// 拖拽结束回调
let dropEndTable = (par: ObjectInterface) => {
    emits('dropEnd', par)
}
</script>
<style lang="scss" scoped>
.card {
    :deep(.custom) {
        .titleMore {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .el-input {
            width: 200px;
        }

        .btn {
            float: right;

            .el-icon {
                padding: 0 5px;
            }
        }

        .btnRow {
            display: flex;
            align-items: center;
            height: 100%;
        }
    }

    :deep(.block) {
        padding: 0 !important;
    }

    .tableListBtn {
        height: auto;
        padding: 0;
        margin-bottom: 8px;
    }
}
</style>
