<template>
    <div>
        <!-- 穿梭框 -->
        <div>
            <el-dialog v-model="transferModals" title="分享" width="40%" :close-on-click-modal="false">
                <div class="transBox">
                    <div class="allBag">
                        <el-input style="width: 220px;margin-left: 18px;margin-top:5px" v-model="allBag"
                            placeholder="搜索"></el-input>
                        <div class="allLog">
                            <el-tree ref="treeRef" :data="allTreeData" :props="allTreeProps" show-checkbox node-key="id"
                                :default-expanded-keys="openTree" @check-change="allTreeChange"
                                :default-checked-keys="backScreen" :check-strictly="true" />
                        </div>
                    </div>
                    <div class="needBag">
                        <div style="border-bottom: 1px solid gray;">
                            <span>已选择{{ chooseTagData.length }}人</span>
                            <span style="color: red;font-size: 14px;float: right;">清空</span>
                        </div>
                        <div class="needLog">
                            <el-tag v-for="(item, index) in chooseTagData" :key="index" class="tagtag"
                                :closable="lastPeople" @close="handleClose(item)">
                                {{ item.userName }}
                            </el-tag>
                        </div>
                    </div>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="backToFather">取消</el-button>
                        <el-button type="primary" @click="sureShare">
                            确定
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import { ref, onMounted, toRef } from 'vue';
import userTree from '../../../api/user/userTree';
import fileShare from '../../../api/fileShare/fileShare';
import fileCount from '../../../api/fileCount/fileCount'
import { ElMessage } from 'element-plus'
export default {
    props: {
        thanks: {
            type: Boolean,
            required: true
        },
        clickRowId: {
            type: Number,
            required: true
        },
        workOrEdit: {
            type: Number,
            required: true
        },
        isNewMenu:{
            type: Boolean,
            required: true
        },
    },
    setup(props, { emit }) {
        let { backToFather, sureBackFather } = toRefs(props)
        let result = props.thanks
        let dees = props.clickRowId
        let feeh = props.workOrEdit
        let isNewMenus = props.isNewMenu
        let transferModals = ref(false)
        let allTreeData = ref([])
        let allTreeProps = {
            label: 'label',
            children: 'children',
            disabled: false,
            id: "id"
        }
        let openTree = ref([])
        let chooseTagData = ref([])
        let allBag = ref('')
        let needTagData = ref([])
        let backScreen = ref([])
        let lastPeople = ref(false)
        function allTeam() {
            if (result) {
                transferModals.value = result
            }
        }
        // 分享穿梭框
        function allTreeChange(e) {
            const id = e.id;
            const label = e.label;
            // 查找是否已经存在相同 userId 的数据的索引
            const existingIndex = chooseTagData.value.findIndex(item => item.userId === id);
            if (existingIndex !== -1) {
                // 如果已存在，删除该项
                chooseTagData.value.splice(existingIndex, 1);
            } else {
                // 选择操作，将数据添加到 needTagData 中
                chooseTagData.value.push({ userId: id, userName: label });
            }
            if (chooseTagData.value.length === 1) {
                lastPeople.value = true
            } else {
                lastPeople.value = false
            }
        }
        // 确认分享
        function sureShare() {
            if (feeh === 1) {
                if (chooseTagData.value.length === 0) {
                    ElMessage({
                        type: "error",
                        message: "你还未选择人员！"
                    })
                } else {
                    console.log(chooseTagData.value, 'value');
                    let arr = []
                    arr = chooseTagData.value.map(item => {
                        return item.userId
                    })
                    fileShare.addSharePeople(dees, arr).then(res => {
                        if (res.code === 200) {
                            ElMessage({
                                message: "分享成功",
                                type: "success"
                            })
                            transferModals.value = false
                            emit("getCback", transferModals.value)
                        }
                    })
                }
            } else {
                if (chooseTagData.value.length === 0) {
                    ElMessage({
                        type: "error",
                        message: "你还未选择人员！"
                    })
                } else {
                    let arr = []
                    arr = chooseTagData.value.map(item => {
                        return item.userId
                    })
                    fileCount.addActor(dees, arr).then(res => {
                        if (res.code === 200) {
                            ElMessage({
                                message: "提醒人员成功",
                                type: "success"
                            })
                            transferModals.value = false
                            emit("getCback", transferModals.value)
                        }
                    })
                }
            }

        }
        // 获取用户树
        function getAllUser() {
            console.log('isNewMenu', props.clickRowId)
            userTree.getUserTree({}).then(res => {
                allTreeData.value = [res]
                userTree.getUserTree({}).then(res => {
                    allTreeData.value = [res];
                    // 递归函数来获取所有节点的 id
                    function getAllNodeIds(nodes) {
                        nodes.forEach(node => {
                            openTree.value.push(node.id);
                            if (node.children && node.children.length > 0) {
                                getAllNodeIds(node.children);
                            }
                        });
                    }
                    // 调用递归函数获取所有节点的 id
                    getAllNodeIds(allTreeData.value);
                });
            })
            if (feeh === 1) {
                fileShare.getSharePeople(dees).then(res => {
                    // 去除数组内部的重复元素
                    const uniqueRes = Array.from(new Set(res.map(item => item.userName))).map(id => res.find(item => item.userName === id));
                    // 现在的 uniqueRes 数组不包含重复元素
                    chooseTagData.value = uniqueRes;
                    backScreen.value = chooseTagData.value.map(item => {
                        return item.userId
                    })
                })
            } else if(!isNewMenus){   
                fileCount.getActor(dees).then(res => {
                    console.log(res, 'count');
                })
            }

        }
        function getBack() {
            transferModals.value = false
            emit("getCback", transferModals.value)
        }
        function handleClose(tag) {
            chooseTagData.value.splice(chooseTagData.value.indexOf(tag), 1);
            // 从标签中获取 userId
            // const userId = tag.userId;
            // 从 chooseTagData 中筛选出不包含当前 userId 的标签
            // chooseTagData.value = chooseTagData.value.filter(item => item.userId !== userId)

        }
        onMounted(() => {
            console.log(feeh, 'eeh');
            allTeam()
            getAllUser()
        })
        return {
            transferModals,
            allTreeData,
            allTreeProps,
            openTree,
            chooseTagData,
            allTreeChange,
            sureShare,
            allBag,
            getAllUser,
            result,
            allTeam,
            dees,
            needTagData,
            handleClose,
            backScreen,
            lastPeople,
            feeh,
            backToFather: getBack,
        }
    }
}
</script>

<style scoped>
.transBox {
    width: 550px;
    height: 400px;
    margin: 0 auto;
    display: flex;
    justify-content: space-around;
    align-items: center;
    /* border: 1px solid black; */
}

.tagtag {
    display: flex;
    justify-content: space-between;
    align-items: center;
    text-align: start;
    width: 230px;
    margin: 0 auto;
}

.allBag {
    width: 255px;
    height: 380px;
    border: 1px solid green;
}

.needBag {
    width: 255px;
    height: 380px;
    border: 1px solid green;
}

.allLog {
    width: 245px;
    height: 330px;
    margin: 5px auto;
    /* border: 1px solid red; */
    overflow-y: auto;
}

:deep(.el-tag__content) {
    display: block;
}

:deep(.el-icon el-tag__close) {
    display: block;
}
</style>