<template>
    <div class="app-container">
        <!-- 搜索表单 -->
        <el-form ref="queryFormRef" :model="state.queryParams" :inline="true">
            <!-- <el-form-item prop="id">
                <el-input
                    v-model="queryParams.id"
                    placeholder="输入会员ID"
                    style="width: 300px"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item> -->
            <el-form-item prop="account">
                <el-input
                    v-model="queryParams.account"
                    placeholder="输入ID、用户名、邮箱、手机号"
                    style="width: 300px"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item prop="startStatTime">
                <el-date-picker
                    v-model="queryParams.startStatTime"
                    type="date"
                    placeholder="起始日期"
                    size="small"
                />
            </el-form-item>
            <el-form-item prop="endStatTime">
                <el-date-picker
                    v-model="queryParams.endStatTime"
                    type="date"
                    placeholder="结束日期"
                    size="small"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleQuery"
                    >搜索</el-button
                >
                <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 数据表格 -->
        <el-table
            ref="dataTableRef"
            v-loading="state.loading"
            :data="state.recordList"
            highlight-current-row
            border
        >
            <el-table-column type="index" align="center" />

            <el-table-column label="会员ID" prop="memberId" align="center" />
            <el-table-column
                label="会员账号"
                prop="username"
                min-width="160"
                align="center"
            />
            <!-- <el-table-column
                label="邀请码"
                prop="promotionCode"
                align="center"
            />
            <el-table-column
                label="一级邀请"
                prop="firstLevel"
                align="center"
            />
            <el-table-column
                label="二级邀请"
                prop="secondLevel"
                align="center"
            />
            <el-table-column
                label="三级邀请"
                prop="thirdLevel"
                align="center"
            /> -->

            <!-- <el-table-column label="团队盈亏比" align="center">
                <template #default="scope">
                    <div v-if="scope.row.totalProfit">111</div>
                    <div v-if="scope.row.totalProfit">
                        {{
                            (
                                scope.row.totalProfit /
                                (scope.row.totalBalance - scope.row.totalProfit)
                            ).toFixed(2)
                                ? (
                                      scope.row.totalProfit /
                                      (scope.row.totalBalance -
                                          scope.row.totalProfit)
                                  ).toFixed(2)
                                : 0
                        }}
                        %
                    </div>
                    <div v-else>0 %</div>
                </template>
            </el-table-column> -->
            <el-table-column
                label="团队总余额"
                prop="totalBalance"
                align="center"
            >
                <template #default="scope">{{
                    scope.row.totalBalance
                        ? truncation(scope.row.totalBalance)
                        : 0
                }}</template>
            </el-table-column>
            <el-table-column
                label="团队CT持币量"
                prop="ctBalance"
                align="center"
                width="100"
            >
                <template #default="scope">{{
                    scope.row.ctBalance ? truncation(scope.row.ctBalance) : 0
                }}</template>
            </el-table-column>
            <el-table-column
                label="团队总出金"
                prop="totalWithdraw"
                align="center"
            >
                <template #default="scope">{{
                    scope.row.totalWithdraw
                        ? truncation(scope.row.totalWithdraw)
                        : 0
                }}</template>
            </el-table-column>
            <el-table-column
                label="团队总入金"
                prop="totalRecharge"
                align="center"
            >
                <template #default="scope">{{
                    scope.row.totalRecharge
                        ? truncation(scope.row.totalRecharge)
                        : 0
                }}</template>
            </el-table-column>
            <el-table-column
                label="今日出金"
                prop="todayWithdraw"
                align="center"
            >
                <template #default="scope">{{
                    scope.row.todayWithdraw
                        ? truncation(scope.row.todayWithdraw)
                        : 0
                }}</template>
            </el-table-column>
            <el-table-column
                label="今日入金"
                prop="todayRecharge"
                align="center"
            >
                <template #default="scope">{{
                    scope.row.todayRecharge
                        ? truncation(scope.row.todayRecharge)
                        : 0
                }}</template>
            </el-table-column>
            <el-table-column
                label="团队总人数"
                prop="agentTotalCount"
                align="center"
            >
                <template #default="scope">{{
                    scope.row.totalCount ? scope.row.totalCount : 1
                }}</template>
            </el-table-column>
            <el-table-column
                label="团队合约人数"
                prop="totalSwapCount"
                align="center"
                width="100"
            >
                <template #default="scope">{{
                    scope.row.totalSwapCount ? scope.row.totalSwapCount : 1
                }}</template>
            </el-table-column>
            <el-table-column
                label="今日合约人数"
                prop="totalSwapCount"
                align="center"
                width="100"
            >
                <template #default="scope">{{
                    scope.row.todayOrderCount ? scope.row.todayOrderCount : 1
                }}</template>
            </el-table-column>
            <el-table-column
                label="团队合约余额"
                prop="totalSwapBalance"
                align="center"
                width="100"
            >
                <template #default="scope">{{
                    scope.row.totalSwapBalance
                        ? truncation(scope.row.totalSwapBalance)
                        : 0
                }}</template>
            </el-table-column>
            <el-table-column
                label="团队跟单人数"
                prop="totalFollowCount"
                align="center"
                width="100"
            >
                <template #default="scope">{{
                    scope.row.totalFollowCount ? scope.row.totalFollowCount : 1
                }}</template>
            </el-table-column>
            <el-table-column
                label="团队跟单余额"
                prop="totalFollowBalance"
                align="center"
                width="100"
            >
                <template #default="scope">{{
                    scope.row.totalFollowBalance
                        ? truncation(scope.row.totalFollowBalance)
                        : 0
                }}</template>
            </el-table-column>
            <!-- <el-table-column
                label="团队资金流水"
                prop="totalAward"
                align="center"
            >
                <template #default="scope">{{
                    scope.row.totalAward ? scope.row.totalAward.toFixed(2) : 0
                }}</template>
            </el-table-column> -->
            <el-table-column label="团队总佣金" prop="totalFee" align="center">
                <template #default="scope">{{
                    scope.row.totalFee ? truncation(scope.row.totalFee) : 0
                }}</template>
            </el-table-column>
            <el-table-column
                label="跟单总分润"
                prop="totalFollowDividend"
                align="center"
                width="100"
            >
                <template #default="scope">{{
                    scope.row.totalFollowDividend
                        ? truncation(scope.row.totalFollowDividend)
                        : 0
                }}</template>
            </el-table-column>
            <el-table-column
                label="取消跟单人数"
                prop="cancelFollowerCustomer"
                align="center"
                width="100"
            >
                <template #default="scope">
                    <div
                        @click="agentList(scope.row, 20)"
                        style="cursor: pointer; color: blue; width: 100%"
                    >
                        <span>
                            {{
                                scope.row.cancelFollowerCustomer
                                    ? scope.row.cancelFollowerCustomer
                                    : 0
                            }}
                        </span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                label="今日新增用户"
                prop="todayNewUserCount"
                align="center"
                width="100"
            >
                <template #default="scope">
                    <div
                        @click="todayNewUserList(scope.row)"
                        style="cursor: pointer; color: blue; width: 100%"
                    >
                        <span>
                            {{
                                scope.row.todayNewUserCount
                                    ? scope.row.todayNewUserCount
                                    : 0
                            }}
                        </span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                label="合约返佣点数"
                prop="rate"
                align="center"
                width="100"
            >
                <template #default="scope">{{
                    scope.row.rate?.toFixed(2)
                }}</template>
            </el-table-column>
            <el-table-column
                label="跟单返佣点数"
                prop="followRate"
                align="center"
                width="100"
            >
                <template #default="scope">{{
                    scope.row.followRate?.toFixed(2)
                }}</template>
            </el-table-column>
            <!-- <el-table-column
                label="跟单分润点数"
                prop="dividendRate"
                align="center"
                width="100"
            >
                <template #default="scope">{{
                    scope.row.dividendRate?.toFixed(2)
                }}</template>
            </el-table-column> -->
            <el-table-column
                label="操作"
                prop="thirdLevel"
                fixed="right"
                align="center"
                min-width="200"
            >
                <template #default="scope">
                    <el-button
                        type="primary"
                        size="small"
                        @click.stop="showRewardSetModify(scope.row, 1)"
                    >
                        合约修改
                    </el-button>
                    <el-button
                        type="primary"
                        size="small"
                        @click.stop="showRewardSetModify(scope.row, 2)"
                    >
                        跟单修改
                    </el-button>
                    <!-- <el-button
                        type="primary"
                        size="small"
                        @click.stop="showRewardSetModify(scope.row, 3)"
                    >
                        跟单分润修改
                    </el-button> -->
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页工具条 -->
        <pagination
            v-if="state.total > 0"
            :total="state.total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
        />
        <!-- 设置比例弹窗 -->
        <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="text"
                        v-model="formData.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>
            <template #footer>
                <div class="dialog-footer">
                    <el-button
                        type="primary"
                        :loading="loading"
                        @click="submitFormData(dialog.title)"
                        >确 定</el-button
                    >
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog
            v-model="state.dialogTableVisible"
            :title="state.title"
            width="70%"
        >
            <el-table
                :data="state.studentFollowingData"
                border
                v-loading="state.follow"
            >
                <el-table-column prop="id" label="序号" align="center" />
                <el-table-column
                    prop="memberId"
                    label="会员ID"
                    align="center"
                />
                <el-table-column
                    prop="username"
                    label="会员账号"
                    align="center"
                    width="150"
                />
                <el-table-column
                    prop="nickname"
                    label="会员昵称"
                    align="center"
                />
                <!-- <el-table-column
                    prop="teacherId"
                    label="老师跟单ID"
                    align="center"
                />
                <el-table-column
                    prop="teacherMemberId"
                    label="老师会员ID"
                    align="center"
                />
                <el-table-column
                    prop="teacherUsername"
                    label="老师账号"
                    align="center"
                />
                <el-table-column
                    prop="teacherNickname"
                    label="老师昵称"
                    align="center"
                /> -->
                <el-table-column
                    prop="totalAccountBalance"
                    label="账户总余额"
                    align="center"
                >
                    <template #default="scope">
                        <span>{{
                            truncation(scope.row.totalAccountBalance)
                        }}</span></template
                    >
                </el-table-column>
                <el-table-column
                    prop="assetAccount"
                    label="资产账户"
                    align="center"
                >
                    <template #default="scope">
                        <span>{{
                            truncation(scope.row.assetAccount)
                        }}</span></template
                    >
                </el-table-column>
                <el-table-column
                    prop="contractAccount"
                    label="合约账户"
                    align="center"
                >
                    <template #default="scope">
                        <span>{{
                            truncation(scope.row.contractAccount)
                        }}</span></template
                    >
                </el-table-column>
                <el-table-column
                    prop="followAccount"
                    label="跟单账户"
                    align="center"
                >
                    <template #default="scope">
                        <span>{{
                            truncation(scope.row.followAccount)
                        }}</span></template
                    >
                </el-table-column>
                <el-table-column
                    prop="followAllprofitOrLoss"
                    label="跟单总盈亏"
                    align="center"
                >
                    <template #default="scope">
                        <span>{{
                            truncation(scope.row.followAllprofitOrLoss)
                        }}</span></template
                    >
                </el-table-column>

                <el-table-column
                    prop="followTime"
                    label="跟随时间"
                    align="center"
                    min-width="120"
                />
            </el-table>
            <pagination
                v-if="state.studentTotal > 0"
                :total="state.studentTotal"
                v-model:page="state.agentStudentPositionForm.currentPage"
                v-model:limit="state.agentStudentPositionForm.pageSize"
                @pagination="agentList"
            />
        </el-dialog>

        <!-- 今日新增用户 -->
        <el-dialog
            v-model="state.todayNewUsersTableVisible"
            :title="state.todayNewUsersTitle"
            width="70%"
        >
            <el-table
                :data="state.todayNewUsersData"
                border
                v-loading="state.todayNewUsers"
            >
                <el-table-column type="index" align="center" />
                <el-table-column
                    prop="id"
                    label="会员ID"
                    align="center"
                />
                <el-table-column
                    prop="username"
                    label="会员账号"
                    align="center"
                    width="150"
                />
                <el-table-column
                    prop="totalBalance"
                    label="账户总余额"
                    align="center"
                >
                    <template #default="scope">
                        <span>{{
                            truncation(scope.row.totalBalance)
                        }}</span></template
                    >
                </el-table-column>
                <el-table-column
                    prop="registrationTime"
                    label="注册时间"
                    align="center"
                    min-width="120"
                />
            </el-table>
            <pagination
                v-if="state.todayNewUsersTotal > 0"
                :total="state.todayNewUsersTotal"
                v-model:page="state.todayNewUsersForm.pageNo"
                v-model:limit="state.todayNewUsersForm.pageSize"
                @pagination="todayNewUserList(state.rowData)"
            />
        </el-dialog>
    </div>
</template>
<script lang="ts">
export default {
    name: "team",
};
</script>

<script lang="ts" setup>
import { reactive, ref, toRefs, onMounted } from "vue";
import { Search, Refresh } from "@element-plus/icons-vue";
import { ElForm, ElTable, ElMessage } from "element-plus";
import { teamDetails } from "@/api/invitation/index";
import { RecordQueryParam, RecordItem } from "@/types/api/invitation/index";
import {
    transactionRebateSet,
    followersAgent,
    rewardModifyFollow,
    rewardModifyDividend,
    todayNewUser
} from "@/api/swap";
import { truncation } from "@/utils/filter";
import moment from "moment";
const dataFormRef = ref(ElForm);
const queryFormRef = ref(ElForm);
const state = reactive({
    queryParams: {
        account: "",
        pageNo: 1,
        pageSize: 15,
        realName: "",
        mobilePhone: "",
        email: "",
        id: "",
        username: "",
        startStatTime: "",
        endStatTime: "",
    } as RecordQueryParam,
    loading: true,
    recordList: [] as RecordItem[],
    total: 0,
    formData: {
        id: "",
        rate: 0,
        type: "0",
        username: "",
        realName: "",
        canUpdate: false,
        oldRate: 0,
    },

    dialog: {
        title: "",
        visible: false,
    },

    rules: {
        rate: [{ required: true, message: "比例不能为空", trigger: "blur" }],
        wcRate: [
            {
                validator: (rule: any, value: any, callback: any) => {
                    if (value === "") {
                        callback(new Error("不能为空"));
                    } else if (value > 10) {
                        callback(new Error("不能大于10"));
                    } else if (value % 2 === 1) {
                        callback(new Error("不能为奇数"));
                    } else {
                        callback();
                    }
                },
                trigger: "blur",
            },
        ],
    },

    // 当前跟随列表
    follow: true,
    studentTotal: 0,

    studentFollowingData: [],
    dialogTableVisible: false,
    title: "当前跟随列表",

    agentStudentPositionForm: {
        currentPage: 1,
        pageSize: 10,
        status: 10,
        teacherIds: [0],
    },

    // 今日新增用户
    todayNewUsers: true,
    todayNewUsersTotal: 0,

    todayNewUsersData: [],
    todayNewUsersTableVisible: false,
    todayNewUsersTitle: "今日新增用户",

    todayNewUsersForm: {
        pageNo: 1,
        pageSize: 10,
        userId: 0,
        startTime: '',
    },
    rowData: {} as any
});
const { queryParams, formData, rules, dialog, loading } = toRefs(state);

const handleQuery = () => {
    state.loading = true;
    state.queryParams.endStatTime = state.queryParams.endStatTime
        ? moment(state.queryParams.endStatTime).format("YYYY-MM-DD")
        : "";
    state.queryParams.startStatTime = state.queryParams.startStatTime
        ? moment(state.queryParams.startStatTime).format("YYYY-MM-DD")
        : "";

    teamDetails(state.queryParams).then(({ data }) => {
        state.recordList = data.content;
        state.total = data.totalElements;
        state.loading = false;
    });
};

// 获取代理商学生列表
const agentList = (row: any, index: number) => {
    if (row.cancelFollowerCustomer < 1) {
        return;
    }
    state.dialogTableVisible = true;
    state.agentStudentPositionForm.status = index;
    state.agentStudentPositionForm.teacherIds = JSON.parse(row.teacherIds);
    followersAgent(state.agentStudentPositionForm).then((res: any) => {
        state.studentFollowingData = res.data.records;
        state.studentTotal = res.data.total;
        state.follow = false;
    });
};

// 获取今日新增用户列表
const todayNewUserList = (row: any) => {
    state.rowData = row;
    if (state.rowData.todayNewUserCount < 1) {
        return;
    }
    state.todayNewUsers = true;
    state.todayNewUsersData = [];
    state.todayNewUsersTotal = 0;
    state.todayNewUsersTableVisible = true;
    state.todayNewUsersForm.userId = row.memberId;
    state.todayNewUsersForm.startTime = moment().format("YYYY-MM-DD");
    todayNewUser(state.todayNewUsersForm).then((res: any) => {
        state.todayNewUsersData = res.data.content;
        state.todayNewUsersTotal = res.data.totalElements;
        state.todayNewUsers = false;
    });
};

onMounted(() => {
    handleQuery();
});

/**
 * 设置比例弹窗
 * @param row 行数据
 */
const showRewardSetModify = (row: any, index: number) => {
    state.dialog = {
        title:
            index == 1
                ? "设置合约比例"
                : index == 2
                ? "设置跟单比例"
                : "设置跟单分润比例",
        visible: true,
    };
    formData.value.id = row.memberId;
    formData.value.username = row.username;
    formData.value.oldRate =
        index == 1 ? row.rate : index == 2 ? row.followRate : row.dividendRate;
    formData.value.rate =
        index == 1 ? row.rate : index == 2 ? row.followRate : row.dividendRate;
    formData.value.realName = row.realName;
    formData.value.canUpdate = row.canUpdate;
};

/**
 * 合约提交
 */

function submitFormData(row: any) {
    const apiMap = {
        设置合约比例: transactionRebateSet,
        设置跟单比例: rewardModifyFollow,
        default: rewardModifyDividend,
    };

    const api = apiMap[row] || apiMap.default;

    dataFormRef.value.validate((valid: any) => {
        if (valid) {
            loading.value = true;
            api(state.formData)
                .then((res: any) => {
                    if (!res.code) {
                        ElMessage.success(res.message);
                        cancel();
                        handleQuery();
                    } else {
                        ElMessage.error(res.message);
                        cancel();
                    }
                })
                .finally(() => {
                    loading.value = false;
                });
        }
    });
}

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

// 搜索重置
const resetQuery = function () {
    queryFormRef.value.resetFields();
    handleQuery();
};
</script>

<style lang="less" scoped></style>
