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

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import { ElForm, ElTable, ElMessage } from "element-plus";
import { Search, Refresh, ArrowUp, ArrowDown } from "@element-plus/icons-vue";
import { localStorage } from "@/utils/storage";
import SecondContract from "./components/SecondContract.vue";
import {
    queryPositionList,
    forceCloseAll,
    contractWalletLock,
    contractWalletUnLock,
    forceCloseOut,
    orderQuantity,
} from "@/api/swap";
import {
    ContractQueryParam,
    ContractItem,
    ForceCloseAllParam,
    ForceCloseOutParam,
} from "@/types/api/swap";
import { queryContractCoinList } from "@/api/system/dashboard";
import { ContractCoinListResponseData } from "@/types/api/system/dashboard";

const queryFormRef = ref(ElForm);
const dataTableRef = ref(ElTable);
const dataFormRef = ref(ElForm);
const fcaDataFormRef = ref(ElForm);

const state = reactive({
    loading: true,
    loading2: false,
    loading3: false,
    coinList: [] as ContractCoinListResponseData,
    searchBox: {
        title: "展开搜索",
        expand: false,
    },
    queryParams: {
        pageNo: 1,
        pageSize: 15,
        contractId: "",
        memberId: "",
        phone: "",
        email: "",
        status: "STARTED",
        hasPosition: 1,
    } as ContractQueryParam,
    list: [] as ContractItem[],
    total: 0,
    dialog: {
        title: "",
        visible: false,
    },
    fcaDialog: {
        title: "",
        visible: false,
    },
    formData: {
        memberId: "",
        username: "",
        password: "",
    } as ForceCloseOutParam,
    fcaFormData: {
        username: "",
        password: "",
    } as ForceCloseAllParam,
    rules: {
        password: [
            { required: true, message: "密码不能为空", trigger: "blur" },
        ],
    },
});

const {
    loading,
    loading2,
    loading3,
    coinList,
    searchBox,
    queryParams,
    list,
    total,
    dialog,
    fcaDialog,
    formData,
    fcaFormData,
    rules,
} = toRefs(state);

function handleQuery() {
    orderQuantity(state.queryParams).then(({ data }) => {
        state.list = data.content;
        state.total = data.totalElements;
        state.loading = false;
    });
}

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

/**
 * 获取合约交易对
 */
// const getContractCoinList = () => {
//     queryContractCoinList({ pageNo: 1, pageSize: 1000 }).then(({ data }) => {
//         state.coinList = data.content;
//     });
// };

// 当前盈亏排序
const sortChange = (row: any) => {
    TotalProfitAndLoss(row);
};

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

/**
 * 禁止平仓
 */
const cwLock = (row: any) => {
    state.loading2 = true;
    contractWalletLock({ id: row.id })
        .then((res: any) => {
            if (!res.code) {
                state.loading2 = false;
                ElMessage.success(res.message);
                handleQuery();
            } else {
                state.loading2 = false;
                ElMessage.error(res.message);
            }
        })
        .catch(() => {
            loading2.value = false;
        });
};

/**
 * 可以平仓
 */
const cwUnLock = (row: any) => {
    state.loading2 = true;
    contractWalletUnLock({ id: row.id })
        .then((res: any) => {
            if (!res.code) {
                state.loading2 = false;
                ElMessage.success(res.message);
                handleQuery();
            } else {
                state.loading2 = false;
                ElMessage.error(res.message);
            }
        })
        .catch(() => {
            state.loading2 = false;
        });
};

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

    formData.value.positionId = row.id;
    formData.value.username = localStorage.get("user");
    formData.value.password = "";
};

/**
 * 提交强平
 */
function submitFormData() {
    dataFormRef.value.validate((valid: any) => {
        if (valid) {
            loading3.value = true;
            forceCloseOut(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() {
    dialog.value.visible = false;
    formData.value.positionId = "";
    formData.value.password = "";
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
}

/**
 * 所有用户一键平仓
 */
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;
                    } 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 closeSearch = () => {
    state.searchBox.expand = !state.searchBox.expand;
    state.searchBox.title = !state.searchBox.expand ? "展开搜索" : "收起搜索";
};

// 定时刷新

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

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

<template>
    <div class="app-container">
        <!-- <el-row> </el-row> -->
        <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
            ref="dataTableRef"
            v-loading="loading"
            :data="list"
            highlight-current-row
            border
            @sort-change="sortChange"
        >
            <el-table-column type="expand">
                <template #default="scope">
                    <SecondContract
                        :id="scope.row.id + ''"
                        width="98%"
                        height="auto"
                    />
                </template>
            </el-table-column>
            <el-table-column label="会员ID" prop="id" align="center" />
            <el-table-column
                label="会员账号"
                prop="username"
                min-width="120"
                align="center"
            />
            <el-table-column
                label="仓位数量"
                prop="coin.symbol"
                min-width="120"
                align="center"
            >
                <template #default="scope">
                    {{ scope.row.currentPositionWithCutList.length }}
                </template>
            </el-table-column>
            <el-table-column
                label="当前盈亏 "
                prop="currentProfit"
                min-width="110"
                align="center"
                sortable
            >
                <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
                label="资产账户"
                prop="cashBalance"
                min-width="140"
                align="center"
                sortable
            >
                <template #default="scope">
                    {{
                        (Math.floor(scope.row.cashBalance * 100) / 100).toFixed(
                            2
                        )
                    }}
                </template>
            </el-table-column>
            <el-table-column
                label="合约账户"
                prop="balance"
                min-width="140"
                align="center"
                sortable
            >
                <template #default="scope">
                    {{ (Math.floor(scope.row.balance * 100) / 100).toFixed(2) }}
                </template>
            </el-table-column>
            <!-- <el-table-column
                label="仓位模式"
                prop="type"
                min-width="140"
                align="center"
                sortable
            >
                <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"
                min-width="140"
                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"
                                ? "卖出开空"
                                : "买入开多"
                        }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column
                label="多仓盈亏 "
                prop="currentProfit"
                min-width="110"
                align="center"
                sortable
            >
                <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="leverage"
                min-width="130"
                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"
                min-width="140"
                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"
                min-width="110"
                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"
                min-width="110"
                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"
                min-width="110"
                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="estimatedBlastPrice"
                min-width="140"
                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"
                min-width="140"
                align="center"
                sortable
            >
                <template #default="scope">
                    <div>
                        {{
                            scope.row.cutList[0]
                                ? scope.row.cutList[0].profitPrice
                                : ""
                        }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                label="止损位"
                prop="decimalScale"
                min-width="140"
                align="center"
                sortable
            >
                <template #default="scope">
                    <div>
                        {{
                            scope.row.cutList[0]
                                ? scope.row.cutList[0].lossPrice
                                : ""
                        }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                label="空仓盈亏 "
                prop="currentProfit"
                min-width="110"
                align="center"
                sortable
            >
                <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="leverage"
                min-width="130"
                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"
                min-width="140"
                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"
                min-width="110"
                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"
                min-width="110"
                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"
                min-width="110"
                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="estimatedBlastPrice"
                min-width="140"
                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"
                min-width="140"
                align="center"
                sortable
            >
                <template #default="scope">
                    <div>
                        {{
                            scope.row.cutList[0]
                                ? scope.row.cutList[0].profitPrice
                                : ""
                        }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                label="止损位"
                prop="decimalScale"
                min-width="140"
                align="center"
                sortable
            >
                <template #default="scope">
                    <div>
                        {{
                            scope.row.cutList[0]
                                ? scope.row.cutList[0].lossPrice
                                : ""
                        }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column
                label="开仓类型"
                prop="openType"
                min-width="110"
                align="center"
                sortable
            >
                <template #default="scope">
                    <span v-if="scope.row.openType == 0">市价委托</span>
                    <span v-else-if="scope.row.openType == 1">限价委托</span>
                    <span v-else-if="scope.row.openType == 2">计划委托</span>
                    <span v-else>--</span>
                </template>
            </el-table-column>

            <el-table-column
                label="状态"
                prop="status"
                min-width="110"
                align="center"
                sortable
            >
                <template #default="scope">
                    <span v-if="scope.row.status == 'STARTED'">未平仓</span>
                    <span v-else-if="scope.row.status == 'PARTLYDONE'"
                        >部分平仓</span
                    >
                    <span v-else-if="scope.row.status == 'DONE'">全部平仓</span>
                    <span v-else>--</span>
                </template>
            </el-table-column>
            <el-table-column
                label="创建时间"
                prop="createTime"
                min-width="160"
                align="center"
                sortable
            /> -->
            <!-- <el-table-column
                label="操作"
                align="center"
                width="180"
                fixed="right"
            >
                <template #default="scope">
                    <el-button
                        v-if="scope.row.isLock == 1"
                        type="success"
                        size="small"
                        :loading="loading2"
                        @click.stop="cwUnLock(scope.row)"
                        >可以平仓</el-button
                    >
                    <el-button
                        v-else
                        type="danger"
                        size="small"
                        :loading="loading2"
                        @click.stop="cwLock(scope.row)"
                        >禁止平仓</el-button
                    >
                    <el-button
                        type="primary"
                        size="small"
                        :loading="loading3"
                        @click.stop="showForceCloseOut(scope.row)"
                        >强平</el-button
                    >
                </template>
            </el-table-column> -->
        </el-table>

        <!-- 分页工具条 -->
        <pagination
            v-if="total > 0"
            :total="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="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>
    </div>
</template>

<style lang="scss" scoped>
.right-btns {
    text-align: right;
    margin-bottom: 20px;
}
</style>
