<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.nickname" placeholder="请输入昵称" style="width: 200px; margin-right: 12px;"></el-input>
            <el-button type="primary" icon="Search" @click="search">查询</el-button>
            <el-button type="primary" icon="Finished" @click="selectionSend">批量发送消息</el-button>
            <el-button type="danger" icon="Delete" @click="selectionDelete">批量删除</el-button>
            <el-button type="primary" @click="handleSync" style="float: right" :class="{ 'no-click': loading }">
                <!-- <el-icon v-if="loading" class="mht-loading" style="margin-right: 4px;">
                    <Loading />
                </el-icon> -->
                <el-icon :class="{'mht-loading': loading}" style="margin-right: 4px;">
                    <Refresh></Refresh>
                </el-icon>
                同步联系人
            </el-button>
        </el-card>
        <el-card class="table-card">
            <div class="table-card-center">
                <div class="table-box">
                    <el-table :data="userTable" style="width: 100%" max-height="calc(100vh - 285px)"
                        @selection-change="handleSelectionChange" row-key="user_id">
                        <template #empty>
                            <span v-if="tableLoading">加载中...</span>
                            <span v-if="!tableLoading && query.robot_id">暂无数据</span>
                            <span v-if="!query.robot_id && !tableLoading" style="font-weight: bold;">请选择一个机器人</span>
                        </template>
                        <el-table-column type="selection" width="55" :reserve-selection="true" />
                        <el-table-column prop="avatar" label="头像" align="center">
                            <template #default="scoped">
                                <el-image style="width: 30px;display: block;margin: auto;border-radius: 4px;"
                                    :src="scoped.row.avatar" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="nickname" label="昵称" />
                        <el-table-column prop="realname" label="姓名" />
                        <el-table-column prop="sex" label="性别" align="center" />
                        <el-table-column prop="remark_phone_1" label="电话" align="center" min-width="110">
                            <template #default="scoped">
                                <span class="user-phone" v-if="!scoped.row.remark_phone_2">{{ scoped.row.remark_phone_1
                                    }}</span>
                                <el-popover placement="bottom-start" title="" :width="200" trigger="hover">
                                    <template #reference>
                                        <span class="user-phone" v-if="scoped.row.remark_phone_2">{{
                                            scoped.row.remark_phone_1 }}</span>
                                    </template>
                                    <ul class="phone-list">
                                        <li>{{ scoped.row.remark_phone_2 }}</li>
                                        <li>{{ scoped.row.remark_phone_3 }}</li>
                                        <li>{{ scoped.row.remark_phone_4 }}</li>
                                        <li>{{ scoped.row.remark_phone_5 }}</li>
                                    </ul>
                                </el-popover>
                            </template>
                        </el-table-column>
                        <el-table-column prop="" label="标签" min-width="180">
                            <template #default="scoped">
                                <el-tag v-show="scoped.row.tags != ''" v-for="item in scoped.row.tags?.split(',')" style="margin-right: 5px;margin-bottom: 3px;margin-top: 3px;">{{item}}</el-tag>

                                <el-icon style="color: var(--el-color-primary); cursor: pointer;font-size: 16px;transform: translateY(4px);margin-left: 5px;">
                                    <svg class="icon" aria-hidden="true" @click="addTag(scoped.row)">
                                        <use xlink:href="#icon-tianjiabiaoqian1"></use>
                                    </svg>
                                </el-icon>
                               
                            </template>
                        </el-table-column>
                        
                        <el-table-column prop="real_remarks" label="备注" min-width="120" />
                        <el-table-column prop="remarks" label="描述" />
                        <!-- <el-table-column prop="ext_field1_timestamp" label="手术时间" align="center"
                            min-width="160"></el-table-column> -->
                        <el-table-column prop="create_time" label="添加时间" align="center"
                            min-width="160"></el-table-column>
                            <el-table-column prop="is_deleted_me" label="是否被删除" align="center" min-width="100">
                            <template #default="scoped">
                                <span>{{ scoped.row.is_deleted_me == 1 ? '是' : '否' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="sync_time" label="同步时间" align="center" min-width="160" />
                        
                        
                        <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)">
                                            <svg class="icon" aria-hidden="true">
                                                <use xlink:href="#icon-xiangqingye-43"></use>
                                            </svg>
                                        </el-icon>
                                    </el-tooltip>
                                    <el-tooltip class="box-item" effect="dark" content="发送消息" placement="bottom">
                                        <el-icon @click="handleSend(scoped.row)">
                                            <svg class="icon" aria-hidden="true">
                                                <use xlink:href="#icon-fasong"></use>
                                            </svg>
                                        </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="发送消息" width="1000px" align-center destroy-on-close>
            <div class="dialog-box">
                <div class="send-user">
                    <span>发送给：</span>
                    <el-image v-if="allUserlist.length == 0" :src="ruleForm.avatar"></el-image>
                    <el-image v-if="allUserlist.length > 0" :src="item.avatar" v-for="item in selectList"></el-image>
                </div>
                <UserMessage :messageMain="ruleForm" :allUserIds="allUserlist" @hideMessage="hideMessage"></UserMessage>

            </div>

        </el-dialog>
        <el-dialog v-model="dialogTag" title="设置客户标签" width="1000px" align-center destroy-on-close>
            <div class="dialog-box">

                <TagClass :initialSelectedTags="tags" :robot_id="robot_id" @change="selectedTags" :is_user="true"></TagClass>

            </div>
            <template #footer>
                <el-button type="primary" @click="saveTag" :class="{ 'no-click': saveLoading }">
                    <el-icon v-if="saveLoading" class="mht-loading" style="margin-right: 4px;">
                        <Loading></Loading>
                    </el-icon>
                    确 定</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, nextTick, watch, onActivated } from 'vue'
import { userList, syncUser, deleteUser } from '@/api/user'
import { robotList } from '@/api/robot'
import { userBindTag } from '@/api/tags'
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'
import TagClass from '@/components/TagClass/indexUser.vue'
defineOptions({
  name: "user",
});
const detailInfo = detailStore()

const userRobotStore = robotStore()
const router = useRouter()
const dialogVisible = ref(false)
const query = reactive({
    nickname: '',
    page: 1,
    page_size: 20
})
const robot_id = ref('')
const userTable = 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 userList({ robot_id: robot_id.value, ...query })
    tableLoading.value = false
    userTable.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 handleSync = async () => {
    if (!robot_id.value) {
        ElNotification({
            type: 'warning',
            message: '请选择机器人'
        })
    } else {
        try {
            loading.value = true
            await syncUser({
                robot_id: robot_id.value
            })
            loading.value = false
            ElNotification({
                type: 'success',
                message: '同步成功'
            })
            query.page = 1
            getTable()
        } catch (err) {
            loading.value = false
        }

    }
}
const allUserlist = ref('')
const handleSend = (row) => {
    dialogVisible.value = true
    allUserlist.value = ''
    ruleForm.value = row

}

let allUser_ids = []

const selectionSend = () => {
    if (allUser_ids.length == 0) {
        ElNotification({
            type: 'warning',
            message: '请选择列表用户'
        })
        return
    }
    allUserlist.value = allUser_ids.join(',')
    dialogVisible.value = true
}
// 多选
const selectList = ref([])
const handleSelectionChange = (e) => {
    selectList.value = e
    allUser_ids = e.map((el) => {
        return el.user_id
    })
}
const hideMessage = (e) => {
    dialogVisible.value = false
}
const toDetail = (e) => {
    detailInfo.userDetails = {is_friend: true, ...e}
    router.push('/userDetails')
}
const handeleDelete = async (row) => {

    ElMessageBox.confirm(
        '确认移除该好友吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            await deleteUser({
                robot_id: robot_id.value,
                sleep_max_second: 0,
                user_id: row.user_id
            })
            ElNotification({
                type: 'success',
                message: '操作成功'
            })
            query.page = 1
            getTable()
        })
        .catch(() => {

        })
}
const selectionDelete = () => {
    if (allUser_ids.length == 0) {
        ElNotification({
            type: 'warning',
            message: '请选好友列表'
        })
        return
    }
    ElMessageBox.confirm(
        '确认批量移除好友吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {

            await deleteUser({
                robot_id: robot_id.value,
                sleep_max_second: 5,
                user_id: allUser_ids.join(',')
            })
            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()
}


// 添加标签
const dialogTag = ref(false)
const tags = ref([])
const user_row = ref({})
const addTag = (row) => {
    dialogTag.value = true
    user_row.value = row
    if(row.tags){
        const tag_names = row.tags?.split(',')
        const tag_ids = row.tags_id?.split(',')
        tags.value = tag_names.map((name, index) => ({
            name: name,
            id: tag_ids[index]
        }))
    } else{
        tags.value = []
    }

}
let selected_tags = []
const selectedTags = (e) => {
    selected_tags = e
}
const saveLoading = ref(false)
const saveTag = async () => {
    
    if(selected_tags.length > 0){
        saveLoading.value = true
        const tag_list = selected_tags.map((el) => {
            return {
                tag_group_id: el.tag_group_id,
                tag_id: el.id,
            }
        })
        userBindTag({
            robot_id: robot_id.value,
            tag_list: tag_list,
            user_list: [user_row.value.user_id]
        }).then((res) => {
            saveLoading.value = false
            dialogTag.value = false
            ElNotification({
                type: 'success',
                message: '操作成功'
            })
            getTable()
        })
    } else {
        if(tags.value.length > 0){
            ElMessageBox.confirm(
        '您删除了该用户的所有标签，是否确认?',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            userBindTag({
                robot_id: robot_id.value,
                tag_list: [],
                user_list: [user_row.value.user_id]
            }).then((res) => {
                saveLoading.value = false
                dialogTag.value = false
                ElNotification({
                    type: 'success',
                    message: '操作成功'
                })
                getTable()
            })
        })
        } else {
            dialogTag.value = false
        }
    }
        
}

onMounted(() => {
    // if (userRobotStore.robotInfo.id) {
    //     getTable()
    // }
    getRobotList()
})
onActivated(() => {
    if(robot_id.id != '' && query.nickname != ''){
        query.nickname = ''
        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>