<script lang="ts">
export default {
    name: "agentArcDiag",
};
</script>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from "vue";
import { ElForm, ElMessage, ElLoading } from "element-plus";
import {
    Search,
    Refresh,
    Plus,
    Minus,
    Setting,
    ArrowUp,
    ArrowDown,
} from "@element-plus/icons-vue";
import { truncation } from "@/utils/filter";
import {
    transactionRebateSet,
    rewardModifyFollow,
    queryRewardSetDataList,
    memberGetUppers,
} from "@/api/swap";
import {
    MemberItem,
    MemberQueryParam,
    UserListTreeOrg,
} from "@/types/api/member/list";

import { RewardSetParam } from "@/types/api/swap";
import { da, it } from "element-plus/es/locale";

const loading = ref();
const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const profitStatusMap = {
    "1": "盈利",
    "-1": "亏损",
};

const superPartnerStatus = {
    "1": "是",
    "0": "否",
    "": "全部",
};

const patternSettings = {
    "0": "单独设置",
    "1": "联动设置",
};

const state = reactive({
    submiting: false,
    searchBox: {
        title: "展开搜索",
        expand: false,
    },
    queryParams: {
        pageNo: 1,
        pageSize: 1000,
        superPartner: "1",
        account: "",
        commonStatus: "",
        lockOrReward: "",
        transactionStartTime: "",
        transactionEndTime: "",
        profitStatus: "",
        property: "",
        direction: "1",
        inviterId: "",
        getAccount: "",
    } as MemberQueryParam,
    list: [] as MemberItem[],
    scaleValue: "100%",
    valueX: 100,
    baseData: {
        id: "架构图",
        label: {},
        children: [] as UserListTreeOrg[],
    },
    horizontal: false,
    expandAll: true,
    disaled: false,
    userList: [] as UserListTreeOrg[],
    dialog: {
        title: "",
        visible: false,
    },
    dialog1: {
        title: "",
        visible: false,
    },
    formData: {
        id: "",
        rate: 0,
        type: "0",
        username: "",
        realName: "",
        canUpdate: false,
    } as RewardSetParam,
    oldRate: 0,
    oldwcRate: 0,

    rules: {
        rate: [{ required: true, message: "比例不能为空", trigger: "blur" }],
    },
    tier: 1,
    searchList: [],
});
const {
    submiting,
    searchBox,
    queryParams,
    scaleValue,
    valueX,
    baseData,
    dialog,
    dialog1,
    formData,
    oldRate,
    oldwcRate,
    rules,
} = toRefs(state);

const openLoading = () => {
    loading.value = ElLoading.service({
        target: "#org_tree",
        lock: true,
        text: "Loading",
    });
};

const closeLoading = () => {
    loading.value.close();
};

const attachChildrenById = (items: any[], targetId: number | string, children: any[]) => {
    for (const item of items) {
        if (item.id == targetId) {
            item.children = children;
            return true;
        }
        if (item.children?.length && attachChildrenById(item.children, targetId, children)) {
            return true;
        }
    }
    return false;
};

const fetchAgentChildren = async (inviterId: string) => {
    const params = {
        ...state.queryParams,
        inviterId,
        pageNo: 1,
        pageSize: 1000,
    };
    const { data } = await queryRewardSetDataList(params);
    return getTopList([...data.content].reverse() as MemberItem[]);
};

const loadData = (node: any, resolve: (data: any[], auto?: boolean) => void) => {
    const inviterId = node.$$level === 0 ? "" : String(node.id);
    fetchAgentChildren(inviterId).then((children) => {
        if (node.$$level === 0) {
            state.baseData.children = children;
        } else {
            attachChildrenById(state.baseData.children, node.id, children);
        }
        resolve(children, true);
    });
};

const handleQuery = () => {
    state.queryParams.inviterId = "";
    if (state.tier > 1) {
        AllMemberManage();
    } else {
        getMemberManage();
    }
    clearHistoryData();
};

/**
 * 获取用户数据
 */

const getMemberManage = async () => {
    const inviterId = state.queryParams.inviterId
        ? String(state.queryParams.inviterId)
        : "";
    const children = await fetchAgentChildren(inviterId);
    if (inviterId) {
        attachChildrenById(state.baseData.children, inviterId, children);
    } else {
        state.baseData.children = children;
    }
    state.queryParams.account = "";
};

const AllMemberManage = async () => {
    openLoading();
    const { data } = await queryRewardSetDataList(state.queryParams);
    const ephemeralData = data.content.reverse() as any[];
    state.baseData.children = getTopList(ephemeralData);

    // 从最后一个索引开始逐个处理
    await insertDataIntoChildren(0);

    closeLoading();
};
const insertDataIntoChildren = async (index: any) => {
    if (index >= state.searchList.length) {
        return;
    }
    const currentIndex = state.searchList[index];
    const currentBaseDataItem = findItemById(
        state.baseData.children,
        currentIndex
    );

    if (currentBaseDataItem) {
        if (!currentBaseDataItem.children) {
            currentBaseDataItem.children = [];
        }

        // 根据索引获取数据
        state.queryParams.inviterId = currentIndex;
        const { data } = (await queryRewardSetDataList(
            state.queryParams
        )) as any;
        currentBaseDataItem.children.push(...getTopList(data.content));
    }

    // 递归处理下一个索引
    await insertDataIntoChildren(index + 1);
};

const findItemById = (items: any, targetId: any) => {
    for (let i = 0; i < items.length; i++) {
        const item = items[i];
        if (item.id == targetId) {
            return item;
        } else if (item.children) {
            const foundInChildren = findItemById(
                item.children,
                targetId
            ) as any;
            if (foundInChildren) {
                return foundInChildren;
            }
        }
    }
    return null;
};

/**
 *  搜索
 */

const search = async () => {
    if (state.queryParams.getAccount == "") {
        state.queryParams.account = "";
        await handleQuery();
    } else {
        try {
            const { code, message } = (await memberGetUppers({
                account: state.queryParams.getAccount,
            })) as any;
            if (code == 0) {
                state.tier = 10;
                state.searchList = message?.split(",");
                await handleQuery();
            } else {
                await handleQuery();
            }
        } catch (error) {
            console.error(error);
        }
    }
};

/** 是否展示展开按钮：优先后端 directAgentCount，否则用团队人数兜底 */
const hasSubordinates = (item: MemberItem) => {
    if (typeof item.directAgentCount === "number") {
        return item.directAgentCount > 0;
    }
    return (item.agentTotalCount ?? 0) > 1;
};

const getTopList = (list: MemberItem[]) => {
    let len = list.length;
    let data = [];
    for (let i = 0; i < len; i++) {
        let topItem = list[i];
        let id = topItem.id;
        let superPartner = topItem.superPartner;

        let nodeStyle = "one";
        if (superPartner == "1") {
            nodeStyle = "two";
        }
        let label = getLabel(topItem);
        let treeItem = {
            id: id,
            label: label,
            style: nodeStyle,
            children: [] as any,
            isLeaf: !hasSubordinates(topItem),
        };
        data.push(treeItem);
    }
    return data;
};

const getLabel = (item: MemberItem) => {
    let superPartner,
        id,
        t0,
        t1,
        t2,
        t3,
        t4,
        t5,
        t6,
        t7,
        t8,
        t9,
        rate,
        t10,
        wcRate;
    let superPartnerText = "";

    superPartner = item.superPartner;
    if (superPartner == "0") {
        superPartnerText = "普通会员";
    } else if (superPartner == "1") {
        superPartnerText = "超级代理商";
    } else if (superPartner == "2") {
        superPartnerText = "超级合伙人";
    }
    rate = item.rate;
    id = item.id;
    t0 = item.username;
    t1 = truncation(item.totalBalance);
    t2 = truncation(item.contractBalance);
    t3 = truncation(item.followBalance);
    t4 = item.agentTotalCount;
    t5 = item.followCount;
    t6 = item.agentTotalFee;
    t7 = item.rate;
    t8 = item.superPartner;
    t9 = item.realName;
    t10 = item.followRate;
    wcRate = item.followRate;
    id = id ? id : 0;
    t0 = t0 ? t0 : "";
    t1 = t1 ? t1 : 0;
    t2 = t2 ? t2 : 0;
    t3 = t3 ? t3 : 0;
    t4 = t4 ? t4 : 0;
    t5 = t5 ? t5 : 0;
    t6 = t6 ? t6 : 0;
    t7 = t7 ? t7 : 0;
    t10 = t10 ? t10 : 0;
    t1 = "账户余额:" + t1;
    t2 = "合约余额:" + t2;
    t3 = "跟单余额:" + t3;
    t4 = "团队人数:" + t4;
    t5 = "跟单人数:" + t5;
    t6 = "佣金:" + t6;
    t7 = "合约比例:" + t7;
    t10 = "跟单比例:" + t10;
    let v1 = item.totalProfit;
    let v2 = item.totalLoss;
    v1 = v1 ? v1 : 0;
    v2 = v2 ? v2 : 0;
    v1 = Number(v1).toFixed(2);
    v2 = Number(v2).toFixed(2);
    let diffValue = 0.0;
    if (Number(v2) <= 0) {
        v2 = Math.abs(Number(v2));
        diffValue = Number(v1) - v2;
    }

    if (Number(v2) >= 0) {
        diffValue = Number(v1) - Number(v2);
    }
    diffValue = Number(diffValue.toFixed(2));

    let label = {
        superPartnerText: superPartnerText,
        id: id,
        t0: t0,
        t1: t1,
        t2: t2,
        t3: t3,
        t4: t4,
        t5: t5,
        t6: t6,
        t7: t7,
        t8: t8,
        t9: t9,
        diffValue: "盈亏差值:" + diffValue,
        rate: rate,
        t10: t10,
        wcRate: wcRate,
    };
    return label;
};

/**
 * 查询重置
 * */
const resetQuery = () => {
    queryFormRef.value.resetFields();
    state.tier = 1;
    handleQuery();
};

const clearHistoryData = () => {
    state.queryParams.pageNo = 1;
    state.list = [];
    state.userList = [];
    state.baseData.children = [];
};

const defineMenus = () => {
    return {};
};
/**
 * 缩小
 */
const zoomOut = () => {
    if (state.valueX > 0) {
        valueX.value--;
        scaleValue.value = valueX.value + "%";
    }
};

/**
 * 放大
 */
const zoomIn = () => {
    if (state.valueX < 200) {
        valueX.value++;
        scaleValue.value = valueX.value + "%";
    }
};

const zoomSlider = (val: any) => {
    return val + "%";
};

const zoomInput = (val: any) => {
    scaleValue.value = val + "%";
};

/**
 * 设置合约比例
 * */
const showRewardSetModify = (row: any) => {
    state.dialog = {
        title: "设置合约比例",
        visible: true,
    };
    formData.value.id = row.label.id;
    formData.value.rate = row.label.rate;
    formData.value.username = row.label.t0;
    formData.value.realName = row.label.t9;
    formData.value.canUpdate = false;
    oldRate.value = row.label.rate;
};

// 修改跟单比例

const ModifyTheRaceRatioSettings = (row: any) => {
    state.dialog1 = {
        title: "设置跟单比例",
        visible: true,
    };
    formData.value.id = row.label.id;
    formData.value.rate = row.label.wcRate;
    formData.value.username = row.label.t0;
    formData.value.realName = row.label.t9;
    formData.value.canUpdate = false;
    oldwcRate.value = row.label.wcRate ? row.label.wcRate : 0;
};
/**
 * 提交合约比例
 */
function submitFormData() {
    dataFormRef.value.validate((valid: any) => {
        submiting.value = true;
        if (valid) {
            transactionRebateSet(state.formData)
                .then((res: any) => {
                    if (!res.code) {
                        ElMessage.success(res.message);
                        submiting.value = false;
                        cancel();
                        handleQuery();
                    } else {
                        ElMessage.error(res.message);
                        submiting.value = false;
                        cancel();
                    }
                })
                .catch(() => {
                    submiting.value = false;
                });
        }
    });
}

/**
 * 提交跟单比例
 */
function submitFormDataEvent() {
    dataFormRef.value.validate((valid: any) => {
        submiting.value = true;
        if (state.formData.rate > 100) {
            ElMessage.warning("比例不能大于100");
            submiting.value = false;
        } else {
            if (valid) {
                rewardModifyFollow(state.formData)
                    .then((res: any) => {
                        if (!res.code) {
                            ElMessage.success(res.message);
                            submiting.value = false;
                            cancel();
                            handleQuery();
                        } else {
                            ElMessage.error(res.message);
                            submiting.value = false;
                            cancel();
                        }
                    })
                    .catch(() => {
                        submiting.value = false;
                    });
            }
        }
    });
}
/**
 * 取消
 */
function cancel() {
    dialog.value.visible = false;
    dialog1.value.visible = false;
    formData.value.id = "";
    formData.value.rate = 0;
    formData.value.wcRate = 0;
    formData.value.type = "0";
    formData.value.username = "";
    formData.value.realName = "";
    formData.value.canUpdate = false;
    oldRate.value = 0;
    oldwcRate.value = 0;
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
}

const nodeDragStart = () => {};

const nodeDragMove = () => {};
const nodeDragEnd = (node: any, command: any) => {};
const onNodeDblclick = () => {};
const onNodeClick = () => {};
const onNodeDrag = () => {};
const onNodeDragStop = () => {};
const onZoom = (scale: any) => {};

/**
 * 展开/收起搜索
 */
const closeSearch = () => {
    state.searchBox.expand = !state.searchBox.expand;
    state.searchBox.title = !state.searchBox.expand ? "展开搜索" : "收起搜索";
};

onMounted(() => {
    handleQuery();
});
</script>

<template>
    <div class="app-container">
        <!-- 搜索表单 -->
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item prop="getAccount">
                <el-input
                    v-model="queryParams.getAccount"
                    placeholder="输入ID, 用户名搜索..."
                    style="width: 300px"
                    clearable
                    @keyup.enter="search"
                />
            </el-form-item>
            <el-form-item prop="transactionStartTime" v-show="searchBox.expand">
                <el-date-picker
                    v-model="queryParams.transactionStartTime"
                    style="width: 210px"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetime"
                    placeholder="开始日期"
                />
            </el-form-item>
            <el-form-item prop="transactionEndTime" v-show="searchBox.expand">
                <el-date-picker
                    v-model="queryParams.transactionEndTime"
                    style="width: 210px"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetime"
                    placeholder="结束日期"
                />
            </el-form-item>
            <el-form-item prop="profitStatus" v-show="searchBox.expand">
                <span>盈亏：</span>
                <el-select
                    v-model="queryParams.profitStatus"
                    class="filter-item"
                    placeholder="请选择"
                    style="width: 100px"
                >
                    <el-option
                        v-for="(key, value) in profitStatusMap"
                        :key="key"
                        :label="key"
                        :value="value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item prop="superPartner" v-show="searchBox.expand">
                <span>是否代理商：</span>
                <el-select
                    v-model="queryParams.superPartner"
                    class="filter-item"
                    placeholder="请选择"
                    style="width: 100px"
                >
                    <el-option
                        v-for="(key, value) in superPartnerStatus"
                        :key="key"
                        :label="key"
                        :value="value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="search"
                    >搜索</el-button
                >
                <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
                <el-button
                    link
                    @click="closeSearch"
                    style="border: 0"
                    size="small"
                >
                    {{ searchBox.title }}
                    <template v-if="searchBox.expand"
                        ><el-icon class="el-icon--right"><ArrowUp /></el-icon
                    ></template>
                    <template v-else
                        ><el-icon class="el-icon--right"><ArrowDown /></el-icon
                    ></template>
                </el-button>
            </el-form-item>
        </el-form>
        <el-row v-show="false">
            <el-button-group>
                <el-button
                    :icon="Minus"
                    @click="zoomOut"
                    class="zm-tree-icon"
                ></el-button>
                <el-button>{{ state.scaleValue }}</el-button>
                <el-button
                    :icon="Plus"
                    @click="zoomIn"
                    class="zoom-in"
                ></el-button>
            </el-button-group>
        </el-row>

        <el-slider
            v-show="false"
            v-model="valueX"
            :max="300"
            :min="30"
            :format-tooltip="zoomSlider"
            @input="zoomInput"
        />
        <div id="org_tree" class="org-tree">
            <vue3-tree-org
                :data="baseData"
                :toolBar="{ expand: false }"
                :only-one-node="false"
                :clone-node-drag="false"
                collapsable="true"
                center
                lazy
                :load="loadData"
                :disabled="true"
                :label-style="{ borderRadius: '7px' }"
                :default-expand-level="state.tier"
                :define-menus="defineMenus"
                @on-node-drag="nodeDragMove"
                @on-node-drag-start="nodeDragStart"
                @on-node-drag-end="nodeDragEnd"
                @on-node-dblclick="onNodeDblclick"
                @on-node-click="onNodeClick"
                @on-drag="onNodeDrag"
                @on-drag-stop="onNodeDragStop"
                @on-zoom="onZoom"
            >
                <template v-slot="{ node }">
                    <div
                        v-if="typeof node.label == 'object'"
                        class="tree-org-node__text"
                        :class="node.style"
                    >
                        <div class="content-block">
                            {{ node.id }} - {{ node.label.superPartnerText }}
                        </div>
                        <div class="content-block">{{ node.label.t0 }}</div>
                        <div class="content-block">{{ node.label.t1 }}</div>
                        <div class="content-block">{{ node.label.t2 }}</div>
                        <div class="content-block">{{ node.label.t3 }}</div>
                        <div class="content-block">{{ node.label.t4 }}</div>
                        <div class="content-block">{{ node.label.t5 }}</div>
                        <!-- <div class="content-block">{{ node.label.t6 }}</div> -->
                        <!-- <div class="content-block">
                            {{ node.label.diffValue }}
                        </div> -->
                        <div class="content-block">
                            <div class="content-inline">
                                <span>{{ node.label.t7 }}</span>
                                <el-button
                                    type="primary"
                                    size="small"
                                    :icon="Setting"
                                    class="tree-org-node-btn"
                                    v-if="node.label.t8 == 1"
                                    @click.stop="showRewardSetModify(node)"
                                />
                            </div>
                        </div>
                        <div class="content-block">
                            <div class="content-inline">
                                <span>{{ node.label.t10 }}</span>
                                <el-button
                                    type="primary"
                                    size="small"
                                    :icon="Setting"
                                    class="tree-org-node-btn"
                                    v-if="node.label.t8 == 1"
                                    @click.stop="
                                        ModifyTheRaceRatioSettings(node)
                                    "
                                />
                            </div>
                        </div>
                    </div>
                </template>
            </vue3-tree-org>
        </div>
        <!-- 设置合约比例弹窗 -->
        <el-dialog
            :title="dialog.title"
            v-model="dialog.visible"
            width="540px"
            destroy-on-close
        >
            <el-form
                ref="dataFormRef"
                :model="formData"
                :rules="rules"
                label-width="136px"
            >
                <el-form-item label="用户" prop="username">
                    <el-input
                        type="text"
                        v-model="formData.username"
                        readonly
                        disabled
                    />
                </el-form-item>
                <el-form-item label="选择模式" prop="type">
                    <el-select
                        v-model="formData.type"
                        class="filter-item"
                        placeholder="请选择"
                        style="width: 200px"
                    >
                        <el-option
                            v-for="(key, value) in patternSettings"
                            :key="key"
                            :label="key"
                            :value="value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="原比例">
                    <el-input type="text" v-model="oldRate" readonly disabled />
                </el-form-item>
                <el-form-item label="新比例" prop="rate">
                    <el-input
                        type="number"
                        v-model="formData.rate"
                        placeholder="请输入"
                    />
                </el-form-item>
            </el-form>
            <div>
                <div>说明:</div>
                <div>
                    单独设置就是只设置本账户，如果设置为0本账户就不拿返佣。
                </div>
                <div>
                    联动设置就是设置账户增加或下调的百分比后，下级账户也自动变化。
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button
                        type="primary"
                        :loading="submiting"
                        @click="submitFormData"
                        >确 定</el-button
                    >
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 设置赛事比例弹窗 -->
        <el-dialog
            :title="dialog1.title"
            v-model="dialog1.visible"
            width="540px"
            destroy-on-close
        >
            <el-form
                ref="dataFormRef"
                :model="formData"
                :rules="rules"
                label-width="136px"
            >
                <el-form-item label="用户" prop="username">
                    <el-input
                        type="text"
                        v-model="formData.username"
                        readonly
                        disabled
                    />
                </el-form-item>
                <el-form-item label="选择模式" prop="type">
                    <el-select
                        v-model="formData.type"
                        class="filter-item"
                        placeholder="请选择"
                        style="width: 200px"
                    >
                        <el-option
                            v-for="(key, value) in patternSettings"
                            :key="key"
                            :label="key"
                            :value="value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="原比例">
                    <el-input
                        type="text"
                        v-model="oldwcRate"
                        readonly
                        disabled
                    />
                </el-form-item>
                <el-form-item label="新比例" prop="rate">
                    <el-input
                        type="number"
                        v-model="formData.rate"
                        placeholder="请输入"
                    />
                </el-form-item>
            </el-form>
            <div>
                <div>说明:</div>
                <div>
                    单独设置就是只设置本账户，如果设置为0本账户就不拿返佣。
                </div>
                <div>
                    联动设置就是设置账户增加或下调的百分比后，下级账户也自动变化。
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button
                        type="primary"
                        :loading="submiting"
                        @click="submitFormDataEvent"
                        >确 定</el-button
                    >
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.org-tree {
    position: relative;
    width: 100%;
    height: 900px;
    .tree-org-node {
        background-color: #fff;
    }
}

.one {
    color: #666;
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 7px !important;
    padding: 10px;
}

.two {
    color: #fff;
    background-color: #66ccff;
    border-radius: 7px !important;
    padding: 10px;
    display: flex;
    flex-direction: column;
}

.content-block {
    text-align: start;
}
.content-inner {
    display: inline;
    text-align: left;
}
.tree-org-node-btn {
    display: inline;
    background: #66ccff;
    border: 1px solid #fff;
    color: #ffffff;
    margin-left: 15px;
}
.tree-org-node-btn:hover,
.tree-org-node-btn:active,
.tree-org-node-btn:focus {
    background: #66ccff;
    border: 1px solid #fff;
}
.tree-org-node__text {
    min-width: 180px;
}
</style>
