<template>
    <div class="user-container">
        <el-card class="search">
            <el-select-v2 style="width: 200px;margin-right: 10px;" v-model="robot_id" popper-class="costom-select"
                :options="robotCards" placeholder="请选择机器人" :props="v2props" filterable @change="changeRobot">
                <template #default="{ item }">
                    <div class="costom-select-item">
                        <el-image :src="item.head_url"></el-image>
                        <span>{{ item.name }}</span>
                    </div>
                </template>
                <template #footer v-if="robotTotal > 100">
                    <el-pagination v-model:current-page="queryRobot.page" :page-size="queryRobot.page_size" size="small"
                        background layout="prev, pager, next" :total="robotTotal" class="mt-4"
                        @current-change="currentChange" />
                </template>
            </el-select-v2>
            <el-input v-model="query.name" placeholder="请输入关键字" style="width: 200px; margin-right: 12px;"></el-input>
            <el-button type="primary" icon="Search" @click="search">查询</el-button>
            <!-- <el-button type="danger" icon="Delete" @click="selectionDelete">批量删除</el-button> -->
            <el-button type="primary" @click="handeleAddGroup" style="float: right" >
               
                <el-icon style="margin-right: 4px;">
                    <Plus></Plus>
                </el-icon>
                新增标签组
            </el-button>
        </el-card>
        <el-card class="table-card">
            <div class="table-card-center">
                <div class="table-box">
                    
                    <el-table :data="tabGroups" style="width: 100%" max-height="calc(100vh - 285px)" row-key="id" @expand-change="exhandleChange">
                        <template #empty>
                            <span v-if="tableLoading">加载中...</span>
                            <span v-if="!tableLoading && robot_id">暂无数据</span>
                            <span v-if="!robot_id && !tableLoading" style="font-weight: bold;">请选择一个机器人</span>
                        </template>
                        
                        
                        <el-table-column prop="name" label="标签组名称" />
                        <el-table-column prop="description" label="描述" />
                        <el-table-column prop="created_at" label="创建时间" />
                        
                        
                        
                        <el-table-column prop="" label="操作" width="100" align="center" fixed="right">
                            <template #default="scoped">
                                <div class="mht-operations">
                                    <el-tooltip class="box-item" effect="dark" content="子标签" placement="bottom">
                                        <el-icon @click="toDetail(scoped.row)"><document /></el-icon>
                                  
      
                                    </el-tooltip>
                                    <el-tooltip class="box-item" effect="dark" content="编辑" placement="bottom">
                                        <el-icon @click="handleEdit(scoped.row)">
                                            <Edit />
                                        </el-icon>
                                    </el-tooltip>
                                    <el-tooltip class="box-item" effect="dark" content="删除" placement="bottom">
                                        <el-icon class="el-icon-danger" @click="handeleDelete(scoped.row)">
                                            <Delete />
                                        </el-icon>
                                    </el-tooltip>
                                </div>

                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="pagination-box">
                    <el-pagination v-model:current-page="query.page" v-model:page-size="query.page_size"
                        :page-sizes="[20, 30, 40, 50]" :size="query.page_size" background
                        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
        </el-card>
        <el-dialog v-model="dialogVisible" :title="dialogGroupTitle" width="600px" align-center destroy-on-close>
            <div class="dialog-box">
               <el-form :model="groupForm" :rules="groupRule" ref="groupFormRef">
                    <el-form-item label="标签组名称" prop="name">
                        <el-input v-model="groupForm.name" placeholder="请输入标签组名称" />
                    </el-form-item>
                    <el-form-item label="标签组描述">
                        <el-input type="textarea" v-model="groupForm.description" placeholder="请输入标签组描述" />
                    </el-form-item>

               </el-form>

            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="groupFormSubmit" :class="{ 'no-click': submitGrouploading }">
                        <el-icon v-if="submitGrouploading" class="mht-loading" style="margin-right: 4px;">
                            <Loading />
                        </el-icon>
                        <el-icon v-else style="margin-right: 4px;">
                            <svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-baocun"></use>
                            </svg>
                        </el-icon>
                        保 存
                    
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch, onActivated } from 'vue'
import { tagGroupList, addTagGroup, deleteTagGroup, upTagGroup, tagList, addTag, deleteTag, upTag } from '@/api/tags'
import { robotList } from '@/api/robot'
import { ElNotification } from 'element-plus';
import UserMessage from '@/components/UserMessage/index.vue'
import robotStore from '@/store/modules/robotStore'
import { useRouter } from 'vue-router';
import detailStore from '@/store/modules/detailStore'
defineOptions({
  name: "user",
});
const detailInfo = detailStore()

const userRobotStore = robotStore()
const router = useRouter()
const dialogVisible = ref(false)
const query = reactive({
    name: '',
    page: 1,
    page_size: 20
})
const robot_id = ref('')
const tabGroups = ref([])
const robotCards = ref([])
const total = ref(0)
const ruleForm = ref({})
const tableLoading = ref(false)
const getTable = async () => {
    // if (!userRobotStore.robotInfo.id) {
    //     ElNotification({
    //         type: 'warning',
    //         message: '请在机器人页面选择机器人！'
    //     })
    //     return
    // }
    tableLoading.value = true
    const res = await tagGroupList({ robot_id: robot_id.value, ...query })
    tableLoading.value = false
    tabGroups.value = res.list
    total.value = res.total
}

const search = () => {
    if (!robot_id.value) {
        ElNotification({
            type: 'warning',
            message: '请选择机器人！'
        })
    } else {
        query.page = 1
        getTable() 
    }
    
}

const handleSizeChange = (e) => {
    query.page = 1
    query.page_size = e
    getTable()
}
const handleCurrentChange = (e) => {
    query.page = e
    getTable()
}
const loading = ref(false)






const handeleDelete = async (row) => {

    ElMessageBox.confirm(
        '确认删除该标签组吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            await deleteTagGroup(row.id)
            ElNotification({
                type: 'success',
                message: '操作成功'
            })
            query.page = 1
            getTable()
        })
        .catch(() => {

        })
}

const v2props = ref({
    value: 'id',
    label: 'name'
})
const queryRobot = ref({
    page: 1,
    page_size: 100
})
const robotTotal = ref(0)
const getRobotList = async () => {
    const res = await robotList(queryRobot.value)
    robotCards.value = res.list
    robotTotal.value = res.total
}
const changeRobot = (e) => {
    robotCards.value.forEach(item => {
        if (item.id == e) {
            userRobotStore.robotInfo = item
        }
    })
    query.page = 1
    getTable()
}
const currentChange = (e) => {
    queryRobot.value.page = e
    getRobotList()
}

// 标签组操作
// 标签组表单
let tagGroup_id = ''
const dialogGroupTitle = ref('')
const handeleAddGroup = () => {
    tagGroup_id = ''
    dialogGroupTitle.value = '新增标签组'
    if (!robot_id.value) {
        ElNotification({
            type: 'warning',
            message: '请选择机器人！'
        })
    } else {
        dialogVisible.value = true
        groupForm.value.name = ''
        groupForm.value.description = ''
    }
    
}
const groupForm = ref({
    name: '',
    description: ''
})
const groupRule = ref({
    name: [{ required: true, message: '请输入标签组名称', trigger: 'blur' }],
})
const groupFormRef = ref()

const submitGrouploading = ref(false)
const groupFormSubmit = () => {
    groupFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                submitGrouploading.value = true
                if (tagGroup_id) {
                    await upTagGroup({...groupForm.value, robot_id: robot_id.value}, tagGroup_id)
                    ElNotification({
                        type: 'success',
                        message: '更新成功'
                    })
                    dialogVisible.value = false
                    submitGrouploading.value = false
                    groupForm.value.name = ''
                    groupForm.value.description = ''
                    getTable()
                } else {
                    await addTagGroup({...groupForm.value, robot_id: robot_id.value})
                    ElNotification({
                        type: 'success',
                        message: '新增成功'
                    })
                    dialogVisible.value = false
                    submitGrouploading.value = false
                    groupForm.value.name = ''
                    groupForm.value.description = ''
                    query.page = 1
                    getTable()
                }
            } catch (err) {
                
                submitGrouploading.value = false
            }
        }
    })
}

const handleEdit = (row) => {
    tagGroup_id = row.id
    dialogGroupTitle.value = '编辑标签组'
    groupForm.value.name = row.name
    groupForm.value.description = row.description
    dialogVisible.value = true
}



const exhandleChange = (a, b) => {
    console.log(a, b.length)
}

const toDetail = (row) => {
    router.push({
        path: '/tagChildren',
        query: {
            robot_id: robot_id.value,
            tag_group_id: row.id
        }
    })
}

onMounted(() => {
  
    getRobotList()
})
onActivated(() => {
    if (robot_id.value != '' && query.name != '') {
        query.name = ''
        getTable()
    }
})
</script>
<style lang="scss" scoped>
.user-container {
    padding: var(--el-main-padding);

    // height: 100%;
    .el-card {
        background-color: var(--el-bg-color);
    }

    .table-card {
        margin-top: 20px;

        .table-card-center {
            height: calc(100vh - 232px);
        }

        .table-box {
            height: calc(100% - 60px);
        }
    }

    .pagination-box {
        overflow: hidden;
        margin-top: 25px;
        text-align: right;

        .el-pagination {
            float: right;
        }
    }

    .operations {
        font-size: 14px;
        // color: var(--el-color-primary);
        cursor: pointer;

        .el-icon {
            position: relative;
            top: 2px;
        }

        &:hover {
            color: var(--el-color-primary);
        }
    }

    .user-phone {
        color: var(--el-color-primary);
        cursor: pointer;

    }

    .send-user {
        overflow: hidden;
        line-height: 30px;

        span {
            float: left;
        }

        .el-image {
            float: left;
            width: 30px;
            height: 30px;
            border-radius: 6px;
            margin-bottom: 10px;
            margin-right: 12px;
        }

    }

}
</style>