<template>
  <div style="padding:20px">
    <a-tabs default-active-key="1">
      <a-tab-pane key="1" tab="历史订单">
        <a-table
          :columns="OrderColumns.filter((item) => !item.hidden)"
          :dataSource="historyOrders"
          :pagination="historyOrdersPagination"
          @change="historyOrdersChange"
          :row-key="(row) => row.Id"
        >
          <template slot="status" slot-scope="text">
            {{ statusRender(text) }}</template
          >
          <template slot="Profit" slot-scope="text">
            <span style="color:red">{{ text }}</span>
          </template>
          <template slot="UnstableProfit" slot-scope="text">
            <span style="color:red">{{ text }}</span>
          </template>
        </a-table>
      </a-tab-pane>
      <a-tab-pane key="2" tab="持仓订单" force-render>
        <a-table
          :columns="OrderColumns"
          :dataSource="nowOrders"
          :pagination="nowOrdersPagination"
          :row-key="(row) => row.Id"
        >
          <template slot="status" slot-scope="text">
            {{ statusRender(text) }}</template
          >
          <template slot="Profit" slot-scope="text">
            <span style="color:red">{{ text }}</span>
          </template>
          <template slot="UnstableProfit" slot-scope="text">
            <span style="color:red">{{ text }}</span>
          </template>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <a-tag style="margin:20px 0">账户基本信息</a-tag>
    <a-form-model layout="inline">
      <a-form-model-item label="持币数量"
        ><a-input
          v-model="basic.CoinCount"
          disabled
          style="width:100px"
        ></a-input
      ></a-form-model-item>
      <a-form-model-item label="持仓总价"
        ><a-input
          v-model="basic.TotalPurchasePrice"
          disabled
          style="width:100px"
        ></a-input
      ></a-form-model-item>
      <a-form-model-item label="持仓均价"
        ><a-input
          v-model="basic.AvgPurchasePrice"
          disabled
          style="width:100px"
        ></a-input
      ></a-form-model-item>
      <a-form-model-item label="持仓占比(%)"
        ><a-input
          v-model="basic.TotalPurchasePriceRatio"
          disabled
          style="width:100px"
        ></a-input
      ></a-form-model-item>
      <a-form-model-item label="浮动盈亏(%)"
        ><a-input
          v-model="basic.FloatingPL"
          disabled
          style="width:100px"
        ></a-input
      ></a-form-model-item>
      <a-form-model-item label="浮动持仓利润(已预扣手续费)"
        ><a-input
          v-model="basic.TotalPurchasePriceProfit"
          disabled
          style="width:100px"
        ></a-input
      ></a-form-model-item>
      <a-form-model-item label="总利润(已预扣手续费)"
        ><a-input
          v-model="basic.TotalProfit"
          disabled
          style="width:100px"
        ></a-input
      ></a-form-model-item>
      <a-form-model-item label="最新成交价"
        ><a-input
          v-model="basic.NewestPrice"
          disabled
          style="width:100px"
        ></a-input
      ></a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
/* eslint-disable */
import { OrderColumns } from "./js/columns";
import Bus from "../common/bus";
import {
  sendSock,
  initWebSocket,
  closeWebSocket,
} from "../utils/plugin/socket";

const S_PING = 100;
const R_PONG = 101;
const SUBSCRIBE = 102;
const ACCOUNT_INFO = 103;
const ORDER_PUBLISH = 104;
const TRADE_LOG = 105;

export default {
  props: {
    RobotId: { type: String, default: "60521323-28C3-AC14-0076-48B075584510" },
  },
  data() {
    return {
      OrderColumns,
      historyOrders: [],
      nowOrders: [],
      labelCol: { span: 6 },
      wrapperCol: { span: 6 },
      historyOrdersPagination: { current: 1, pageSize: 15 },
      nowOrdersPagination: { current: 1, pageSize: 15 },
      basic: {},
      pingInterval: null,
    };
  },
  created() {
    this.initOrders(); //初始化两个订单列表
  },
  mounted() {
    console.log("connecting");
    this.initWs(); //初始化ws连接
  },
  beforeDestroy() {
    closeWebSocket();
    localStorage.clear();
    clearInterval(this.pingInterval);
  },
  methods: {
    initOrders() {
      this.initHistoryOrders();
      this.initNowOrders();
    },
    initHistoryOrders() {
      let pageIndex = this.historyOrdersPagination.current;
      let pageSize = this.historyOrdersPagination.pageSize;
      this.$http
        .get(
          `/Api/Order/GetHistorySpotGoodsOrder?pageIndex=${pageIndex}&pageSize=${pageSize}&robotId=${this.RobotId}`
        )
        .then((res) => {
          if (res.Code == 200) {
            this.historyOrders = res.Data.List;
            const pager = { ...this.historyOrdersPagination };
            pager.total = res.Data.Count;
            this.historyOrdersPagination = pager;
          }
        });
    },

    //触发分页
    // nowOrdersChange(pagination) {
    //   this.nowOrdersPagination = pagination;
    //   this.initNowOrders();
    // },

    //触发分页
    historyOrdersChange(pagination) {
      this.historyOrdersPagination = pagination;
      this.initHistoryOrders();
    },

    initNowOrders() {
      // let pageIndex = this.nowOrdersPagination.current;
      // let pageSize = this.nowOrdersPagination.pageSize;
      this.$http
        .get(`/Api/Order/GetRuningSpotGoodsOrder?robotId=${this.RobotId}`)
        .then((res) => {
          if (res.Code == 200) {
            this.nowOrders = res.Data;
            // const pager = { ...this.nowOrdersPagination };
            // pager.total = 100;
            // this.nowOrdersPagination = pager;
          }
        });
    },

    initWs() {
      let that = this;
      initWebSocket("ws://54.249.164.224").then(
        (rs) => {
          //订阅事件
          sendSock(
            {
              Notify: SUBSCRIBE,
              RobotId: this.RobotId,
            },
            that.wsCb
          );
          //ping包检测连接
          that.pingIntervalKeeper();
        },
        (rj) => {
          that.$message.error("连接websocket失败，正在重连");
          that.initWs();
        }
      );
    },

    wsCb(data) {
      console.log("ws received", data);

      if (data && data.Notify == ACCOUNT_INFO) {
        this.dealAccountInfo(data);
      } else if (data && data.Notify == ORDER_PUBLISH) {
        this.dealOrder(data);
      } else if (data && data.Notify == R_PONG) {
        this.dealPong(data);
      } else if (data && data.Notify == TRADE_LOG) {
        Bus.$emit("tradeLog", data);
      }
    },

    pingPkg() {
      console.log("心跳包检测发送");
      let timeStamp = Date.now();
      let that = this;
      sendSock(
        {
          Notify: S_PING,
          TimeStamp: timeStamp,
        },
        that.wsCb
      );
      localStorage.setItem("pingTimeStamp", timeStamp);
      if (!localStorage.getItem("missPkg")) {
        localStorage.setItem("missPkg", 1);
      } else {
        let missPkgCount = parseInt(localStorage.getItem("missPkg")) + 1;
        localStorage.setItem("missPkg", missPkgCount);
        console.log("丢包次数增加1", missPkgCount);
        if (missPkgCount > 3) {
          /** 达到丢包上限
           * 1.停止ping包interval
           * 2.关闭ws
           * 3.重新获取订单列表
           */
          console.log("达到丢包次数", missPkgCount);
          clearInterval(this.pingInterval);
          localStorage.clear();
          closeWebSocket();
          this.initOrders();
          this.initWs();
        }
      }
    },

    //心跳包ping包定时发送
    pingIntervalKeeper() {
      let that = this;
      that.pingPkg();
      this.pingInterval = setInterval(() => {
        that.pingPkg();
      }, 30000);
    },

    //心跳包pong包检测
    dealPong(data) {
      //收到pong包后与本地得timeStamp匹配到之后丢包次数默认-1
      let timeStamp = localStorage.getItem("pingTimeStamp");
      let missPkgCount = parseInt(localStorage.getItem("missPkg"));
      if (data.TimeStamp == timeStamp) {
        missPkgCount--;
        console.log("丢包次数减少1", missPkgCount);
        localStorage.setItem("missPkg", missPkgCount);
      }
    },

    //账号信息推送处理
    dealAccountInfo(data) {
      this.basic = { ...this.basic, ...data };
      if (
        this.nowOrders.length > 0 &&
        data.NewestPrice &&
        data.NewestPrice != 0
      ) {
        this.nowOrders.forEach((item) => {
          let totalSalePrice = data.NewestPrice * item.PurchaseCoinCount; //销售总价
          let saleFee = totalSalePrice * 0.02; //销售手续费
          let Profit =
            totalSalePrice -
            item.TotalPurchasePrice -
            saleFee -
            item.PurchaseFee;
          item.Profit = Profit.toFixed(5); //算出利润
          item.UnstableProfit = (
            (data.NewestPrice / item.PurchasePrice - 1) *
            100
          ).toFixed(5); //算出浮动盈亏
          // console.log(item.UnstableProfit, "看看数据");
        });
      }
    },

    //订单推送处理
    dealOrder(data) {
      //4|| 6
      let targetIndex = -1;
      for (let i = 0; i < this.nowOrders.length; i++) {
        if (data.Id == this.nowOrders[i].Id) {
          targetIndex = i;
          break;
        }
      }
      if (targetIndex == -1) {
        this.nowOrders.push(data);
      } else {
        this.nowOrders[targetIndex] = {
          ...this.nowOrders[targetIndex],
          ...data,
        };
        if (data.Status == 4 || data.Status == 6) {
          this.nowOrders.splice(targetIndex, 1);
          if (this.historyOrdersPagination.current == 1)
            this.initHistoryOrders();
        }
      }
    },
    statusRender(status) {
      //已创建=0,部分购买=1,已购买=2,部分购买被撤销=3,购买被撤销=4,部分卖出=5,已卖出=6,部分卖出已撤销=7,卖出已撤销=8
      switch (status) {
        case 0:
          return "已创建";
        case 1:
          return "部分购买";
        case 2:
          return "已购买";
        case 3:
          return "部分购买被撤销";
        case 4:
          return "购买被撤销";
        case 5:
          return "部分卖出";
        case 6:
          return "已卖出";
        case 7:
          return "部分卖出已撤销";
        case 8:
          return "卖出已撤销";
      }
    },
  },
};
</script>
