<!-- 编辑弹窗 -->
<template>
    <ele-modal
        form
        :width="520"
        v-model="visible"
        title="用户绑定标签"
        @open="handleOpen"
    >
        <el-checkbox-group v-model="userTag">
            <el-checkbox
                v-for="item in userTagData"
                :label="item.tagName"
                :value="item.id"
                :key="item.id"
            />
        </el-checkbox-group>

        <template #footer>
            <el-button @click="handleCancel">关闭</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="loading"
                >确定</el-button
            >
        </template>
    </ele-modal>
</template>

<script setup>
    import { ref, reactive, nextTick } from 'vue';
    import { ElMessage } from 'element-plus';
    import request from '@/utils/request';

    /** 弹窗是否打开 */
    const visible = ref(false);
    const loading = ref(false);

    const userTag = ref([]);

    /** 关闭弹窗 */
    const handleCancel = () => {
        visible.value = false;
    };

    /** 弹窗打开事件 */
    const userId = ref('');
    const handleOpen = (row) => {
        visible.value = true;
        nextTick(() => {
            if (row && row.userId) {
                userId.value = row.userId;
                getUserTagList(row.userId);
            }
        });
    };

    const userTagData = ref([]);
    //获取用户标签数据
    const getUserTagList = (userId) => {
        if (!userId) return;
        request.get(`/user/tag/getMyBingTag/${userId}`).then((res) => {
            if (res.data.code == 200) {
                userTagData.value = res.data.data;
                userTag.value = userTagData.value
                    .filter((item) => item.bind)
                    .map((item) => item.id);
            }
        });
    };

    const emit = defineEmits(['success']);
    /** 提交 */
    const handleSubmit = () => {
        if (userTag.value.length == 0)
            return ElMessage.warning('请选择用户标签');
        loading.value = true;
        request
            .post('/user/tag/bind', {
                userId: userId.value,
                tagIdList: userTag.value
            })
            .then((res) => {
                loading.value = false;
                if (res.data.code == 200) {
                    handleCancel();
                    emit('success');
                } else {
                    ElMessage.error(res.data.msg);
                }
            });
    };

    defineExpose({
        handleOpen
    });
</script>
