<template>
    <div :id="id" :class="className" :style="{ height, width }">
        <!-- 数据表格 -->
        <el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="recordList"
            highlight-current-row
            border
        >
            <el-table-column
                label="合约交易对"
                prop="coin.symbol"
                min-width="100"
                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"
                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"
                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="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-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="操作"
                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>
        <!-- 强平 -->
        <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>

        <!-- 分页工具条 -->
        <pagination
            v-if="total > 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
        />
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from "vue";
import { localStorage } from "@/utils/storage";

import { ElForm, ElTable, ElMessage } from "element-plus";
import {
    queryPositionList,
    forceCloseAll,
    contractWalletLock,
    contractWalletUnLock,
    forceCloseOut,
    orderQuantity,
} from "@/api/swap";
import {
    ContractQueryParam,
    ContractItem,
    ForceCloseAllParam,
    ForceCloseOutParam,
} from "@/types/api/swap";
const dataTableRef = ref(ElTable);
const dataFormRef = ref(ElForm);
const state = reactive({
    loading: true,
    loading2: false,
    loading3: false,
    queryParams: {
        pageNo: 1,
        pageSize: 15,
        contractId: "",
        memberId: "",
        phone: "",
        email: "",
        status: "STARTED",
    } as ContractQueryParam,
    recordList: [] as ContractItem[],
    total: 0,
    formData: {
        memberId: "",
        username: "",
        password: "",
    } as ForceCloseOutParam,
    dialog: {
        title: "",
        visible: false,
    },
    rules: {
        password: [
            { required: true, message: "密码不能为空", trigger: "blur" },
        ],
    },
});

const {
    loading,
    queryParams,
    recordList,
    total,
    loading2,
    loading3,
    formData,
    dialog,
    rules,
} = toRefs(state);

/**
 * 排序
 */
// function handleSortChange(column: any) {
//     var sortingType = column.order;
//     state.queryParams.property = column.prop;
//     if (sortingType === "ascending") {
//         state.queryParams.direction = "1";
//     } else if (sortingType === "descending") {
//         state.queryParams.direction = "0";
//     } else {
//         state.queryParams.property = "id";
//         state.queryParams.direction = "1";
//     }
//     handleQuery();
// }

/**
 * 查询重置
 */
// 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 props = defineProps({
    id: {
        type: String,
        default: "0",
    },
    className: {
        type: String,
        default: "sr-body",
    },
    width: {
        type: String,
        default: "100px",
        required: true,
    },
    height: {
        type: String,
        default: "100px",
        required: true,
    },
});

const handleQuery = () => {
    state.loading = true;
    orderQuantity(state.queryParams).then(({ data }) => {
        state.recordList = data.content[0].currentPositionWithCutList;
        state.total = data.totalElements;
        state.loading = false;
    });
};

// 定时刷新

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

onMounted(() => {
    state.queryParams.memberId = props.id;
    handleQuery();
    periodicRefresh();
});
</script>

<style lang="scss" scoped>
.sr-body {
    margin: 10px auto;
}
</style>
