<script lang='ts' name='DropDownTable' setup>
import { nextTick, onMounted, reactive, ref, watch } from 'vue';
import { ArrowDown, ArrowUp, Search } from '@element-plus/icons-vue';
import { getLanguage } from '@/api/workflowManagement/index';
import { getAllUserList, getAllUser } from '@/api/workflowManagement/index'
import { pages } from '@/constant/route';
import { language } from '@/model/language';
import { onClickOutside, useElementSize } from '@vueuse/core';

const props = defineProps({
    i_user_no: { type: String, required: true, default: '' },
    multiple: { type: Boolean, default: false },
    disabled: { type: Boolean, default: false },
});

const emit = defineEmits<{
    (e: 'change', val: string): void
    (e: 'update:i_user_no', val: string): void
    (e: 'update:label', val: string): void
}>();


interface User {
    i_company_name: string;
    i_dept_name: string;
    i_employee_name: string;
    i_key: string;
    i_employee_pinyin: string;
    i_key: string;
}

const select = ref(false);
const search = ref('');
const selectUser = ref('');
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const target = ref(null);
const inputEl = ref(null);
const loading = ref(false);

onClickOutside(target, (event) => {
    if (event.isTrusted) {
        select.value = false;
    }
});

const { width: inputWidth } = useElementSize(inputEl);


let data = reactive({
    pageSizes: [] as string[],
    tableData: [] as User[],
    pageSize: 20 as number,
    currentPage: 1 as number,
    total: 1 as number,
    multipleSelection: [] as User[],
    Language: {} as language.NewApply,
    searchSelectedDataCache: [] as User[],
});

onMounted(async () => {
    let res1: any = await getLanguage({ i_func_id: pages.newApply });
    data.Language = res1.data;

    if (search.value !== '') {
        let res: any = await getAllUserList({ i_field: search.value });
        data.tableData = res.dataList;
    }

    if (props.i_user_no !== '') {
        let res: any = await getAllUser({ i_key: props.i_user_no });
        data.multipleSelection = res.dataList;
        data.tableData = res.dataList;
        selectUser.value = '';
        data.multipleSelection.forEach(el => {
            selectUser.value += (selectUser.value === '' ? '' : ',') + el.i_employee_pinyin;
        });
        emit('update:label', selectUser.value)
    }
});

watch(() => select.value, async (newVal: boolean) => {
    if (newVal && (props.multiple === false)) {
        search.value = '';
        handleSelectOnlyOne(data.multipleSelection, data.multipleSelection[0]);
    } else if (newVal && (props.multiple === true)) {
        search.value = '';
    }
});

watch(() => props.i_user_no, async (newVal: string) => {
    if (newVal === '') {
        search.value = ''
        selectUser.value = '';
        data.multipleSelection = []
        data.tableData = []
        data.searchSelectedDataCache = []
        selectUser.value = ''
    } else {
        if (newVal !== '') {
            let res: any = await getAllUser({ i_key: newVal });
            data.multipleSelection = res.dataList;
            selectUser.value = '';
            data.multipleSelection.forEach(el => {
                selectUser.value += (selectUser.value === '' ? '' : ',') + el.i_employee_pinyin;
            });
        }
    }
});

// 页条数切换
const handleSizeChange = (val: number) => {
    data.pageSize = val;
};

// 页码切换
const handleCurrentChange = (val: number) => {
    data.currentPage = val;
};

const handleSelect = (val: User[]) => {
    if (!props.multiple) {
        // 单选模式
        if (val.length !== 0) {
            data.multipleSelection = val.slice(val.length - 1, val.length);
            // selectUser.value = '';
            data.multipleSelection.forEach((el: User) => {
                selectUser.value = el.i_employee_pinyin;
            });
            handleSelectOnlyOne(val, data.multipleSelection[0]);
            emit('change', data.multipleSelection[0].i_key);
            emit('update:i_user_no', data.multipleSelection[0].i_key);
            select.value = false;
        } else {
            selectUser.value = '';
            emit('change', '');
            emit('update:i_user_no', '');
        }
    } else {
        // 多选模式
        if (val.length === 0) {
			// 如果选择是空的话 那就代表有一个勾选被取消了
            let userId = '';
            selectUser.value = '';
            data.searchSelectedDataCache = [];
            data.multipleSelection = [];
            emit('change', userId);
            emit('update:i_user_no', userId);
            // if (data.searchSelectedDataCache.length === 1) {
            //     // 但是本次搜索勾选缓存中是有数据的
            //     let userId = '';
            //     data.searchSelectedDataCache.forEach(el => {
            //         for (let i = 0; i < data.multipleSelection.length; i++) {
            //             if (el.i_key === data.multipleSelection[i].i_key) {
            //                 data.multipleSelection.splice(i, 1);
            //             }
            //         }
            //     });
            //     selectUser.value = '';
            //     data.searchSelectedDataCache = [];
            //     data.multipleSelection.forEach((el: User) => {
            //         selectUser.value += (selectUser.value === '' ? '' : ',') + el.i_employee_pinyin;
            //         userId += (userId === '' ? '' : ',') + el.i_key;
            //     });
            //     emit('change', userId);
            //     emit('update:i_user_no', userId);
            // }
        } else if (data.searchSelectedDataCache.length > 1) {
            let userId = '';
            let deleteIndex = -1;
            for (let i = 0; i < data.multipleSelection.length; i++) {
                if (data.tableData.findIndex(item => data.multipleSelection[i].i_key === item.i_key) !== -1
                ) {
                    if (val.findIndex(item => data.multipleSelection[i].i_key === item.i_key) === -1) {
                        deleteIndex = i;
                    }
                }
            }

            data.multipleSelection.splice(deleteIndex, (deleteIndex !== -1 ? 1 : 0));
            selectUser.value = '';
            data.searchSelectedDataCache = [];
            data.multipleSelection.forEach((el: User) => {
                selectUser.value += (selectUser.value === '' ? '' : ',') + el.i_employee_pinyin;
                userId += (userId === '' ? '' : ',') + el.i_key;
            });
            emit('change', userId);
            emit('update:i_user_no', userId);
        }
        // if (selectUser.value !== '') {
        //   let userId = '';
        //   selectUser.value = '';
        //   userId += props.i_user_no;
        //   data.multipleSelection = data.multipleSelection.concat(val);
        //   data.searchSelectedDataCache = data.searchSelectedDataCache.concat(val);
        //   data.multipleSelection.forEach((el: User) => {
        //     selectUser.value += (selectUser.value === '' ? '' : ',') + el.i_employee_pinyin;
        //     userId += (userId === '' ? '' : ',') + el.i_key;
        //   });
        //   emit('change', userId);
        //   emit('update:i_user_no', userId);
        // } else {
        let userId = '';
        selectUser.value = '';
        // data.multipleSelection = data.multipleSelection.concat(val);
        for (let i = 0; i < val.length; i++) {
            if (data.multipleSelection.findIndex(item => val[i].i_key === item.i_key) === -1) {
                data.multipleSelection.push(val[i]);
            }
        }
        data.searchSelectedDataCache = val;
        data.multipleSelection.forEach((el: User) => {
            selectUser.value += (selectUser.value === '' ? '' : ',') + el.i_employee_pinyin;
            userId += (userId === '' ? '' : ',') + el.i_key;
        });
        emit('change', userId);
        emit('update:i_user_no', userId);
        // }
    }
};

// 改变勾选
// const handleSelectionChange = (val: User[]) => {
//   if (props.multiple === false) {
//     if (val.length !== 0) {
//       data.multipleSelection = val.slice(val.length - 1, val.length);
//       // selectUser.value = '';
//       data.multipleSelection.forEach((el: User) => {
//         selectUser.value = el.i_employee_pinyin;
//       });
//       handleSelectOnlyOne(val, data.multipleSelection[0]);
//       emit('change', data.multipleSelection[0].i_key);
//       emit('update:i_user_no', data.multipleSelection[0].i_key);
//       select.value = false;
//     } else {
//       selectUser.value = '';
//       emit('change', '');
//       emit('update:i_user_no', '');
//     }
//   } else {
//     let userId = '';
//     selectUser.value = '';
//     data.multipleSelection = val;
//     data.multipleSelection.forEach((el: User) => {
//       selectUser.value += (selectUser.value === '' ? '' : ',') + el.i_employee_pinyin;
//       userId += (userId === '' ? '' : ',') + el.i_key;
//     });
//     emit('change', userId);
//     emit('update:i_user_no', userId);
//   }
// };

const handleSelectOnlyOne = (dataList: User[], val: User) => {
    // multipleTableRef.value!.clearSelection();
    dataList.forEach((row: User) => {
        if (val.i_key !== row.i_key) {
            multipleTableRef.value!.toggleRowSelection(row, undefined);
        }
    });
};

// 搜索事件
const handleSearchChanged = async (val: string) => {
    if (val === '') return;
    loading.value = true;
    search.value = val;
    try {
        let res: any = await getAllUserList({ i_field: search.value });
        data.tableData = res.dataList;
        // 搜索时重新清除缓存
        data.searchSelectedDataCache = [];
        nextTick(() => {
            // 获取哪些人是勾选的
            data.multipleSelection.forEach((row: User) => {
                for (let i = 0; i < data.tableData.length; i++) {
                    if (row.i_key === data.tableData[i].i_key) {
                        data.searchSelectedDataCache.push(data.tableData[i]);
                        multipleTableRef.value!.toggleRowSelection(data.tableData[i], undefined);
                    }
                }
            });
            // 如果选择的数据中没有这个 user_no 的话就添加进去
            if (props.i_user_no !== '' && data.multipleSelection.length === 0) {
                if (props.i_user_no.search(',') === -1) {
                    // 单选的情况
                    for (let i = 0; i < data.tableData.length; i++) {
                        if (props.i_user_no === data.tableData[i].i_key) {
                            if (data.multipleSelection.findIndex((el) => el.i_key === data.tableData[i].i_key) === -1) {
                                data.multipleSelection.push(data.tableData[i]);
                            }
                            multipleTableRef.value!.toggleRowSelection(data.tableData[i], undefined);
                        }
                    }
                } else {
                    // 多选的情况
                    let arr = props.i_user_no.split(',');
                    for (let y = 0; y < arr.length; y++) {
                        for (let i = 0; i < data.tableData.length; i++) {
                            if (arr[y] === data.tableData[i].i_key) {
                                if (data.multipleSelection.findIndex((el) => el.i_key === data.tableData[i].i_key) === -1) {
                                    data.multipleSelection.push(data.tableData[i]);
                                    data.searchSelectedDataCache.push(data.tableData[i]);
                                }
                                multipleTableRef.value!.toggleRowSelection(data.tableData[i], undefined);
                            }
                        }
                    }

                }
            }
            loading.value = false;
        });
    } catch (e) {
        loading.value = false;
        return;
    }
};

const init = () => {
    selectUser.value = ''
    data.tableData = []
    data.searchSelectedDataCache = []
    data.multipleSelection = []
    search.value = ''
}

const openPopover = async () => {
    if (props.disabled === false) {
        select.value = !select.value
        if (select.value === true) {
            if (props.i_user_no !== '') {
                let res: any = await getAllUser({ i_key: props.i_user_no });
                data.tableData = res.dataList;
                nextTick(() => {
                    // 获取哪些人是勾选的
                    data.multipleSelection.forEach((row: User) => {
                        for (let i = 0; i < data.tableData.length; i++) {
                            if (row.i_key === data.tableData[i].i_key) {
                                data.searchSelectedDataCache.push(data.tableData[i]);
                                multipleTableRef.value!.toggleRowSelection(data.tableData[i], undefined);
                            }
                        }
                    });
                })
            }
        }
    }
}

defineExpose({ init, label: selectUser.value })
</script>
<template>
    <el-popover :visible='select' :width='inputWidth' placement='bottom'>
        <template #reference>
            <el-input ref='inputEl' v-model='selectUser' :disabled='disabled' autosize class='cursor-pointer' readonly
                @click='openPopover'>
                <template #suffix>
                    <el-icon @click='openPopover'>
                        <ArrowUp v-if='select === true' />
                        <ArrowDown v-else />
                    </el-icon>
                </template>
            </el-input>
        </template>
        <!--<div v-show='select === true' ref='target' class='w-full relative'>-->
        <!--  <div class='absolute z-50 w-full'>-->
        <!--<el-card shadow='hover'>-->
        <div ref='target'>
            <div class='w-40 mb-2'>
                <el-input v-model='search' :placeholder='data.Language.search' :suffix-icon='Search' clearable
                    @change='handleSearchChanged' />
            </div>
            <el-table ref='multipleTableRef' v-loading='loading' :data='data.tableData' border height='200px'
                highlight-current-row style='width: 100%' table-layout='fixed' @select='handleSelect'>
                <el-table-column type='selection' width='55' class-name="no-select-all" />
                <el-table-column :label='data.Language.i_employee_name' prop='i_employee_name' />
                <el-table-column :label='data.Language.i_employee_pinyin' prop='i_employee_pinyin' />
                <el-table-column :label='data.Language.i_dept_no' prop='i_company_name' />
                <el-table-column :label='data.Language.dept' prop='i_dept_name' />
            </el-table>
        </div>
        <!--</el-card>-->
        <!--  </div>-->
        <!--</div>-->
    </el-popover>


    <!--<el-input v-model='selectUser' :suffix-icon=' select === true ? ArrowUp : ArrowDown' readonly-->
    <!--          @click='select=!select'></el-input>-->
    <!--<div v-show='select === true' ref='target' class='w-full relative'>-->
    <!--  <div class='absolute z-50 w-full'>-->
    <!--    <el-card shadow='hover'>-->
    <!--      <div class='w-40 mb-2'>-->
    <!--        <el-input-->
    <!--          v-model='search'-->
    <!--          :placeholder='data.Language.search'-->
    <!--          :suffix-icon='Search'-->
    <!--          @change='handleSearchChanged'-->
    <!--        />-->
    <!--      </div>-->
    <!--      <el-table ref='multipleTableRef' :data='data.tableData' border height='200px' highlight-current-row-->
    <!--                style='width: 100%'-->
    <!--                table-layout='fixed' @selection-change='handleSelectionChange'>-->
    <!--        <el-table-column type='selection' width='55' />-->
    <!--        <el-table-column :label='data.Language.i_employee_name' prop='i_employee_name' />-->
    <!--        <el-table-column :label='data.Language.i_employee_pinyin' prop='i_employee_pinyin' />-->
    <!--        <el-table-column :label='data.Language.i_dept_no' prop='i_company_name' />-->
    <!--        <el-table-column :label='data.Language.dept' prop='i_dept_name' />-->
    <!--      </el-table>-->
    <!--    </el-card>-->
    <!--  </div>-->
    <!--</div>-->
</template>

<style>
th.no-select-all>.cell {
    display: none !important;
}
</style>