<template>
    <div class="app-container" style="display: flex">
        <div>
            <el-form
                label-width="100px"
                :model="state.submittingContent"
                style="max-width: 460px"
                :rules="state.rules"
            >
                <el-form-item label="特级用户">
                    <el-select
                        v-model="state.submittingContent.memberId"
                        class="m-2"
                        placeholder="请选择用户"
                        size="small"
                    >
                        <el-option
                            @click.stop="cut(state.submittingContent.symbol)"
                            v-for="item in state.aListOfPremiumUsers"
                            :key="item.id"
                            :label="item.username"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="交易对">
                    <el-select
                        v-model="state.submittingContent.symbol"
                        class="m-2"
                        placeholder="请选择交易对"
                        size="small"
                    >
                        <el-option
                            @click.stop="cut(state.submittingContent.symbol)"
                            v-for="item in state.list"
                            :key="item.id"
                            :label="item.symbol"
                            :value="item.symbol"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="当前盈亏">
                    <el-input
                        disabled
                        style="width: 175px"
                        v-model="state.profitLossSum"
                    />
                </el-form-item>
                <el-form-item v-if="state.show">
                    <el-button
                        type="danger"
                        @click.stop="reset(state.submittingContent)"
                        >正常平仓</el-button
                    >
                </el-form-item>
                <hr />
                <hr />
                <el-form-item label="平仓方向" prop="direction">
                    <el-select
                        v-model="state.submittingContent.direction"
                        class="m-2"
                        placeholder="请选择平仓方向"
                        size="small"
                    >
                        <el-option label="卖出平空" value="0" />
                        <el-option label="卖出平多" value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="开仓价格" prop="openPrice">
                    <el-input
                        style="width: 175px"
                        v-model="state.submittingContent.openPrice"
                        placeholder="请输入开仓价格"
                    />
                </el-form-item>
                <el-form-item label="平仓价格" prop="settlementPrice">
                    <el-input
                        style="width: 175px"
                        v-model="state.settlementPrice"
                        placeholder="请输入平仓价格"
                    />
                </el-form-item>
                <el-form-item label="下单数量">
                    <el-input
                        style="width: 175px"
                        v-model="state.totalPosition"
                        placeholder="请输入下单数量"
                    />
                </el-form-item>
                <el-form-item label="当前价格">
                    <el-input
                        disabled
                        style="width: 175px"
                        v-model="state.currentPrice"
                    />
                </el-form-item>
                <!-- <el-form-item label="保证金">
                    <el-input
                        disabled
                        style="width: 175px"
                        v-model="state.liquidationList.principalAmount"
                    />
                </el-form-item> -->
                <el-form-item label="收益">
                    <div>
                        {{ earnings() }}
                    </div>
                </el-form-item>
                <!-- <el-form-item label="收益率">
                    <div>
                        {{
                            (
                                (earnings() /
                                    state.liquidationList.principalAmount) *
                                100
                            ).toFixed(2) + "%"
                        }}
                    </div>
                </el-form-item> -->

                <el-form-item v-if="state.show">
                    <el-button
                        type="primary"
                        @click.stop="submitting(state.submittingContent)"
                        >提交</el-button
                    >

                    <el-button @click.stop="clearContents()">取消</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div id="mychart" style="width: 100%; height: 500px"></div>
    </div>
</template>

<script lang="ts">
name: "management";
</script>

<script lang="ts" setup>
import {
    specialMerchandisingManagement,
    detailsOfTheContract,
    orderQuantity,
    resetState,
    gettingTheId,
    kLineData,
} from "@/api/documentary/index";
import { queryContractCoinList } from "@/api/system/dashboard";
import {
    onMounted,
    ref,
    reactive,
    toRefs,
    onUnmounted,
    onBeforeUnmount,
} from "vue";
import { ElMessage } from "element-plus";
import { Content } from "@/types/api/system/dashboard";
import { orderQuantityItem } from "@/types/api/documentary/index";
import * as echarts from "echarts";
import { timestampToTime } from "@/utils/filter";
import { io } from "socket.io-client";

const state = reactive({
    submittingContent: {
        symbol: "",
        amount: "",
        direction: "",
        closePrice: "",
        openPrice: "",
        memberId: "",
    },

    list: [] as Content[],
    rules: {
        price: [
            {
                required: true,
                message: "不能为空",
                trigger: "blur",
            },
        ],
    },
    kLineParams: {
        symbol: "BTC/USDT",
        from: "1669737600000" as any,
        to: "" as any,
        resolution: "1" as any,
    },
    queryParams: {
        pageNo: 1,
        pageSize: 50,
    },
    currentPriceList: [],
    liquidationList: [] as orderQuantityItem[],
    show: true,
    settlementPrice: "",
    aListOfPremiumUsers: [] as Content[],
    transactionParams: {
        memberId: "",
        symbol: "",
    },
    myChartData: {
        dates: [],
        data: [],
    },
    socketdata: {
        // url: "ws://121.40.165.18:8800",
        // url: "http://127.0.0.1:3000",
        url: "ws://47.242.41.34:38986",
    },
    profitLossSum: "" as any, //当前盈亏
    totalPosition: "" as any, //下单数量
    currentPrice: "" as any, //当前价格
});
const {
    currentPriceList,
    liquidationList,
    submittingContent,
    transactionParams,
    myChartData,
} = toRefs(state);
const handleQuery = () => {
    queryContractCoinList(state.queryParams).then(({ data }) => {
        state.list = data.content.filter((item: any) => {
            return item.symbol == "ETH/USDT" || item.symbol == "BTC/USDT";
        });
    });
    // detailsOfTheContract().then((res) => {
    //     state.currentPriceList = res.data;
    // });
    gettingTheId().then((res) => {
        state.aListOfPremiumUsers = res.data;
    });
};

// 获取echart 数据

const echartData = () => {
    state.kLineParams.to = Date.parse(new Date().toLocaleString());
    state.kLineParams.from =
        state.kLineParams.to - state.kLineParams.resolution * 1000 * 60 * 100;
    kLineData(state.kLineParams).then((res: any) => {
        state.myChartData.data = res.map(function (item: any) {
            return [
                +item[1],
                +item[4],
                +item[3],
                +item[2],
                +item[5],
                (item[4] - item[1]).toFixed(6),
                ((item[4] - item[1]) / item[4]).toFixed(6) + "%",
            ];
        });
        state.myChartData.dates = res.map(function (item: any) {
            return timestampToTime(item[0]);
        });
        initEcharts();
    });
};

// 获取MA数据

const calculateMA = (dayCount: number, data: any[]) => {
    var result = [];
    for (var i = 0, len = data.length; i < len; i++) {
        if (i < dayCount) {
            result.push("-");
            continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
            sum += +data[i - j][1];
        }
        result.push((sum / dayCount).toFixed(2));
    }
    return result;
};

// 提交测试价格
const submitting = (row: any) => {
    state.submittingContent.closePrice = state.settlementPrice;
    specialMerchandisingManagement(row).then((res: any) => {
        if (res.code == 0) {
            ElMessage.success(res.message);
            clearContents();
        } else {
            ElMessage.error(res.message);
            clearContents();
        }
    });
};
// 取消提交
const clearContents = () => {
    (state.submittingContent.symbol = ""),
        (state.submittingContent.amount = "");
    state.submittingContent.direction = "";
    state.submittingContent.openPrice = "";
    state.submittingContent.memberId = "";
    state.settlementPrice = "";
    state.submittingContent.amount = "";
    state.totalPosition = "";
    // state.liquidationList.principalAmount = 0;
    state.profitLossSum = "";
    state.currentPrice = "";
    state.currentPriceList[state.submittingContent.symbol] = 0;
};

// 重置交易员状态

const reset = (row: any) => {
    resetState(row).then((res: any) => {
        if (res.code == 0) {
            ElMessage.success(res.message);
        }
    });
};

onMounted(() => {
    handleQuery();
    echartData();
    // createSocket();
});

// 定时刷新当前价格
setInterval(() => {
    if (state.submittingContent.symbol == "") {
    } else {
        orderQuantity(state.transactionParams).then((res: any) => {
            if (res.data.length < 1) {
                state.show = false;
                state.totalPosition = 0;
                ElMessage.warning(
                    `交易对${state.submittingContent.symbol}没有持仓`
                );
            } else {
                state.liquidationList = res.data;
                state.currentPrice = state.liquidationList[0].currentPrice;
                state.show = true;
                let sum = 0;
                state.liquidationList.forEach((item: any) => {
                    sum += item.currentProfit;
                    return sum;
                });
                state.profitLossSum = sum.toFixed(2);
            }
        });
    }
}, 3000);

//echart 准时刷新

let echartTime = setInterval(() => {
    let i = 0;
    if (new Date().getSeconds() == 59) {
        i++;
        if (i == state.kLineParams.resolution) {
            setTimeout(() => {
                echartData();
                i = 0;
            }, 1500);
        }
    }
}, 1000);

// 清除定时器
onBeforeUnmount(() => {
    clearInterval(echartTime);
});
// 切换交易对提醒

const cut = (row: any) => {
    state.transactionParams.memberId = state.submittingContent.memberId;
    state.transactionParams.symbol = state.submittingContent.symbol;
    state.kLineParams.symbol = state.transactionParams.symbol;
    if (state.kLineParams.symbol !== "") {
        echartData();
    }
    if (
        state.transactionParams.memberId !== "" &&
        state.transactionParams.symbol !== ""
    ) {
        orderQuantity(state.transactionParams).then((res: any) => {
            if (res.data.length < 1) {
                state.show = false;
                state.totalPosition = 0;
                ElMessage.warning(`交易对${row}没有持仓`);
            } else {
                state.liquidationList = res.data;
                state.show = true;
                state.currentPrice = state.liquidationList[0].currentPrice;
                state.show = true;
                let sum = 0;
                state.liquidationList.forEach((item: any) => {
                    sum += item.currentProfit;
                    return sum;
                });
                state.profitLossSum = sum.toFixed(2);
                let j = 0;
                for (
                    let i = 0;
                    i < state.liquidationList.length - 1 &&
                    j <= state.liquidationList.length - 1;
                    i++
                ) {
                    j = i + 1;
                    if (
                        state.liquidationList[i].totalPosition >
                        state.liquidationList[j].totalPosition
                    ) {
                        state.totalPosition =
                            state.liquidationList[i].totalPosition;
                    } else {
                        state.totalPosition =
                            state.liquidationList[j].totalPosition;
                    }
                }
            }
        });
    }
};

// 计算收益

const earnings = () => {
    state.submittingContent.amount = "" + state.totalPosition;
    if (Number(state.submittingContent.direction) == 1) {
        return parseFloat(
            (
                (parseFloat(state.submittingContent.openPrice) -
                    parseFloat(state.settlementPrice)) *
                    -1 *
                    parseFloat(state.submittingContent.amount) +
                parseFloat(state.profitLossSum)
            ).toFixed(2)
        );
    } else {
        return parseFloat(
            (
                (parseFloat(state.submittingContent.openPrice) -
                    parseFloat(state.settlementPrice)) *
                    parseFloat(state.submittingContent.amount) *
                    1 +
                parseFloat(state.profitLossSum)
            ).toFixed(2)
        );
    }
};

// 绘制K线

const initEcharts = () => {
    const option = {
        legend: {
            data: ["日K", "MA5", "MA10", "MA20", "MA30"],
            inactiveColor: "#777",
        },
        tooltip: {
            trigger: "axis",
            confine: true,
            axisPointer: {
                animation: true,
                type: "cross",
                lineStyle: {
                    color: "#376df4",
                    width: 1,
                    opacity: 1,
                },
            },
            show: true,
        },
        title: {
            text: state.kLineParams.symbol,
            left: "10%",
            subtext: `MA5:${
                calculateMA(5, state.myChartData.data)[
                    calculateMA(5, state.myChartData.data).length - 1
                ]
            }  MA10:${
                calculateMA(10, state.myChartData.data)[
                    calculateMA(10, state.myChartData.data).length - 1
                ]
            }  MA20:${
                calculateMA(20, state.myChartData.data)[
                    calculateMA(20, state.myChartData.data).length - 1
                ]
            }  MA30:${
                calculateMA(30, state.myChartData.data)[
                    calculateMA(30, state.myChartData.data).length - 1
                ]
            }`,
        },
        xAxis: {
            type: "category",
            data: state.myChartData.dates,

            axisLine: { lineStyle: { color: "#8392A5" }, onZero: true },
            boundaryGap: false,
            splitLine: { show: true },
            min: "dataMin",
            max: "dataMax",
        },
        yAxis: {
            scale: true,
            axisLine: { lineStyle: { color: "#8392A5" } },
            splitLine: { show: true },
            position: "right",
        },
        grid: {
            bottom: 80,
            show: true,
        },
        dataZoom: [
            {
                type: "inside",
                xAxisIndex: [0, 1],
                start: 40,
                end: 100,
                minValueSpan: 10,
            },
            {
                show: true,
                type: "slider",
                xAxisIndex: [0, 1],
                top: "90%",
                start: 50,
                end: 100,
            },
        ],
        series: [
            {
                type: "candlestick",
                name: "日K",
                data: state.myChartData.data,
                barWidth: "85%",
                itemStyle: {
                    color: "#0CF49B",
                    color0: "#FD1050",
                    borderColor: "#0CF49B",
                    borderColor0: "#FD1050",
                },
                barMinHeight: 20,
                markPoint: {
                    data: [
                        {
                            type: "max",
                            y: "14%",
                            valueDim: "highest",
                        },
                        {
                            type: "min",
                            itemStyle: { color: "#FD1050" },
                            y: "80%",
                            valueDim: "lowest",
                        },
                        {
                            x: "92%",
                            yAxis: state.myChartData.data[
                                state.myChartData.data.length - 1
                            ][0],

                            value: state.myChartData.data[
                                state.myChartData.data.length - 1
                            ][0],
                            animation: true,
                            label: {
                                show: true,
                                color: "white",
                            },
                            itemStyle: { color: "rgba(176, 164, 164, 1)" },
                        },
                    ],
                    value: state.myChartData.data[
                        state.myChartData.data.length
                    ],
                    xAxis: 0,
                    yAxis: state.myChartData.data[
                        state.myChartData.data.length
                    ],
                    emphasis: {
                        disabled: true,
                    },

                    label: {
                        show: true,
                        color: "white",
                        position: "inside",
                    },
                    symbol: "Rect",
                    symbolKeepAspect: true,
                    symbolSize: [50, 15],
                    symbolRotate: 0,
                },
                tooltip: {
                    trigger: "item",
                    formatter: function (params: any) {
                        let htmlStr = "<div>";
                        htmlStr +=
                            "<span style='min-height: 20pt; font-size: 10pt'>";
                        htmlStr += params.name + "<br/>";
                        htmlStr += "开:" + params.data[1] + "<br/>";
                        htmlStr += "高:" + params.data[4] + "<br/>";
                        htmlStr += "低:" + params.data[3] + "<br/>";
                        htmlStr += "收:" + params.data[2] + "<br/>";
                        htmlStr += "涨跌额:" + params.data[6] + "<br/>";
                        htmlStr += "涨跌幅:" + params.data[7] + "<br/>";
                        htmlStr +=
                            "成交量:" +
                            params.data[5] +
                            "<br/>" +
                            "</span>" +
                            "</div>";
                        return htmlStr;
                    },
                },
            },
            {
                name: "MA5",
                type: "line",
                data: calculateMA(5, state.myChartData.data),
                smooth: true,
                showSymbol: false,
                lineStyle: {
                    width: 1,
                },
            },
            {
                name: "MA10",
                type: "line",
                data: calculateMA(10, state.myChartData.data),
                smooth: true,
                showSymbol: false,
                lineStyle: {
                    width: 1,
                },
            },
            {
                name: "MA20",
                type: "line",
                data: calculateMA(20, state.myChartData.data),
                smooth: true,
                showSymbol: false,
                lineStyle: {
                    width: 1,
                },
            },
            {
                name: "MA30",
                type: "line",
                data: calculateMA(30, state.myChartData.data),
                smooth: false,
                showSymbol: false,
                lineStyle: {
                    width: 1,
                },
            },
        ],
    };
    const myChart = echarts.init(document.getElementById("mychart") as any);
    myChart.setOption(option);
    // 随着屏幕大小调节图表;
    window.addEventListener("resize", () => {
        myChart.resize();
    });
};

// 添加Socket连接

const createSocket = () => {
    const socket = io(state.socketdata.url, {
        transports: ["websocket"],
        path: "",
    });
    socket.on("error", (error: any) => {
        console.log(error);
    });
    socket.on("connect", () => {
        console.log("连接成功");
    });

    socket.on("message", (msg: any) => {
        console.log(msg);
    });

    // 断开连接
    socket.on("disconnect", () => {
        console.log("断开连接");
    });
    onUnmounted(() => {
        socket.close();
    });
};
</script>

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