<template>
    <div class="app-container">
        <div class="background-color-fff padding-20 border-radius-8px margin-bottom-20">
            <el-form
                :model="queryParams"
                ref="queryRef"
                :inline="true"
                v-show="showSearch"
                label-width="68px"
            >
                <el-form-item label="邀请码" prop="invitationCode">
                    <el-input
                        v-model="queryParams.invitationCode"
                        placeholder="请输入邀请码"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Search" @click="handleRest">重新计算统计</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="team-detail-page" v-if="!loading">
            <!-- 第一行统计卡片 -->
            <div class="stats-section">
                <el-row :gutter="20" class="stats-row">
                    <!-- 团队人数统计 -->
                    <!-- <el-col :xs="12" :sm="6" :md="3">
                        <el-statistic title="直接下级" :value="stats.directCount">
                            <template #prefix>
                                <el-icon><User /></el-icon>
                            </template>
                        </el-statistic>
                    </el-col> -->
                    <el-col :xs="12" :sm="6" :md="3">
                        <el-statistic title="团队总人数" :value="stats.totalCount">
                            <template #prefix>
                                <el-icon><UserFilled /></el-icon>
                            </template>
                        </el-statistic>
                    </el-col>
                    <el-col :xs="12" :sm="6" :md="3">
                        <el-statistic title="今日新增" :value="stats.todayNew">
                            <template #prefix>
                                <el-icon><TrendCharts /></el-icon>
                            </template>
                        </el-statistic>
                    </el-col>
                    <el-col :xs="12" :sm="6" :md="3">
                        <el-statistic title="本月新增" :value="stats.monthNew">
                            <template #prefix>
                                <el-icon><Calendar /></el-icon>
                            </template>
                        </el-statistic>
                    </el-col>

                    <!-- 充值统计 -->
                    <el-col :xs="12" :sm="6" :md="3">
                        <el-statistic
                            title="今日充值"
                            :value="stats.todayRechargeAmount || 0"
                            :precision="2"
                        >
                            <template #prefix>
                                <el-icon><Money /></el-icon>
                            </template>
                            <!-- <template #suffix>元</template> -->
                        </el-statistic>
                    </el-col>
                    <el-col :xs="12" :sm="6" :md="3">
                        <el-statistic
                            title="今日提现"
                            :value="stats.todayWithdrawAmount || 0"
                            :precision="2"
                        >
                            <template #prefix>
                                <el-icon><CreditCard /></el-icon>
                            </template>
                            <!-- <template #suffix>元</template> -->
                        </el-statistic>
                    </el-col>
                    <el-col :xs="12" :sm="6" :md="3">
                        <el-statistic
                            title="本月充值"
                            :value="stats.monthRechargeAmount || 0"
                            :precision="2"
                        >
                            <template #prefix>
                                <el-icon><Coin /></el-icon>
                            </template>
                            <!-- <template #suffix>元</template> -->
                        </el-statistic>
                    </el-col>
                    <el-col :xs="12" :sm="6" :md="3">
                        <el-statistic
                            title="本月提现"
                            :value="stats.monthWithdrawAmount || 0"
                            :precision="2"
                        >
                            <template #prefix>
                                <el-icon><Wallet /></el-icon>
                            </template>
                            <!-- <template #suffix>元</template> -->
                        </el-statistic>
                    </el-col>
                </el-row>
            </div>

            <!-- 第二行统计卡片 -->
            <div class="stats-section" style="margin-top: 20px">
                <el-row :gutter="20" class="stats-row">
                    <!-- 总充值提现统计 -->
                    <el-col :xs="12" :sm="6" :md="4">
                        <el-statistic
                            title="团队总充值"
                            :value="stats.totalRechargeAmount || 0"
                            :precision="2"
                        >
                            <template #prefix>
                                <el-icon><Odometer /></el-icon>
                            </template>
                            <!-- <template #suffix>元</template> -->
                        </el-statistic>
                    </el-col>
                    <el-col :xs="12" :sm="6" :md="4">
                        <el-statistic
                            title="团队总提现"
                            :value="stats.totalWithdrawAmount || 0"
                            :precision="2"
                        >
                            <template #prefix>
                                <el-icon><Odometer /></el-icon>
                            </template>
                            <!-- <template #suffix>元</template> -->
                        </el-statistic>
                    </el-col>

                    <!-- 昨日对比 -->
                    <!-- <el-col :xs="12" :sm="6" :md="4">
                        <el-statistic title="昨日新增" :value="stats.yesterdayNew || 0">
                            <template #prefix>
                                <el-icon><DataLine /></el-icon>
                            </template>
                        </el-statistic>
                    </el-col>
                    <el-col :xs="12" :sm="6" :md="4">
                        <el-statistic
                            title="昨日充值"
                            :value="stats.yesterdayRechargeAmount || 0"
                            :precision="2"
                        >
                            <template #prefix>
                                <el-icon><DataLine /></el-icon>
                            </template>
                            <template #suffix>元</template>
                        </el-statistic>
                    </el-col>
                    <el-col :xs="12" :sm="6" :md="4">
                        <el-statistic
                            title="昨日提现"
                            :value="stats.yesterdayWithdrawAmount || 0"
                            :precision="2"
                        >
                            <template #prefix>
                                <el-icon><DataLine /></el-icon>
                            </template>
                            <template #suffix>元</template>
                        </el-statistic>
                    </el-col> -->
                </el-row>
            </div>

            <!-- 等级统计 -->
            <el-card shadow="never" class="level-stats-card" style="margin-top: 20px">
                <template #header>
                    <div class="card-header">
                        <span>团队直级分布</span>
                        <el-tag type="info">总计: {{ totalCount }}</el-tag>
                    </div>
                </template>
                <el-row :gutter="20">
                    <el-col
                        v-for="item in levelDistribution"
                        :key="item.levelCode"
                        :xs="12"
                        :sm="6"
                        :md="3"
                    >
                        <el-card shadow="hover" class="level-item">
                            <div class="level-content">
                                <div class="level-name">{{ item.levelName }}</div>
                                <div class="level-count">{{ item.directCount }} 人</div>
                                <!-- <el-progress
                                    v-if="totalCount > 0"
                                    :percentage="item.percentage"
                                    :stroke-width="8"
                                    :color="getLevelColor(item.levelCode)"
                                    :show-text="false"
                                /> -->
                                <!-- <div class="level-percentage">
                                    {{ item.percentage?.toFixed(1) || '0.0' }}%
                                </div> -->
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </el-card>

            <!-- 标签页切换 -->
            <el-tabs v-model="activeTab" class="team-tabs" style="margin-top: 20px">
                <!-- 成员列表标签页 -->
                <el-tab-pane label="成员列表" name="members">
                    <div class="member-list-header">
                        <el-space>
                            <el-input
                                v-model="memberFilter"
                                placeholder="搜索用户名/手机号"
                                :prefix-icon="Search"
                                clearable
                                style="width: 300px"
                            />
                            <el-select
                                v-model="filterLevel"
                                placeholder="筛选等级"
                                clearable
                                style="width: 120px"
                            >
                                <el-option
                                    v-for="level in levelOptions"
                                    :key="level.value"
                                    :label="level.label"
                                    :value="level.value"
                                />
                            </el-select>
                            <el-select
                                v-model="filterRelationLevel"
                                placeholder="筛选层级"
                                clearable
                                style="width: 120px"
                            >
                                <el-option label="直接下级" :value="1" />
                                <el-option label="二级下级" :value="2" />
                                <el-option label="三级下级" :value="3" />
                            </el-select>
                        </el-space>
                    </div>

                    <el-table
                        v-loading="tableLoading"
                        :data="filteredMembers"
                        border
                        stripe
                        style="width: 100%"
                        :default-sort="{ prop: 'relationLevel', order: 'ascending' }"
                    >
                        <el-table-column prop="userId" label="用户ID" sortable />
                        <el-table-column prop="userName" label="用户名">
                            <template #default="{ row }">
                                <div class="user-cell">
                                    <el-avatar :size="32" :src="row.avatar" class="user-avatar">
                                        {{ row.userName?.charAt(0) }}
                                    </el-avatar>
                                    <div class="user-info">
                                        <div class="user-name">{{ row.userName }}</div>
                                        <div v-if="row.nickName" class="user-nickname">
                                            {{ row.nickName }}
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="phone" label="手机号" />
                        <el-table-column prop="levelName" label="用户等级">
                            <template #default="{ row }">
                                <el-tag :type="getLevelTagType(row.levelCode)" size="small">
                                    {{ row.levelName || '未配置名称' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="relationLevel" label="层级" sortable>
                            <template #default="{ row }">
                                <el-tag
                                    :type="getRelationLevelType(row.relationLevel)"
                                    size="small"
                                >
                                    {{ row.relationLevel }}级
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="joinTime" label="加入时间" sortable>
                            <template #default="{ row }">
                                {{ parseTime(row.joinTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="directCount" label="下级人数" sortable>
                            <template #default="{ row }">
                                {{ row.directCount > 0 ? row.directCount : 0 }}
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 分页 -->
                    <div class="pagination-wrapper">
                        <pagination
                            v-show="total > 0"
                            :total="total"
                            v-model:page="queryParams.pageNum"
                            v-model:limit="queryParams.pageSize"
                            @pagination="getMember"
                        />
                    </div>
                </el-tab-pane>
            </el-tabs>

            <!-- 加载状态 -->
            <div v-if="loading" class="loading-overlay">
                <el-icon class="is-loading" :size="48">
                    <Loading />
                </el-icon>
            </div>
        </div>
    </div>
</template>

<script setup name="Relation">
import {
    listRelation,
    getRelation,
    getTeamStatistics,
    recalculateStatistics,
} from '@/api/system/relation';

// 导入新增的图标
import {
    User,
    UserFilled,
    TrendCharts,
    Calendar,
    Money,
    CreditCard,
    Coin,
    Wallet,
    Odometer,
    DataLine,
    PieChart,
    Histogram,
    DataAnalysis,
    Document,
    DocumentChecked,
    DocumentAdd,
    Loading,
    Search,
} from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();

const relationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');

// 响应式数据
const treeLoading = ref(false);
const tableLoading = ref(false);
const activeTab = ref('members');
const treeDepth = ref(3);
const treeFilter = ref('');
const memberFilter = ref('');
const filterLevel = ref('');
const filterRelationLevel = ref('');
const currentPage = ref(1);
const pageSize = ref(20);
const subTeamDialogVisible = ref(false);
const selectedUserId = ref(0);

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        invitationCode: null,
        lowerUserId: null,
        relationLevel: null,
        teamPath: null,
        teamDepth: null,
        directSupId: null,
        status: null,
        expireTime: null,
    },
    rules: {
        supUserId: [{ required: true, message: '上级用户ID不能为空', trigger: 'blur' }],
        lowerUserId: [{ required: true, message: '下级用户ID不能为空', trigger: 'blur' }],
        createTime: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
        updateTime: [{ required: true, message: '更新时间不能为空', trigger: 'blur' }],
    },
});

const { queryParams, form, rules } = toRefs(data);

// 数据存储
const userInfo = ref({
    userName: '',
    phone: '',
    levelCode: '',
    levelName: '',
    createTime: '',
});

// 初始化统计对象，包含所有统计字段
const stats = ref({
    // 团队人数统计
    directCount: 0,
    totalCount: 0,
    todayNew: 0,
    monthNew: 0,
    yesterdayNew: 0,

    // 等级人数统计
    vip1Count: 0,
    vip2Count: 0,
    vip3Count: 0,
    vip4Count: 0,
    otherCount: 0,

    // 团队充值统计
    totalRechargeAmount: 0,
    totalWithdrawAmount: 0,
    todayRechargeAmount: 0,
    todayWithdrawAmount: 0,
    monthRechargeAmount: 0,
    monthWithdrawAmount: 0,
    yesterdayRechargeAmount: 0,
    yesterdayWithdrawAmount: 0,

    // 团队业绩统计
    totalPerformance: 0,
    todayPerformance: 0,
    monthPerformance: 0,

    // 其他统计
    totalOrderCount: 0,
    todayOrderCount: 0,
    monthOrderCount: 0,
});

const levelDistribution = ref([]);
const teamTree = ref([]);
const members = ref([]);

// 计算属性
const pageTitle = computed(() => {
    return `团队详情 (ID: ${queryParams.value.userId})`;
});

const totalCount = computed(() => {
    return levelDistribution.value.reduce((sum, item) => sum + (item.directCount || 0), 0);
});

const levelOptions = computed(() => {
    const levels = new Set(levelDistribution.value.map(item => item.levelName));
    return Array.from(levels).map(name => ({
        value: name,
        label: name,
    }));
});

const filteredMembers = computed(() => {
    let filtered = members.value;

    // 按搜索条件过滤
    if (memberFilter.value) {
        const keyword = memberFilter.value.toLowerCase();
        filtered = filtered.filter(
            member =>
                (member.userName && member.userName.toLowerCase().includes(keyword)) ||
                (member.nickName && member.nickName.toLowerCase().includes(keyword)) ||
                (member.phone && member.phone.includes(keyword))
        );
    }

    // 按等级过滤
    if (filterLevel.value) {
        filtered = filtered.filter(member => member.levelName === filterLevel.value);
    }

    // 按层级过滤
    if (filterRelationLevel.value) {
        filtered = filtered.filter(member => member.relationLevel === filterRelationLevel.value);
    }

    // 分页
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return filtered.slice(start, end);
});

// 方法
const loadData = async () => {
    try {
        loading.value = true;
        let params = {
            pageNum: 1,
            pageSize: 10,
        };
        getRelation(queryParams.value.invitationCode).then(response => {
            levelDistribution.value = response.data ? response.data.distribution : {};
            getTimeStas();
            getMember();
        });
    } catch (error) {
        console.error('加载数据失败:', error);
    } finally {
        loading.value = false;
    }
};

// 获取团队统计
function getTimeStas() {
    getTeamStatistics(queryParams.value.invitationCode).then(res => {
        if (res.data) {
            // 将API返回的数据合并到stats对象中
            stats.value = {
                ...stats.value,
                ...res.data,
            };

            // 计算等级分布百分比
            // calculateLevelDistributionPercentage();
        }
    });
}

// 计算等级分布百分比
function calculateLevelDistributionPercentage() {
    if (levelDistribution.value && levelDistribution.value.length > 0) {
        const total = levelDistribution.value.reduce((sum, item) => sum + (item.count || 0), 0);
        levelDistribution.value.forEach(item => {
            item.percentage = total > 0 ? (item.count / total) * 100 : 0;
        });
    }
}

// 获取团队成员列表
function getMember() {
    tableLoading.value = true;
    listRelation(queryParams.value).then(response => {
        members.value = response.rows;
        total.value = response.total;
        tableLoading.value = false;
    });
}

// 刷新数据
const refreshData = async () => {
    await loadData();
};

// 格式化金额显示
const formatAmount = amount => {
    if (!amount && amount !== 0) return '0.00';
    return Number(amount).toFixed(2);
};

// 等级颜色映射
const getLevelColor = levelCode => {
    const colors = {
        VIP4: '#f56c6c', // 红色
        VIP3: '#e6a23c', // 橙色
        VIP2: '#409eff', // 蓝色
        VIP1: '#67c23a', // 绿色
        未配置名称: '#909399', // 灰色
    };
    return colors[levelCode] || '#909399';
};

// 等级标签类型
const getLevelTagType = levelCode => {
    const types = {
        VIP4: 'danger',
        VIP3: 'warning',
        VIP2: 'primary',
        VIP1: 'success',
        未配置名称: 'info',
    };
    return types[levelCode] || 'info';
};

// 关系层级标签类型
const getRelationLevelType = level => {
    const types = {
        1: 'success',
        2: 'primary',
        3: 'warning',
        4: 'danger',
    };
    return types[level] || 'info';
};

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    if (!queryParams.value.invitationCode) {
        proxy.$modal.msgError('请输入用户邀请码');
        return;
    }
    loadData();
}

function handleRest() {
    if (!queryParams.value.invitationCode) {
        proxy.$modal.msgError('请输入用户邀请码');
        return;
    }
    recalculateStatistics(queryParams.value.invitationCode).then(res => {
        loadData();
    });
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm('queryRef');
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}
</script>

<style scoped lang="scss">
.team-detail-page {
    padding: 20px;
    background: #fff;
    border-radius: 10px;
}

.stats-section {
    margin-bottom: 20px;

    .stats-row {
        .el-col {
            margin-bottom: 20px;
        }
    }

    .el-statistic {
        text-align: center;
        padding: 20px 10px;
        background: #f8f9fa;
        border-radius: 8px;
        transition: all 0.3s;

        &:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }

        .el-statistic__head {
            font-size: 14px;
            color: #606266;
            margin-bottom: 8px;
            font-weight: 500;
        }

        .el-statistic__content {
            .el-statistic__number {
                font-size: 24px;
                font-weight: bold;
                color: #303133;
            }

            .el-statistic__suffix {
                font-size: 16px;
                color: #409eff;
            }
        }
    }

    .level-stats-card {
        margin-top: 20px;

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .level-item {
            margin-bottom: 0;
            transition: all 0.3s;

            &:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            }

            .level-content {
                text-align: center;
                padding: 15px 0;

                .level-name {
                    font-size: 14px;
                    color: #606266;
                    margin-bottom: 8px;
                    font-weight: 500;
                }

                .level-count {
                    font-size: 20px;
                    font-weight: bold;
                    color: #303133;
                    margin-bottom: 8px;
                }

                .level-percentage {
                    font-size: 12px;
                    color: #909399;
                    margin-top: 4px;
                }
            }
        }
    }
}

.team-tabs {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .member-list-header {
        margin-bottom: 20px;

        .el-space {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;

            @media (max-width: 768px) {
                width: 100%;
            }
        }
    }
}

.user-cell {
    display: flex;
    align-items: center;
    gap: 12px;

    .user-avatar {
        flex-shrink: 0;
    }

    .user-info {
        .user-name {
            font-weight: 500;
            color: #303133;
        }

        .user-nickname {
            font-size: 12px;
            color: #909399;
            margin-top: 2px;
        }
    }
}

.pagination-wrapper {
    margin-top: 20px;
    text-align: right;
    padding: 20px 0;
}

.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2000;

    .is-loading {
        animation: rotating 2s linear infinite;
    }
}

@keyframes rotating {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

// 统计卡片颜色主题
.el-statistic:nth-child(1) {
    border-left: 4px solid #409eff;
} // 蓝色
.el-statistic:nth-child(2) {
    border-left: 4px solid #67c23a;
} // 绿色
.el-statistic:nth-child(3) {
    border-left: 4px solid #e6a23c;
} // 橙色
.el-statistic:nth-child(4) {
    border-left: 4px solid #f56c6c;
} // 红色
.el-statistic:nth-child(5) {
    border-left: 4px solid #6f42c1;
} // 紫色
.el-statistic:nth-child(6) {
    border-left: 4px solid #fd7e14;
} // 橙色
.el-statistic:nth-child(7) {
    border-left: 4px solid #20c997;
} // 青色
.el-statistic:nth-child(8) {
    border-left: 4px solid #dc3545;
} // 红色
</style>
