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

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from "vue";
import { ElTable, ElForm, ElMessage } from "element-plus";
import { Search, Refresh, Download } from "@element-plus/icons-vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import { useRoute } from "vue-router";
import qs from "qs";
import {
    memberDetail,
    lockedActivityList,
    lockMemberCoin,
    manualPay,
    lockWallet,
    unlockWallet,
    resetMemberAddr,
    getCoinName,
    perTradeAll,
} from "@/api/member/detail";
import {
    MemberInfo,
    MemberDetailList,
    LockActivity,
    LockActivityParam,
    ManualPayParam,
    FilterSearchParam,
    TradeItem,
    Symbol,
} from "@/types/api/member/detail";

const emit = defineEmits(["detailClick"]);
const dataTableRef = ref(ElTable);
const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const mpDataFormRef = ref(ElForm);

/**
 * 交易类型
 */
const typeArrMap = {
    0: "充值",
    1: "提现",
    2: "转账",
    3: "币币交易",
    4: "法币买入",
    5: "法币卖出",
    6: "竞猜奖励",
    7: "推广奖励",
    8: "分红",
    9: "投票",
    10: "人工充值",
    11: "配对",
    // 12: "竞猜兑换",
    13: "C2C买入",
    14: "C2C卖出",
    15: "红包发出",
    16: "红包领取",
    17: "提现码提现",
    18: "提现码充值",
    19: "永续合约手续费",
    20: "永续合约盈利",
    21: "永续合约亏损",
    22: "期权合约失败",
    23: "期权合约手续费",
    24: "期权合约奖金",
    25: "合约返佣",
    26: "订单隔夜费",
    27: "平台手续费收入",
    // 28: "竞猜手续费",
    // 29: "竞猜盈利",
    // 30: "竞猜亏损",
    // 31: "竞猜返佣",
    37: "合约跟单手续费",
    38: "合约跟单盈利",
    39: "合约跟单亏损",
    40: "合约跟单分润",
    41: "合约跟单返佣",
    42: "合约跟单隔夜费",
};

const state = reactive({
    loading: true,
    loading2: true,
    loading3: false,
    loading4: false,
    loading5: false,
    loading6: false,
    memberId: 0 as any,
    memberInfo: {} as MemberInfo,
    list: [] as MemberDetailList[],
    lockCoinDialog: {
        title: "",
        visible: false,
        lockUnit: "",
        lockAmount: 0,
    },
    lockActivity: [] as LockActivity[],
    formData: {} as LockActivityParam,
    manualPayDialog: {
        title: "",
        visible: false,
        payAddress: "",
        payUnit: "",
    },
    mpFormData: {} as ManualPayParam,
    rules: {
        amount: [{ required: true, message: "请输入数量", trigger: "blur" }],
    },
    mpRules: {
        amount: [
            { required: true, message: "请输入充值数量", trigger: "blur" },
        ],
    },
    filterSearch: {
        pageNo: 1,
        pageSize: 50,
        memberId: 0,
        type: "",
        symbol: "",
        startTime: "",
        endTime: "",
    } as FilterSearchParam,
    trade: [] as TradeItem[],
    total: 0,
    allSymbolMap: [] as Symbol[],
    dateRange: [] as any,
    aLink: "",
});

const {
    loading,
    loading2,
    loading3,
    loading4,
    loading5,
    loading6,
    memberId,
    memberInfo,
    list,
    lockCoinDialog,
    lockActivity,
    formData,
    rules,
    manualPayDialog,
    mpFormData,
    mpRules,
    filterSearch,
    trade,
    total,
    allSymbolMap,
    aLink,
} = toRefs(state);

/**
 * 获取会员详情
 * @param id 会员id
 */
function getMemberDetail(id: any) {
    state.loading = true;
    memberDetail({ id: id }).then(({ data }) => {
        state.memberInfo = data.member;
        state.list = data.list.filter((item) => {
            return (
                item.coin.unit == "USDT-BEP20" ||
                item.coin.unit == "EUSDT" ||
                item.coin.unit == "TUSDT" ||
                item.coin.unit == "USDT"
            );
        });
        // state.list = data.list;
        state.loading = false;
    });
}

/**
 * 获取活动列表
 */
function getLockedActivityList() {
    lockedActivityList().then(({ data }) => {
        state.lockActivity = data;
    });
}

/**
 * 会员等级描述
 * @param str
 */
function getlevel(str: any) {
    let memberLevelTxt = "";
    if (!str) memberLevelTxt = "普通会员";
    else if (str === 1) memberLevelTxt = "实名";
    else if (str === 2) memberLevelTxt = "认证";
    return memberLevelTxt;
}

function handleRowClick(row: any) {
    emit("detailClick", row);
}

/**
 * 显示锁仓弹窗
 * @param row
 */
function showLockCoin(row: any) {
    state.lockCoinDialog.title = "锁仓";
    state.lockCoinDialog.visible = true;
    state.lockCoinDialog.lockUnit = row.coin.unit;
    state.lockCoinDialog.lockAmount = 0;
    formData.value.amount = 0;
    formData.value.memberId = row.memberId;
    formData.value.unit = row.coin.unit;
}

/**
 * 提交用户平仓
 */
function submitFormData() {
    dataFormRef.value.validate((valid: any) => {
        if (valid) {
            loading3.value = true;
            lockMemberCoin(state.formData)
                .then((res: any) => {
                    if (!res.code) {
                        ElMessage.success(res.message);
                        cancel();
                        loading3.value = false;
                    } else {
                        ElMessage.error(res.message);
                        cancel();
                        loading3.value = false;
                    }
                })
                .catch(() => {
                    loading3.value = false;
                });
        }
    });
}
/**
 * 取消锁仓
 */
function cancel() {
    lockCoinDialog.value.visible = false;
    formData.value.memberId = 0;
    formData.value.activityId = 0;
    formData.value.unit = "";
    formData.value.amount = 0;
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
}

/**
 * 显示人工充币窗口
 */
function showManualPay(row: any) {
    state.manualPayDialog.title = "人工充币";
    state.manualPayDialog.visible = true;
    state.manualPayDialog.payAddress = row.address;
    state.manualPayDialog.payUnit = row.coin.unit;
    mpFormData.value.amount = 0;
    mpFormData.value.uid = row.memberId;
    mpFormData.value.unit = row.coin.unit;
}

/**
 * 提交人工充币
 */
function confrimPay() {
    mpDataFormRef.value.validate((valid: any) => {
        if (valid) {
            loading4.value = true;
            manualPay(state.mpFormData)
                .then((res: any) => {
                    if (!res.code) {
                        ElMessage.success(res.message);
                        getMemberDetail(state.memberId);
                        cancelPay();
                        loading4.value = false;
                    } else {
                        ElMessage.error(res.message);
                        cancelPay();
                        loading4.value = false;
                    }
                })
                .catch(() => {
                    loading4.value = false;
                });
        }
    });
}

/**
 * 取消充值
 */
function cancelPay() {
    manualPayDialog.value.visible = false;
    mpFormData.value.amount = 0;
    mpFormData.value.uid = 0;
    mpFormData.value.unit = "";
    mpDataFormRef.value.resetFields();
    mpDataFormRef.value.clearValidate();
}

/**
 * 锁定、解锁
 */
function optLockWallet(row: any) {
    if (row.isLock) {
        state.loading5 = true;
        unlockWallet({ uid: state.memberId, unit: row.coin.unit })
            .then((res: any) => {
                if (!res.code) {
                    ElMessage.success(res.message);
                    getMemberDetail(state.memberId);
                } else {
                    ElMessage.error(res.message);
                }
                state.loading5 = false;
            })
            .catch((err: any) => {
                state.loading5 = false;
            });
    } else {
        lockWallet({ uid: state.memberId, unit: row.coin.unit })
            .then((res: any) => {
                if (!res.code) {
                    ElMessage.success(res.message);
                    getMemberDetail(state.memberId);
                } else {
                    ElMessage.error(res.message);
                }
                state.loading5 = false;
            })
            .catch((err: any) => {
                state.loading5 = false;
            });
    }
}

/**
 * 重置地址
 */
function resetMemberAddress(row: any) {
    state.loading6 = true;
    resetMemberAddr({ uid: state.memberId, unit: row.coin.unit })
        .then((res: any) => {
            if (!res.code) {
                ElMessage.success(res.message);
                getMemberDetail(state.memberId);
            } else {
                ElMessage.error(res.message);
            }
            state.loading6 = false;
        })
        .catch((err: any) => {
            state.loading6 = false;
        });
}

/**
 * 查询重置
 */
function resetQuery() {
    state.aLink =
        `${
            import.meta.env.VITE_APP_BASE_API
        }/admin/finance/member-transaction/out-excel?memberId=` +
        state.memberId;
    queryFormRef.value.resetFields();
    handleQuery();
}

/**
 * 交易记录
 */
function handleQuery() {
    emit("detailClick", {});
    state.loading2 = true;
    perTradeAll(state.filterSearch).then(({ data }) => {
        state.trade = data.content;
        state.total = data.totalElements;
        state.loading2 = false;
    });
}

function searchByFilter() {
    state.aLink = `${
        import.meta.env.VITE_APP_BASE_API
    }/admin/finance/member-transaction/out-excel?${qs.stringify(
        state.filterSearch
    )}`;
    handleQuery();
}

function getSymbolCoinName() {
    getCoinName()
        .then(({ data }) => {
            state.allSymbolMap = data;
        })
        .catch((err) => {
            console.log(err);
        });
}

/**
 * 交易金额
 */
function tradeAmountStr(obj: any) {
    let amount = obj.row.amount + "";
    let symbol = obj.row.symbol;
    if (obj.row.type == 20) {
        amount = "+" + amount;
    }

    return amount + " " + symbol;
}

onMounted(() => {
    const route = useRoute();
    state.memberId = route.query.id;
    state.filterSearch.memberId = state.memberId;
    state.aLink =
        `${
            import.meta.env.VITE_APP_BASE_API
        }/admin/finance/member-transaction/out-excel?memberId=` +
        state.memberId;

    getMemberDetail(state.memberId);
    getLockedActivityList();
    getSymbolCoinName();
    handleQuery();
});
</script>

<template>
    <div class="app-container">
        <el-card>
            <template #header>
                <svg-icon icon-class="link" /> 基本信息
            </template>

            <el-row class="card-row">
                <el-col :span="6">
                    <p>
                        会员等级：<span style="color: #ec0909">{{
                            getlevel(memberInfo.memberLevel)
                        }}</span>
                    </p>
                    <p>
                        真实姓名：<span>{{ memberInfo.realName }}</span>
                    </p>
                    <p>
                        注册时间：<span>{{ memberInfo.registrationTime }}</span>
                    </p>
                </el-col>
                <el-col :span="6">
                    <p>
                        会员状态：<span style="color: #2d8cf0">{{
                            !memberInfo.status ? "正常" : "禁用"
                        }}</span>
                    </p>
                    <p>
                        会员手机号：<span>{{ memberInfo.mobilePhone }}</span>
                    </p>
                    <p>
                        最近登录时间：<span>{{
                            memberInfo.lastLoginTime
                        }}</span>
                    </p>
                </el-col>
                <el-col :span="6">
                    <p>
                        会员昵称：<span>{{ memberInfo.username }}</span>
                    </p>
                    <p>
                        身份证号：<span>{{ memberInfo.idNumber }}</span>
                    </p>
                </el-col>
                <el-col :span="6">
                    <p>
                        用户ID：<span>{{ memberInfo.id }}</span>
                    </p>
                    <p>
                        邮箱：<span>{{ memberInfo.email }}</span>
                    </p>
                </el-col>
            </el-row>
        </el-card>

        <el-card style="margin-top: 20px">
            <template #header>
                <svg-icon icon-class="link" /> 用户资产
            </template>

            <el-row class="card-row">
                <el-table :data="list" v-loading="loading">
                    <el-table-column
                        label="币种"
                        prop="coin.unit"
                        min-width="100"
                        align="center"
                    />
                    <el-table-column
                        label="可用"
                        prop="balance"
                        min-width="180"
                        align="center"
                    />
                    <el-table-column
                        label="冻结"
                        prop="frozenBalance"
                        min-width="180"
                        align="center"
                    />
                    <el-table-column
                        label="待释放资产"
                        prop="toReleased"
                        min-width="180"
                        align="center"
                    />
                    <el-table-column
                        label="地址"
                        prop="address"
                        min-width="180"
                        align="center"
                    />
                    <el-table-column label="操作" align="center" width="310">
                        <template #default="scope">
                            <el-button
                                type="success"
                                size="small"
                                @click.stop="showLockCoin(scope.row)"
                            >
                                锁仓
                            </el-button>
                            <el-button
                                type="primary"
                                size="small"
                                @click.stop="showManualPay(scope.row)"
                            >
                                充值
                            </el-button>
                            <el-button
                                :type="scope.row.isLock ? 'success' : 'danger'"
                                :loading="loading5"
                                size="small"
                                @click.stop="optLockWallet(scope.row)"
                            >
                                <span v-if="scope.row.isLock">解锁</span>
                                <span v-else>锁定</span>
                            </el-button>
                            <el-button
                                type="warning"
                                :loading="loading6"
                                size="small"
                                @click.stop="resetMemberAddress(scope.row)"
                            >
                                重置地址
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 锁仓弹窗 -->
                <el-dialog
                    :title="lockCoinDialog.title"
                    v-model="lockCoinDialog.visible"
                    width="500px"
                    destroy-on-close
                >
                    <el-form
                        ref="dataFormRef"
                        :model="formData"
                        :rules="rules"
                        label-width="100px"
                    >
                        <el-form-item label="币种" prop="lockUnit">
                            {{ lockCoinDialog.lockUnit }}
                        </el-form-item>
                        <el-form-item label="选择锁仓活动" prop="activityId">
                            <el-select
                                v-model="formData.activityId"
                                class="filter-item"
                                placeholder="请选择"
                            >
                                <el-option
                                    v-for="item in lockActivity"
                                    :key="item.title"
                                    :label="item.title"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="锁仓数量" prop="amount">
                            <el-input
                                type="number"
                                v-model="formData.amount"
                                placeholder="请输入锁仓数量"
                            />
                        </el-form-item>
                    </el-form>

                    <template #footer>
                        <div class="dialog-footer">
                            <el-button
                                type="primary"
                                :loading="loading3"
                                @click="submitFormData"
                                >确 定</el-button
                            >
                            <el-button @click="cancel">取 消</el-button>
                        </div>
                    </template>
                </el-dialog>

                <!-- 人工充值弹窗 -->
                <el-dialog
                    :title="manualPayDialog.title"
                    v-model="manualPayDialog.visible"
                    width="500px"
                    destroy-on-close
                >
                    <el-form
                        ref="mpDataFormRef"
                        :model="mpFormData"
                        :rules="mpRules"
                        label-width="100px"
                    >
                        <el-form-item label="币种">
                            {{ manualPayDialog.payUnit }}
                        </el-form-item>
                        <el-form-item label="充值地址">
                            {{ manualPayDialog.payAddress }}
                        </el-form-item>
                        <el-form-item label="充值数量" prop="amount">
                            <el-input
                                type="number"
                                v-model="mpFormData.amount"
                                placeholder="请输入充值数量"
                            />
                        </el-form-item>
                    </el-form>

                    <template #footer>
                        <div class="dialog-footer">
                            <el-button
                                type="primary"
                                :loading="loading4"
                                @click="confrimPay"
                                >确 定</el-button
                            >
                            <el-button @click="cancelPay">取 消</el-button>
                        </div>
                    </template>
                </el-dialog>
            </el-row>
        </el-card>

        <el-card style="margin-top: 20px">
            <template #header>
                <svg-icon icon-class="link" /> 交易记录
            </template>

            <el-row class="card-row">
                <!-- 搜索表单 -->
                <el-form
                    ref="queryFormRef"
                    :model="filterSearch"
                    :inline="true"
                >
                    <el-form-item prop="type">
                        <span>交易类型：</span>
                        <el-select
                            v-model="filterSearch.type"
                            class="filter-item"
                            placeholder="请选择"
                            style="width: 100px"
                        >
                            <el-option
                                v-for="(key, value) in typeArrMap"
                                :key="key"
                                :label="key"
                                :value="value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="symbol">
                        <span>币种：</span>
                        <el-select
                            v-model="filterSearch.symbol"
                            class="filter-item"
                            placeholder="请选择"
                            style="width: 100px"
                        >
                            <el-option
                                v-for="item in allSymbolMap"
                                :key="item.unit"
                                :label="item.unit"
                                :value="item.unit"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="startTime">
                        <el-date-picker
                            v-model="filterSearch.startTime"
                            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="endTime">
                        <el-date-picker
                            v-model="filterSearch.endTime"
                            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>
                        <el-button
                            type="primary"
                            :icon="Search"
                            @click="searchByFilter"
                            >搜索</el-button
                        >
                        <el-button :icon="Refresh" @click="resetQuery"
                            >重置</el-button
                        >
                    </el-form-item>
                    <el-form-item>
                        <a :href="aLink" target="_self">
                            <el-button type="success" :icon="Download"
                                >导出</el-button
                            >
                        </a>
                    </el-form-item>
                </el-form>

                <!-- 数据表格 -->
                <el-table
                    ref="dataTableRef"
                    v-loading="loading2"
                    :data="trade"
                    @row-click="handleRowClick"
                    highlight-current-row
                    border
                >
                    <el-table-column
                        label="会员ID"
                        prop="memberId"
                        min-width="100"
                        align="center"
                    />
                    <el-table-column
                        label="交易类型"
                        prop="type"
                        min-width="100"
                        align="center"
                    >
                        <template #default="scope">
                            {{ typeArrMap[scope.row.type] }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="交易金额"
                        prop="amount"
                        min-width="100"
                        align="center"
                    >
                        <template #default="scope">
                            {{ tradeAmountStr(scope) }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="交易时间"
                        prop="createTime"
                        min-width="100"
                        align="center"
                    />
                </el-table>
                <!-- 分页工具条 -->
                <pagination
                    v-if="total > 0"
                    :total="total"
                    v-model:page="filterSearch.pageNo"
                    v-model:limit="filterSearch.pageSize"
                    @pagination="handleQuery"
                />
            </el-row>
        </el-card>
    </div>
</template>

<style lang="scss" scoped>
.card-row {
    p {
        color: #a9a5a5;
        span {
            color: #333;
        }
    }
}

.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}
</style>
