<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 { useDataTable, useDataFilter } from '@/hooks/datatable'
import { queryTHJFriends, queryInvestorLevelGroup } from '@/services/api/common'
import { useLoginStore, useUserStore } 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 { getUserId } = useLoginStore()
const { getAccountName } = useUserStore()
const { dataList, total, pageIndex, pageSize } = useDataTable<Model.THJFriendsRsp>()
const { filterOptons, getQueryParams } = useDataFilter<Model.THJFriendsReq>()
const loading = shallowRef(false)
const treeRef = shallowRef<InstanceType<typeof ElTree>>()
const filterText = shallowRef('')
const userId = shallowRef(getUserId()) // 当前用户ID

const treeList = reactive<TreeData[]>([{
    label: getAccountName() ?? '登录用户',
    userid: userId.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: '开户时间' },
])

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 (userId.value == getUserId()) {
        return phoneNumber
    }
    const reg = /^(\d{3})\d{4}(\d{4})$/
    return phoneNumber?.replace(reg, '$1****$2')
}

const getTHJFriends = (params: Partial<Model.THJFriendsReq> = {}) => {
    loading.value = true
    return queryTHJFriends({
        data: {
            userid: userId.value,
            page: pageIndex.value,
            pagesize: pageSize.value,
            ...params
        },
        success: (res) => {
            total.value = res.total
            dataList.value = res.data

            if (treeList[0].children?.length === 0) {
                treeList[0].children = res.data.map((e) => ({
                    label: e.customername,
                    userid: e.frienduserid,
                }))
            }
        },
        complete: () => {
            loading.value = false
        }
    })
}

// 当节点被点击的时候触发
const onNodeClick = ({ userid }: TreeData) => {
    if (userId.value !== userid) {
        userId.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
        getTHJFriends(qs)
    }, clear)
}

const onRefresh = () => {
    getQueryParams((qs) => {
        getTHJFriends(qs).catch((err) => ElMessage.error(err))
    })
}

queryInvestorLevelGroup({
    success: (res) => {
        const [levelGroups] = filterOptons.selectList
        levelGroups.options = res.data.map((e) => ({
            label: e.groupname,
            value: e.levelgroupid
        }))
    }
})
onRefresh()
watch(filterText, (val) => {
    treeRef.value?.filter(val)
})
</script>

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