<template>
    <el-dialog :modal="true" :close-on-click-modal="false" :close-on-press-escape="false" title="选择标签"
        :append-to-body="true" :visible.sync="visible" width="40%" :before-close="handleClose"
        custom-class="inner-dialog">
        <div>
            <div class="flex gap-2">
                <el-tag v-for="(tag) in dynamicTags" :color="tag.color" :key="tag.id" closable
                    :disable-transitions="false" @close="handleTagClose(tag)">
                    {{ tag.directoryName }}
                </el-tag>
                <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small"
                    @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
            </div>

            <div class="t-p">
                <el-form :model="libraryData" label-width="auto" class="form-detail-inline">
                    <el-form-item label="标签名">
                        <el-input placeholder="请查找要标注的标签名，按回车键确认"></el-input>
                    </el-form-item>
                </el-form>
            </div>

            <div>
                <el-row :gutter="20" style="justify-content: space-evenly">
                    <el-col :span="8" style="border: 1px solid #dcdfe6">
                        <el-table ref="tableRef" :data="tableData" max-height="700" @select="selectionChange"
                            row-key="id" class="table-new--dialog">
                            <el-table-column type="selection" width="50" align="center" />
                            <el-table-column prop="directoryName" label="父级标签" align="center" />
                        </el-table>
                    </el-col>
                    <el-col :span="14" style="border: 1px solid #dcdfe6">
                        <el-table ref="tagTableRef" :data="tagTableData" max-height="700" @select="tagSelectionChange"
                            :row-key="row => row.id">
                            <el-table-column type="selection" width="50" align="center" :reserve-selection="true" />
                            <el-table-column prop="directoryName" label="标签名称" align="center" />
                        </el-table>
                    </el-col>
                </el-row>
            </div>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="handleCancel">取 消</el-button>
            <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </div>
        <!-- <div class="op-btn">
            <el-button type="primary" @click="saveHandle">确认</el-button>
            <el-button @click="handleClose">取消</el-button>
        </div> -->
    </el-dialog>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { queryMisList, getDirectoryAllLevel } from '@/api/unified-resources/information-system/index.js'

export default {
    props: {
        // dialogVisible: {
        //     type: Boolean,
        //     default: false
        // }
        value: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            visible: this.value,
            dynamicTags: [],
            inputVisible: false,
            inputValue: '',
            tableData: [],
            tagTableData: [],
            libraryData: {},
            selectArr: [],
            selectAllObj: {},
            tagType: ['success', 'info', 'warning', 'danger'],
        };
    },
    computed: {
        ...mapState('projectManage', ['selectTagList', 'selectDutyId']), // 映射 Vuex 状态
    },
    watch: {
        value(newVal) {
            this.visible = newVal;
        },
        visible(newVal) {
            this.$emit("input", newVal);
        },

        selectTagList: {
            handler(newTags) {
                console.log(newTags,'newTags');
                
                if (newTags && Array.isArray(newTags)) {
                    this.dynamicTags = newTags;
                }

            },
            deep: true, // 深入监听
            immediate: true,
        },
    },
    mounted() {
        this.getList();
    },
    methods: {
        ...mapActions('projectManage', ['setRow', 'setSelectTagList', 'setSelectDutyId']), // 映射 Vuex actions

        getList() {
            getDirectoryAllLevel({ type: '标签' }).then(res => {
                if (+res.code === 200) {
                    this.tableData = res.data || [];
                }
            });
        },

        selectionChange(selection, row) {
            const tagArr = this.$refs.tagTableRef.selection
            const keyValue = tagArr[0]?.directoryName;
            if (keyValue) {
                this.selectAllObj[keyValue] = tagArr;
            }

            let selectIds = [];
            for (const key in this.selectAllObj) {
                if (row.directoryName === key) {
                    this.selectAllObj[key].forEach(element => {
                        selectIds.push(element.id);
                    });
                }
            }

            this.tagTableData.forEach(item => {
                if (selectIds.includes(item.id)) {
                    this.$nextTick(() => {
                        this.$refs.tagTableRef.toggleRowSelection(item, true);
                    });
                }
            });

            this.$refs.tableRef.clearSelection();
            this.$refs.tableRef.toggleRowSelection(row, true);
            if (this.selectArr.length === 0) {
                this.$refs.tableRef.toggleRowSelection(row, true);
            } else {
                if (this.selectArr[0].directoryName === row.directoryName) {
                    this.$refs.tableRef.toggleRowSelection(row, false);
                } else {
                    this.$refs.tableRef.toggleRowSelection(row, true);
                }
            }

            this.selectArr = this.$refs.tagTableRef.selection
            this.tagTableData = row.list;
        },

        tagSelectionChange(newSelection, row) {
            console.log(newSelection,'newSelection');
            
            // 确保 dynamicTags 是一个数组
            const selectIds = newSelection.map(item => item.id);
            if (!selectIds.includes(row.id)) {
                this.dynamicTags = this.dynamicTags.filter(item => item.id !== row.id);
            } else {
                if (!this.dynamicTags.some(item => item.id === row.id)) {
                    this.dynamicTags.push(row);
                } else {
                    ElMessage.error('标签已存在');
                    this.$refs.tagTableRef.toggleRowSelection(row, false);
                    return;
                }
            }

            const groupedData = newSelection.reduce((accumulator, item) => {
                if (!accumulator[item.oneLabel]) {
                    accumulator[item.oneLabel] = [];
                }
                accumulator[item.oneLabel].push(item);
                return accumulator;
            }, {});

            const arraysByKey = Object.values(groupedData);
            console.log(arraysByKey,'arraysByKey');
            
            this.selectAllObj = arraysByKey.reduce((newObject, array) => {
                array.forEach(item => {
                    if (!newObject[item.oneLabel]) {
                        newObject[item.oneLabel] = [];
                    }
                    newObject[item.oneLabel].push(item);
                });
                return newObject;
            }, {});
            console.log( this.selectAllObj,' this.selectAllObj');
            
        },

        handleConfirm() {
            this.setSelectTagList(this.dynamicTags);
            this.$emit('saveHandle', { dynamicTags: this.dynamicTags, column1: this.selectAllObj });
            this.handleClose();
        },

        handleClose() {
            this.visible = false;
            this.$emit("cancel"); // 可以在父组件监听 'cancel' 事件
        },

        handleInputConfirm() {
            if (this.inputValue) {
                this.dynamicTags.push({ directoryName: this.inputValue, color: 'blue' });
            }
            this.inputVisible = false;
            this.inputValue = '';
        },

        handleTagClose(tag) {
            this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
        },
        // 取消按钮处理方法
        handleCancel() {
            this.visible = false;
            this.$emit("cancel"); // 可以在父组件监听 'cancel' 事件
        },
    }
};
</script>

<style scoped lang="scss">
.op-btn {
    text-align: center;
    margin-top: 15px;
}

.other-form {
    .el-form-item {
        width: 27%;
    }
}

.two-form {
    .el-form-item {
        width: 47%;
    }
}

.w100 {
    width: 100% !important;
}

.flex {
    display: flex;
    align-items: center;
}

.t-b {
    font-size: 18px;
    margin-bottom: 20px;
}

.t-p {
    font-size: 15px;
    margin: 20px 0;
}

.list {
    display: flex;
    justify-content: center;

    table {
        width: 100%;
        border-collapse: collapse;
        font-size: 12px;
        color: #606266;

        td,
        thead {
            padding: 0 10px;
            width: 177px;
            height: 34px;
            line-height: 34px;
            border: 1px solid #e4e4e4;
            box-sizing: border-box;
        }

        thead {
            text-align: center;
        }

        .one-td {
            border-top: none;
        }
    }

    .arrowList {
        td {
            border: 0 !important;
            text-align: center;
        }

        tbody {
            border: 0 !important;
        }
    }
}

.el-tag {
    margin-left: 10px;
}

.bg1 {
    background: #f0f8ff;
}

.bg2 {
    background: #e6e6fa;
}

.one-form {
    .el-form-item {
        width: 87%;
    }
}

.w-20 {
    width: 43px;
}
</style>