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

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs, nextTick } from "vue";
import {
    queryRewardSetDataList,
    transactionRebateSet,
    memberGetUppers,
} from "@/api/swap";
import { ElForm, ElMessage } from "element-plus";
import { Search, Refresh, Setting } from "@element-plus/icons-vue";
import "element-tree-line/dist/style.css";
import {
    RewardSetQueryParam,
    RewardSetItem,
    RewardSetParam,
} from "@/types/api/swap";

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

const state = reactive({
    loading: true,
    queryParams: {
        pageNo: 1,
        pageSize: 1000,
        account: "",
        commonStatus: "",
        superPartner: "1",
        property: "registrationTime",
        direction: "1",
        getAccount: "",
    } as RewardSetQueryParam,
    dataList: [] as RewardSetItem[],
    tempList: [] as RewardSetItem[],
    dialog: {
        title: "",
        visible: false,
    },
    formData: {
        id: "",
        rate: 0,
        type: "0",
        username: "",
        realName: "",
        canUpdate: false,
    } as RewardSetParam,
    rules: {
        rate: [{ required: true, message: "比例不能为空", trigger: "blur" }],
    },
    unfold: false,
    refreshTree: true,
    searchList: [],
});

const defaultProps = {
    children: "children",
    label: "label",
};

const { loading, queryParams, dataList, tempList, dialog, formData, rules } =
    toRefs(state);

const memberStatusMap = {
    "0": "正常",
    "1": "非法",
    "": "全部",
};

function handleQuery() {
    state.loading = true;
    queryRewardSetDataList(state.queryParams).then(({ data }) => {
        state.loading = false;
        if (
            state.queryParams.commonStatus == "1" ||
            state.queryParams.getAccount != ""
        ) {
            state.tempList = data.content;
        } else {
            state.tempList = data.content.filter((item: any) => {
                return item.agentTotalCount > 0;
            });
        }
        state.dataList = state.tempList;
        state.dataList.forEach((item) => {
            item.label = relationTreeLabel(item);
        });
    });
}

const relationTreeLabel = (item: RewardSetItem) => {
    return (
        item.id +
        ", " +
        item.username +
        `: ( 团队余额: ${item.agentTotalBalance ? item.agentTotalBalance : "0"}
    , 团队人数: ${item.agentTotalCount ? item.agentTotalCount : "0"}
    , 团队入金: ${
        item.agentTotalRecharge ? item.agentTotalRecharge : "0"
    }, 团队出金: ${item.agentTotalWithdraw ? item.agentTotalWithdraw : "0"}
    , 资金流水: ${
        item.agentTotalAward ? item.agentTotalAward : "0"
    }, 团队佣金: ${item.agentTotalFee ? Math.abs(item.agentTotalFee) : "0"}
    , 佣金比例: ${item.rate ? item.rate : "0"} , 团队跟单余额: ${
            item.followBalance ? item.followBalance.toFixed(2) : "0"
        } , 团队合约余额: ${
            item.contractBalance ? item.contractBalance.toFixed(2) : "0"
        }) `
    );
};

const treeLoad = (node: any, resolve: any) => {
    const dataSubmit = () => {
        let data = node.data;
        let obj = {
            pageNo: 1,
            pageSize: 1000,
            property: "registrationTime",
            direction: "1",
            superPartner: "1",
            inviterId: data.id,
        } as RewardSetQueryParam;
        queryRewardSetDataList(obj).then((res) => {
            data.children = [];
            data.children = res.data.content;
            data.children.forEach((citem: any) => {
                citem.label = relationTreeLabel(citem);
            });
        });
        return resolve([]);
    };
    if (state.unfold) {
        if (
            node.level > 0 &&
            state.searchList.some((item) => item == node.data.id)
        ) {
            dataSubmit();
        }
    } else {
        if (node.level > 0) {
            dataSubmit();
        }
    }
};

/**
 * 查询重置
 */
function resetQuery() {
    state.refreshTree = false;
    state.unfold = false;
    state.queryParams.getAccount = "";
    queryFormRef.value.resetFields();
    handleQuery();
    nextTick(() => {
        state.refreshTree = true;
    });
}

//  查询搜索

const search = async () => {
    state.refreshTree = false;
    state.unfold = true;
    state.loading = true;
    if (state.queryParams.getAccount == "") {
        state.queryParams.account = "";
        await handleQuery();
        state.unfold = false;
    } else {
        try {
            const { code, message } = (await memberGetUppers({
                account: state.queryParams.getAccount,
            })) as any;
            if (code == 0) {
                state.queryParams.account =
                    message?.split(",")[0] || state.queryParams.getAccount;
                state.searchList = message?.split(",");
                await handleQuery();
            } else {
                await handleQuery();
            }
        } catch (error) {
            console.error(error);
        }
    }
    nextTick(() => {
        state.refreshTree = true;
    });
};

const showRewardSetModify = (row: any) => {
    state.dialog = {
        title: "设置比例",
        visible: true,
    };
    formData.value.id = row.id;
    formData.value.username = row.username;
    formData.value.rate = row.thirdLevel;
    formData.value.realName = row.realName;
    formData.value.canUpdate = row.canUpdate;
};

/**
 * 提交
 */
function submitFormData() {
    dataFormRef.value.validate((valid: any) => {
        if (valid) {
            loading.value = true;
            transactionRebateSet(state.formData)
                .then((res: any) => {
                    if (!res.code) {
                        ElMessage.success(res.message);
                        cancel();
                        loading.value = false;
                        handleQuery();
                    } else {
                        ElMessage.error(res.message);
                        cancel();
                        loading.value = false;
                    }
                })
                .catch(() => {
                    loading.value = false;
                });
        }
    });
}

/**
 * 取消
 */
function cancel() {
    dialog.value.visible = false;
    formData.value.id = "0";
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
}

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

<template>
    <div class="app-container">
        <!-- 搜索表单 -->
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item prop="account">
                <el-tooltip
                    content="请输入用户名、邮箱、手机号、姓名搜索"
                    placement="bottom"
                    effect="light"
                >
                    <el-input
                        v-model="queryParams.getAccount"
                        placeholder="请输入用户名、邮箱、手机号、姓名搜索"
                        style="width: 300px"
                        clearable
                        @keyup.enter="search"
                    />
                </el-tooltip>
            </el-form-item>
            <el-form-item prop="commonStatus">
                <span>会员状态：</span>
                <el-select
                    v-model="queryParams.commonStatus"
                    class="filter-item"
                    placeholder="请选择"
                    style="width: 100px"
                >
                    <el-option
                        v-for="(key, value) in memberStatusMap"
                        :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-form-item>
        </el-form>
        <!-- 数据树 -->
        <el-tree
            v-if="state.refreshTree"
            :data="state.dataList"
            :default-expand-all="state.unfold"
            :expand-on-click-node="false"
            :height="800"
            lazy
            :load="treeLoad"
            :props="defaultProps"
        >
            <!-- <template #default="{ node, data }"> -->
            <!-- <template #default="{ node }">
                <span class="custom-tree-node">
                    
                    <span>
                        <el-button
                            type="primary"
                            size="small"
                            :icon="Setting"
                            @click="showRewardSetModify(data)"
                            >修改</el-button
                        >
                    </span>
                </span>
            </template> -->
            <template v-slot:default="{ node, data }">
                <span class="custom-tree-node">{{ node.label }}</span>
            </template>
        </el-tree>
        <!-- 设置比例弹窗 -->
        <!-- <el-dialog
            :title="dialog.title"
            v-model="dialog.visible"
            width="640px"
            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="rate">
                    <el-input
                        type="number"
                        v-model="formData.rate"
                        placeholder="请输入"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button
                        type="primary"
                        :loading="loading"
                        @click="submitFormData"
                        >确 定</el-button
                    >
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog> -->
    </div>
</template>
<style lang="scss">
.el-tree-node__label {
    flex: 1;
    display: flex;
}
</style>
<style lang="scss" scoped>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>
