<!-- 好友查询 -->
<template>
    <el-container class="member">
        <el-aside>
            <el-scrollbar>
                <app-view>
                    <template #header>
                        <el-input v-model="filterText" placeholder="请输入好友" />
                    </template>
                    <el-tree ref="treeRef" :data="treeList" :filter-node-method="filterNode" :expand-on-click-node="false"
                        highlight-current default-expand-all @node-click="onNodeClick" />
                </app-view>
            </el-scrollbar>
        </el-aside>
        <el-main>
            <el-scrollbar>
                <app-view>
                    <template #header>
                        <app-filter :options="filterOptons" :loading="loading" />
                    </template>
                    <!-- 表格数据 -->
                    <app-table :data="dataList" v-model:columns="tableColumns" :loading="loading">
                        <!-- 手机号 -->
                        <template #mobile="{ value }">
                            {{ getPhoneNumber(value) }}
                        </template>
                        <!-- 是否已实名 -->
                        <template #hasauth="{ value }">
                            {{ getAuthStatusName(value) }}
                        </template>
                        <!-- 开户时间 -->
                        <template #createtime="{ value }">
                            {{ formatDate(value) }}
                        </template>
                        <template #footer>
                            <app-pagination :total="total" v-model:page-size="pageSize" v-model:page-index="pageIndex"
                                @change="onRefresh" />
                        </template>
                    </app-table>
                </app-view>
            </el-scrollbar>
        </el-main>
    </el-container>
</template>

<script lang="ts" setup>
import { shallowRef, reactive, watch } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import { formatDate } from '@/filters'
import { useRequest } from '@/hooks/request'
import { useDataFilter } from '@/hooks/datatable'
import { queryTHJFriends, queryInvestorLevelGroup } from '@/services/api/common'
import { loginStore, userStore } from '@/stores'
import { decryptAES } from '@/utils/websocket/crypto'
import AppTable from '@pc/components/base/table/index.vue'
import AppFilter from '@pc/components/base/table-filter/index.vue'
import AppPagination from '@pc/components/base/pagination/index.vue'

interface TreeData {
    label: string;
    userid: number;
    children?: TreeData[];
}

const { userId } = loginStore.$mapGetters()
const { accountName } = userStore.$mapGetters()
const { filterOptons, getQueryParams } = useDataFilter<Model.THJFriendsReq>()
const treeRef = shallowRef<InstanceType<typeof ElTree>>()
const filterText = shallowRef('')
const selectedId = shallowRef(userId.value) // 当前选中用户ID

const treeList = reactive<TreeData[]>([{
    label: accountName.value ?? '登录用户',
    userid: selectedId.value,
    children: []
}])

const tableColumns = shallowRef<Model.TableColumn[]>([
    { prop: 'customername', label: '好友名称' },
    { prop: 'mobile', label: '手机号' },
    { prop: 'groupname', label: '客户等级' },
    { prop: 'hasauth', label: '是否已实名' },
    { prop: 'accoutstatus', label: '状态' },
    { prop: 'createtime', label: '开户时间' },
])

const { loading, dataList, total, pageIndex, pageSize, run } = useRequest(queryTHJFriends, {
    params: {
        pagesize: 20,
        userid: selectedId.value,
    },
    onSuccess: (res) => {
        if (treeList[0].children?.length === 0) {
            treeList[0].children = res.data.map((e) => ({
                label: e.customername,
                userid: e.frienduserid,
            }))
        }
    },
    onError: (err) => {
        ElMessage.error(err)
    }
})

filterOptons.selectList = [
    {
        label: '等级',
        key: 'levelgroupid',
        options: [],
    },
]

filterOptons.inputList = [
    { label: '名称', keys: ['customername'] },
]

filterOptons.buttonList = [
    { lable: '重置', onClick: () => onSearch(true) },
    { lable: '查询', className: 'el-button--primary', onClick: () => onSearch() }
]

// 获取实名状态
const getAuthStatusName = (status: number) => {
    switch (status) {
        case 1: {
            return '已认证'
        }
        case 2: {
            return '已提交'
        }
        case 3: {
            return '已拒绝'
        }
        default: {
            return '未认证'
        }
    }
}

// 获取手机号码
const getPhoneNumber = (value: string) => {
    const phoneNumber = decryptAES(value)
    if (selectedId.value == userId.value) {
        return phoneNumber
    }
    const reg = /^(\d{3})\d{4}(\d{4})$/
    return phoneNumber?.replace(reg, '$1****$2')
}

// 当节点被点击的时候触发
const onNodeClick = ({ userid }: TreeData) => {
    if (selectedId.value !== userid) {
        selectedId.value = userid
        onSearch()
    }
}

// 过滤树节点
const filterNode = (value: string, data: TreeData) => {
    if (value) {
        return data.label.includes(value)
    }
    return true
}

const onSearch = (clear = false) => {
    getQueryParams((qs) => {
        pageIndex.value = 1
        qs.userid = selectedId.value
        run(qs)
    }, clear)
}

const onRefresh = () => {
    getQueryParams((qs) => {
        qs.userid = selectedId.value
        run(qs)
    })
}

queryInvestorLevelGroup().then((res) => {
    const [levelGroups] = filterOptons.selectList
    levelGroups.options = res.data.map((e) => ({
        label: e.groupname,
        value: e.levelgroupid
    }))
})

watch(filterText, (val) => {
    treeRef.value?.filter(val)
})
</script>

<style lang="less">
@import './index.less';
</style>