<template>
  <div id="app">
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive"></router-view> 
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>
    <van-popup :close-on-click-overlay="false" get-container="body" v-model="network" :style="{ width: '324px' }">
      <network/>
    </van-popup>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { openSubscribe, updateSubscribe } from "@/api/subscribe";
import { getParams } from "@/api/app";
import WebSocketClient from "@/utils/socket";
import { getProductList } from "@/api/product";
import { setSession } from "@/utils/sessionStorage";
import bus from '@/utils/bus'
import tradeAssets from "@/mixins/tradeAssets";
import network from "@/components/network";
import { deepCopy } from "@/utils";
export default {
  name: 'App',
  mixins: [tradeAssets],
  components: {
    network
  },
  data () {
    return {
      webSocket: null,
      productDataObj: {},
      timerSign: 0
    }
  },
  provide() {
    return {
      getproductDataObj: () => this.productDataObj,
    }
  },
  computed: {
    ...mapGetters(['socketToken', 'token', 'accountList', 'networkPopup']),
    network: {
      get() {
        return this.networkPopup;
      },
      set() {}
    },
    cfdInfo() {
      let info = {}
      this.accountList.forEach(item => {
        if (item.market == 'CFD') {
          info = item
        }
      })
      return info
    }
  },
  created () {
    if (this.isLogin) {
      this.$store.dispatch('getUserInfo', true)
    }
    this.init()
    bus.$on('updateSubscribe', this.updateSubscribe)
    bus.$on('resetProductDataObj', this.resetProductDataObj)
    bus.$on('socketInit', this.init)
    this.getParams()
  },
  methods: {
    init() {
      if (this.isLogin) {
        this.creatSocket(this.token)
      } else {
        if (this.socketToken) {
          this.creatSocket(this.socketToken)
        } else {
          this.openSubscribe()
        }
      }
    },
    openSubscribe() {
      openSubscribe().then(res => {
        if (res.token) {
          setSession('socketToken', res.token)
          this.creatSocket(res.token)
          this.$store.commit('setSocketToken', res.token)
        }
      }).catch(() => {

      })
    },
    creatSocket(token) {
      this.webSocket = new WebSocketClient('/Quotation/' + token)
      this.webSocket.connect(this.onopen, this.onmessage)
    },
    onopen() {
      console.log("WebSocket连接已打开");
    },
    onmessage(data) {
      let msg = JSON.parse(data.data)
      if (msg) {
        if (msg.type == 'depth' && this.updateSymbolList.indexOf(msg.symbol) != -1) {
          bus.$emit('updateDepth', msg)
        }
        if (msg.type == 'price' && this.updateSymbolList.indexOf(msg.symbol) != -1) {
          if (this.productDataObj && this.productDataObj[msg.symbol] !== undefined) {
            let item = this.productDataObj[msg.symbol]
            msg.ask = Number(this.$handleDigits(msg.ask, this.productDataObj[msg.symbol].digits))
            msg.bid = Number(this.$handleDigits(msg.bid, this.productDataObj[msg.symbol].digits))
            this.$set(this.productDataObj[msg.symbol], 'ask', msg.ask)
            this.$set(this.productDataObj[msg.symbol], 'bid', msg.bid)
            this.$set(this.productDataObj[msg.symbol], 'spread', this.$bigDecimal.subtract(msg.ask, item.close))
            if (item.high < item.ask) {
              this.$set(this.productDataObj[msg.symbol], 'high', msg.ask)
            }
            if (item.low > item.ask) {
              this.$set(this.productDataObj[msg.symbol], 'low', msg.ask)
            }
            if (item.close) {
              this.$set(this.productDataObj[msg.symbol], 'percentage', ((((msg.ask || item.close) - item.close) / item.close) * 100).toFixed(2))
            }
            bus.$emit('updateChart', msg)
          }
          if ((new Date().getTime() - this.timerSign) < 1000) {
            return
          }
          this.timerSign = new Date().getTime()
          bus.$emit('updateSymbol', msg)
        }
      }
    },
    close() {
      this.webSocket && this.webSocket.close()
    },
    updateSubscribe(list, sign, getInfo, add) {
      if (list.length == 0) {
        return
      }
      if (getInfo) {
        getProductList({
          symbol: JSON.stringify(list)
        }).then(res => {
          let list1 = res.list || []
          list1.forEach(item => {
            item.ask = Number(this.$handleDigits(item.ask, item.digits))
            item.bid = Number(this.$handleDigits(item.bid, item.digits))
            if (item.profit_mode == 0 && item.margin_mode == 0) {
              item.contract_size1 = (this.cfdInfo.leverage || 100)
            }
            if (item.close) {
              item.percentage = ((((item.ask || item.close) - item.close) / item.close) * 100).toFixed(2);
            } else {
              item.percentage = 100;
            }
            if (item.high < item.ask) {
              item.high = item.ask
            }
            if (item.low > item.ask) {
              item.low = item.ask
            }
            item.spread = this.$bigDecimal.subtract(item.ask, item.close)
            this.$set(this.productDataObj, item.symbol, item)
          })
        }).catch(() => {})
        return
      }
      if (this.webSocket && this.webSocket.socket.readyState == 3) {
        this.init()
      }
      if (sign) {
        getProductList({
          symbol: JSON.stringify(list)
        }).then(res => {
          let list1 = res.list || []
          list1.forEach(item => {
            item.ask = Number(this.$handleDigits(item.ask, item.digits))
            item.bid = Number(this.$handleDigits(item.bid, item.digits))
            if (item.profit_mode == 0 && item.margin_mode == 0) {
              item.contract_size1 = (this.cfdInfo.leverage || 100)
            }
            if (item.close) {
              item.percentage = ((((item.ask || item.close) - item.close) / item.close) * 100).toFixed(2);
            } else {
              item.percentage = 100;
            }
            if (item.high < item.ask) {
              item.high = item.ask
            }
            if (item.low > item.ask) {
              item.low = item.ask
            }
            item.spread = this.$bigDecimal.subtract(item.ask, item.close)
            this.$set(this.productDataObj, item.symbol, item)
          })
          this.$store.commit('setUpdateSymbolList', list)
        }).catch(() => {})
        updateSubscribe({
          symbols: JSON.stringify(list)
        }).then(res => {
        }).catch(() => {})
        return
      }
      let symbolList = deepCopy(add) || []
      list.forEach(item => {
        item.ask = Number(this.$handleDigits(item.ask, item.digits))
        item.bid = Number(this.$handleDigits(item.bid, item.digits))
        if (item.profit_mode == 0 && item.margin_mode == 0) {
          item.contract_size1 = (this.cfdInfo.leverage || 100)
        }
        if (item.close) {
          item.percentage = ((((item.ask || item.close) - item.close) / item.close) * 100).toFixed(2);
        } else {
          item.percentage = 100;
        }
        if (item.high < item.ask) {
          item.high = item.ask
        }
        if (item.low > item.ask) {
          item.low = item.ask
        }
        item.spread = this.$bigDecimal.subtract(item.ask, item.close)
        this.$set(this.productDataObj, item.symbol, item)
        symbolList.push(item.symbol)
      })
      this.$store.commit('setUpdateSymbolList', symbolList)
      updateSubscribe({
        symbols: JSON.stringify(symbolList)
      }).then(res => {
      }).catch(() => {})
    },
    getParams() {
      getParams({
        type: 'Product,Thirdini,TradeVolume,Advertisement'
      }).then(res => {
        let list = res || [];
        let obj = {
          marketVolume: {}
        };
        list.forEach(item => {
          if (item.type == 'TradeVolume') {
            if (item.remark) {
              item.remark = JSON.parse(item.remark)
              item.remark.forEach(item => {
                obj.marketVolume[item.market] = item.volume
              })
            }
            return
          }
          if (item.type == 'Advertisement') {
            obj[item.title] = item.value ? JSON.parse(item.value) : {}
            return
          }
          if (item.type == 'Product') {
            obj.uncrypto = (item.value.indexOf('H5') === -1)
          } else {
            item.value.forEach((i) => {
              obj[i.key] = i.value
            })
          }
        })
        this.$store.commit('setAppParams', obj)
      }).catch(() => {})
    },
    resetProductDataObj(list) {
      var productDataObj1 = {}
      list.forEach(item => {
        productDataObj1[item] = this.productDataObj[item]
      })
      this.productDataObj = productDataObj1
    }
  }
}
</script>

<style>
#app {
  position: relative;
  color: var(--color-d-);
  background-color: var(--bg-);
  line-height: 1;
}
</style>
