<template>
    <div class="app-container">
        <el-row>
            <el-col :span="22">
                <!-- 搜索表单 -->
                <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                    <el-form-item prop="memberId">
                        <el-tooltip
                            content="请输入用户ID搜索"
                            placement="bottom"
                            effect="light"
                        >
                            <el-input
                                v-model="queryParams.memberId"
                                placeholder="请输入用户ID搜索"
                                style="width: 260px"
                                clearable
                                @keyup.enter="handleQuery"
                            />
                        </el-tooltip>
                    </el-form-item>
                    <!-- <el-form-item prop="contractId" v-show="searchBox.expand">
                        <span>合约交易对：</span>
                        <el-select
                            v-model="queryParams.contractId"
                            class="filter-item"
                            placeholder="请选择"
                            style="width: 100px"
                        >
                            <el-option
                                v-for="item in state.coinList"
                                :key="item.id"
                                :value="item.id"
                                :label="item.symbol"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="contractId" v-show="searchBox.expand">
                        <span>仓位状态：</span>
                        <el-select
                            v-model="queryParams.status"
                            class="filter-item"
                            placeholder="请选择"
                            style="width: 100px"
                        >
                            <el-option value="STARTED" label="未平仓" />
                            <el-option value="PARTLYDONE" label="部分平仓" />
                            <el-option value="DONE" label="全部平仓" />
                        </el-select>
                    </el-form-item> -->
                    <el-form-item prop="phone" v-show="searchBox.expand">
                        <el-tooltip
                            content="请输入用户手机号搜索"
                            placement="bottom"
                            effect="light"
                        >
                            <el-input
                                v-model="queryParams.phone"
                                placeholder="请输入用户手机号搜索"
                                style="width: 260px"
                                clearable
                                @keyup.enter="handleQuery"
                            />
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item prop="email" v-show="searchBox.expand">
                        <el-tooltip
                            content="请输入用户邮箱搜索"
                            placement="bottom"
                            effect="light"
                        >
                            <el-input
                                v-model="queryParams.email"
                                placeholder="请输入用户邮箱搜索"
                                style="width: 260px"
                                clearable
                                @keyup.enter="handleQuery"
                            />
                        </el-tooltip>
                    </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-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-col>
            <el-col :span="2" class="right-btns">
                <el-button type="danger" @click.stop="showForceCloseAll">
                    所有用户一键平仓
                </el-button>
            </el-col>
        </el-row>
        <el-table
            :data="listdata"
            v-loading="state.loading"
            highlight-current-row
            border
        >
            <el-table-column align="center" prop="id" type="expand">
                <template #default="scope">
                    <div style="width: 98%; margin: 1% auto">
                        <el-table
                            :data="scope.row.currentPositionWithCutList"
                            border
                        >
                            <el-table-column
                                label="合约交易对"
                                prop="coin.symbol"
                                align="center"
                            />
                            <el-table-column
                                label="仓位模式"
                                prop="type"
                                align="center"
                            >
                                <template #default="scope">
                                    <div>
                                        <span
                                            :style="{
                                                background:
                                                    scope.row.type == 0
                                                        ? '#42b983'
                                                        : 'red',
                                                color: '#fff',
                                                padding: '3px 5px',
                                                'border-radius': '5px',
                                            }"
                                        >
                                            {{
                                                scope.row.type == 0
                                                    ? "全仓合仓"
                                                    : "全仓分仓"
                                            }}
                                        </span>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="仓位方向"
                                prop="contractBalance"
                                align="center"
                            >
                                <template #default="scope">
                                    <span
                                        :style="{
                                            background:
                                                scope.row.direction == 'SELL'
                                                    ? 'red'
                                                    : '#42b983',
                                            color: '#fff',
                                            padding: '3px 5px',
                                            'border-radius': '5px',
                                        }"
                                    >
                                        {{
                                            scope.row.direction == "SELL"
                                                ? "卖出开空"
                                                : "买入开多"
                                        }}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="当前盈亏 "
                                prop="currentProfit"
                                min-width="110"
                                align="center"
                            >
                                <template #default="scope">
                                    <span
                                        v-if="scope.row.currentProfit == null"
                                    ></span>
                                    <span
                                        :style="{
                                            color:
                                                scope.row.currentProfit < 0
                                                    ? 'red'
                                                    : '#42b983',
                                        }"
                                        v-else
                                        >{{
                                            scope.row.currentProfit.toFixed(2)
                                        }}</span
                                    >
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="当前跟单"
                                prop="currentProfit"
                                min-width="110"
                                align="center"
                            >
                                <template #default="scope">
                                    <span
                                        @click="
                                            (state.studentParams.traderMemberId =
                                                scope.row.memberId),
                                                studentFollowing(scope.row)
                                        "
                                        style="
                                            padding: 30px;
                                            cursor: pointer;
                                            color: #409eff;
                                        "
                                        >{{ scope.row.followCount }}</span
                                    >
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="杠杆"
                                prop="leverage"
                                align="center"
                                sortable
                            >
                                <template #default="scope">
                                    <span
                                        :style="{
                                            background:
                                                scope.row.direction == 'SELL'
                                                    ? 'red'
                                                    : '#42b983',
                                            color: '#fff',
                                            padding: '3px 5px',
                                            'border-radius': '5px',
                                        }"
                                    >
                                        <!-- {{ scope.row.direction == "SELL" ? "空" : "多" }} -->
                                        {{ scope.row.leverage }}X
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="持仓"
                                prop="availablePosition"
                                align="center"
                                sortable
                            >
                                <template #default="scope">
                                    <span
                                        v-if="scope.row.direction == 'SELL'"
                                        >{{ scope.row.availablePosition }}</span
                                    >
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="保证金"
                                prop="principalAmount"
                                align="center"
                                sortable
                            >
                                <template #default="scope">
                                    <span
                                        v-if="scope.row.principalAmount == null"
                                    ></span>
                                    <span v-else>{{
                                        scope.row.principalAmount.toFixed(2)
                                    }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="开仓价格"
                                prop="openPrice"
                                align="center"
                                sortable
                            >
                                <template #default="scope">
                                    <span
                                        v-if="scope.row.openPrice == null"
                                    ></span>
                                    <span v-else>{{
                                        scope.row.openPrice.toFixed(2)
                                    }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="当前价格"
                                prop="currentPrice"
                                align="center"
                                sortable
                            >
                                <template #default="scope">
                                    <span
                                        v-if="scope.row.currentPrice == null"
                                    ></span>
                                    <span v-else>{{
                                        scope.row.currentPrice.toFixed(2)
                                    }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="开仓时间"
                                prop="openTime"
                                align="center"
                                min-width="110"
                            />
                            <el-table-column label="操作" align="center">
                                <template #default="scope">
                                    <el-button
                                        type="danger"
                                        @click.stop="strongFlat(scope.row)"
                                        >强平</el-button
                                    >
                                </template>
                            </el-table-column>
                            <!-- <el-table-column
                            label="预估强平价"
                            prop="estimatedBlastPrice"
                            align="center"
                            sortable
                        >
                            <template #default="scope">
                                <span>{{
                                    scope.row.estimatedBlastPrice < 0
                                        ? "--.--"
                                        : scope.row.estimatedBlastPrice.toFixed(
                                              2
                                          )
                                }}</span>
                            </template>
                        </el-table-column> -->
                            <!-- <el-table-column
                            label="止盈 / 止损"
                            prop="decimalScale"
                            align="center"
                            sortable
                        >
                            <template #default="scope">
                                <div>
                                    {{
                                        scope.row.cutList[0]
                                            ? scope.row.cutList[0].profitPrice
                                            : ""
                                    }}
                                    /
                                    {{
                                        scope.row.cutList[0]
                                            ? scope.row.cutList[0].lossPrice
                                            : ""
                                    }}
                                </div>
                            </template>
                        </el-table-column> -->
                        </el-table>
                    </div>
                </template>
            </el-table-column>

            <el-table-column align="center" prop="id" label="会员ID" />
            <el-table-column
                align="center"
                prop="username"
                label="用户名称"
                width="200"
            />
            <el-table-column align="center" prop="balance" label="仓位数量">
                <template #default="scope">
                    {{ scope.row.currentPositionWithCutList.length }}
                </template>
            </el-table-column>
            <el-table-column
                label="当前总盈亏 "
                prop="currentProfit"
                min-width="110"
                align="center"
            >
                <template #default="scope">
                    <span v-if="TotalProfitAndLoss(scope.row) == null"></span>
                    <span
                        :style="{
                            color:
                                TotalProfitAndLoss(scope.row) < '0'
                                    ? 'red'
                                    : '#42b983',
                        }"
                        v-else
                        >{{ TotalProfitAndLoss(scope.row) }}</span
                    >
                </template>
            </el-table-column>
            <el-table-column align="center" prop="balance" label="账户余额">
                <template #default="scope">
                    {{ truncation(scope.row.balance) }}
                </template>
            </el-table-column>
            <!-- <el-table-column
                align="center"
                prop="frozenBalance"
                label="已用保证金"
                ><template #default="scope">
                    {{ truncation(scope.row.frozenBalance) }}
                </template>
            </el-table-column> -->
            <!-- <el-table-column
                align="center"
                prop="frozenMargin"
                label="冻结保证金"
            /> -->
            <!-- <el-table-column align="center" prop="leverage" label="杠杆" /> -->
            <el-table-column
                align="center"
                prop="cashBalance"
                label="资金账户余额"
            >
                <template #default="scope">
                    {{ truncation(scope.row.cashBalance) }}
                </template>
            </el-table-column>
            <el-table-column
                align="center"
                prop="currentCapital"
                label="账户当前权益"
            >
                <template #default="scope">
                    {{ truncation(scope.row.currentCapital) }}
                </template>
            </el-table-column>
            <!-- <el-table-column
                align="center"
                prop="currentBalance"
                label="账户当前余额(调整保证金后)"
            >
                <template #default="scope">
                    {{ truncation(scope.row.currentBalance) }}
                </template>
            </el-table-column> -->
            <el-table-column
                align="center"
                prop="currentMargin"
                label="账户当前保证金"
            >
                <template #default="scope">
                    {{ truncation(scope.row.currentMargin) }}
                </template>
            </el-table-column>

            <!-- <el-table-column align="center" prop="nickname" label="创建时间">
                <template #default="scope">
                    <span>{{ timestampToTime(scope.row.createdTime) }}</span>
                </template>
            </el-table-column> -->
        </el-table>
        <!-- 强平 -->
        <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="ID" prop="positionId">
                    <el-input
                        type="text"
                        v-model="formData.positionId"
                        readonly
                        disabled
                    />
                </el-form-item>
                <el-form-item label="管理员" prop="username">
                    <el-input
                        type="text"
                        v-model="formData.username"
                        readonly
                        disabled
                    />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input
                        type="password"
                        v-model="formData.password"
                        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>
        <!-- 所有用户一键平仓弹窗 -->
        <el-dialog
            :title="fcaDialog.title"
            v-model="fcaDialog.visible"
            width="640px"
            destroy-on-close
        >
            <el-form
                ref="fcaDataFormRef"
                :model="fcaFormData"
                :rules="rules"
                label-width="136px"
            >
                <el-form-item label="管理员" prop="username">
                    <el-input
                        type="text"
                        v-model="fcaFormData.username"
                        readonly
                        disabled
                    />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input
                        type="password"
                        v-model="fcaFormData.password"
                        placeholder="请输入"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button
                        type="primary"
                        :loading="loading"
                        @click="submitFcaFormData"
                        >确 定</el-button
                    >
                    <el-button @click="fcaCancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <pagination
            v-if="state.total > 0"
            :total="state.total"
            v-model:page="state.queryParams.pageNo"
            v-model:limit="state.queryParams.pageSize"
            @pagination="handleQuery"
        />
        <el-dialog v-model="state.dialogTableVisible" title="学生跟随列表">
            <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"
                />
                <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="profitOrLoss"
                    label="本单盈亏"
                    align="center"
                >
                    <template #default="scope">
                        <span>{{
                            truncation(scope.row.profitOrLoss)
                        }}</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.studentParams.currentPage"
                v-model:limit="state.studentParams.pageSize"
                @pagination="studentFollowing"
            />
        </el-dialog>
    </div>
</template>
<script lang="ts">
name: "traderPosition";
</script>
<script lang="ts" setup>
import {
    followTrader,
    forceCloseOut,
    forceCloseAll,
    studentFollowingList,
} from "@/api/documentary/index";
import { Search, Refresh, ArrowUp, ArrowDown } from "@element-plus/icons-vue";

import { onMounted, onUnmounted, reactive, toRefs, ref } from "vue";
import { localStorage } from "@/utils/storage";
import { ElMessage, ElForm } from "element-plus";

import { truncation } from "@/utils/filter";
const state = reactive({
    queryParams: {
        pageNo: 1,
        pageSize: 15,
        contractId: "",
        memberId: "",
        phone: "",
        email: "",
        status: "STARTED",
        hasPosition: 1,
        isTrader: 1,
    },
    searchBox: {
        title: "展开搜索",
        expand: false,
    },
    loading: true,
    listdata: [],
    total: 0,
    formData: {
        positionId: 0,
        username: "",
        password: "",
    },
    dialog: {
        title: "",
        visible: false,
    },
    rules: {
        password: [
            { required: true, message: "密码不能为空", trigger: "blur" },
        ],
    },
    fcaDialog: {
        title: "",
        visible: false,
    },
    fcaFormData: {
        username: "",
        password: "",
    },
    dialogTableVisible: false,
    studentFollowingData: [],
    studentTotal: 0,
    memberId: 0,
    follow: true,
    studentParams: {
        currentPage: 1,
        pageSize: 15,
        traderMemberId: "",
        hasPosition: true,
        symbol: "",
        direction: "" as any,
    },
});
const queryFormRef = ref(ElForm);
const fcaDataFormRef = ref(ElForm);

const {
    queryParams,
    listdata,
    loading,
    total,
    formData,
    dialog,
    rules,
    searchBox,
    fcaFormData,
    fcaDialog,
} = toRefs(state);
const handleQuery = () => {
    followTrader(state.queryParams).then((res: any) => {
        state.listdata = res.data.content;
        state.loading = false;
        state.total = res.data.totalElements;
    });
};
// 强平

const strongFlat = (row: any) => {
    state.dialog = {
        title: "强平",
        visible: true,
    };

    formData.value.positionId = row.id;
    formData.value.username = localStorage.get("user");
    formData.value.password = "";
};
// 提交强平
const submitFormData = () => {
    forceCloseOut(state.formData).then((res: any) => {
        if (res.code == 0) {
            state.dialog = {
                title: "",
                visible: false,
            };
            ElMessage.success(res.message);
            handleQuery();
        }
    });
};
// 取消提交
const cancel = () => {
    state.dialog = {
        title: "",
        visible: false,
    };
};

// 获取跟随学生列表
const studentFollowing = (row: any) => {
    if (row.followCount < 1) {
        return;
    }
    state.studentParams.direction = row.direction == "BUY" ? 0 : 1;
    state.studentParams.symbol = row.coin.symbol;
    state.dialogTableVisible = true;
    studentFollowingList(state.studentParams, state.memberId).then(
        (res: any) => {
            state.studentFollowingData = res.data.records;
            state.studentTotal = res.data.total;
            console.log(state.studentFollowingData);
            state.follow = false;
        }
    );
};

// 定时刷新
let refreshTimer: ReturnType<typeof setInterval> | null = null

const periodicRefresh = () => {
    refreshTimer = setInterval(() => {
        state.loading = false;
        handleQuery();
    }, 30000);
};

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

/**
 * 查询重置
 */
function resetQuery() {
    queryFormRef.value.resetFields();
    handleQuery();
}

/**
 * 所有用户一键平仓
 */
const showForceCloseAll = () => {
    state.fcaDialog = {
        title: "所有用户一键平仓",
        visible: true,
    };
    fcaFormData.value.username = localStorage.get("user");
    fcaFormData.value.password = "";
};

/**
 * 提交所有用户一键平仓
 */
function submitFcaFormData() {
    fcaDataFormRef.value.validate((valid: any) => {
        if (valid) {
            loading.value = true;
            forceCloseAll(state.fcaFormData)
                .then((res: any) => {
                    if (!res.code) {
                        ElMessage.success(res.message);
                        fcaCancel();
                        loading.value = false;
                        handleQuery();
                    } else {
                        ElMessage.error(res.message);
                        fcaCancel();
                        loading.value = false;
                    }
                })
                .catch(() => {
                    loading.value = false;
                });
        }
    });
}

/**
 * 取消所有用户一键平仓
 */
function fcaCancel() {
    fcaDialog.value.visible = false;
    fcaFormData.value.password = "";
    fcaDataFormRef.value.resetFields();
    fcaDataFormRef.value.clearValidate();
}

// 获取当前总盈亏
const TotalProfitAndLoss = (row: any) => {
    let total = 0;
    row.currentPositionWithCutList.map((item: any) => {
        total = total + item.currentProfit;
    });
    return (Math.floor(total * 100) / 100).toFixed(2);
};

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

onUnmounted(() => {
    if (refreshTimer) { clearInterval(refreshTimer); refreshTimer = null; }
});
</script>

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