import { getAccountList, getCash } from '@/api/assets'
import { getCookie } from "@/utils/cookie";
import WebSocketClient from "@/utils/socket";
import bus from '@/utils/bus'
import { getCurrencyList } from "@/api/product";
export default {
  data () {
    return {
      getAccountListSign: false,
      getCashInfoSign: false,
      updateTradeAssetSocket: null,
      sendTimer: null,
    }
  },
  beforeDestroy () {
    bus.$off('updateAssets', this.updateAssets)
  },
  watch: {
    isLogin(val) {
      if (!val) {
        this.updateTradeAssetSocket && this.updateTradeAssetSocket.close();
        (this.sendTimer && clearInterval(this.sendTimer));
        return
      }
      if (val) {
        this.creatSocket1(getCookie('userToken') || Math.random())
      }
    }
  },
  created () {
    bus.$on('updateAssets', this.updateAssets)
    if (this.isLogin) {
      this.creatSocket1(getCookie('userToken') || Math.random())
    }
    this.getCurrencyList()
  },
  methods: {
    creatSocket1(token) {
      this.updateTradeAssetSocket = new WebSocketClient('/Transaction/' + token)
      this.updateTradeAssetSocket.connect(this.onopen1, this.onmessage1)
    },
    onopen1() {
      this.sendTimer = setInterval(() => {
        if (this.isLogin) {
          if (this.updateTradeAssetSocket && this.updateTradeAssetSocket.socket.readyState == 3) {
            this.sendTimer && clearInterval(this.sendTimer)
            this.creatSocket1(getCookie('userToken') || Math.random())
          }
        }
      }, 40000)
    },
    onmessage1(msg) {
      var data = JSON.parse(msg.data)
      if (data) {
        if (data.type === "trades") {
          bus.$emit('updateOrder')
          if (data.action == '1') {
            bus.$emit('updateCloseOrder')
          }
          this.$store.dispatch('getMessageList')
          this.getAccountList()
        }
        if (data.action === "withdrawCash") {
          this.$store.dispatch('getMessageList')
          this.getCash()
        }
        if (data.action === "logoutUser" || data.action === "updateLoginPassword") {
          this.$notify({
            // message: '网络故障需要重新登录',
            message: data.action === "logoutUser" ? this.$t('ajax.l4') : this.$t('ajax.l2'),
            type: 'danger'
          });
          this.$store.commit('SET_LOGIN', false)
          this.$store.commit('setAccountList', [])
          this.$store.commit('setCashInfo', {})
          bus.$emit('socketInit')
          this.$router.push('/login')
        }
        if (data.action === "CashToFollow" || data.action === 'FollowToCash') {
          this.getCash()
          this.$store.dispatch('getFollowAccount')
          this.$store.dispatch('getMessageList')
        }
        if (data.action === "depositCash" || data.action === 'TransactionToCash' || data.action === 'CashToTransaction') {
          this.getCash()
          this.getAccountList()
          bus.$emit('updateUserDayBalance')
          this.$store.dispatch('getMessageList')
        }
      }
    },
    // 获取储蓄帐号列表
    getAccountList() {
      if (this.getAccountListSign) {
        return
      }
      this.getAccountListSign = true
      getAccountList().then((res) => {
        var list = res.list || []
        this.$store.commit('setAccountList',list)
      }).finally(() => {
        this.getAccountListSign = false
      }).catch(() => {})
    },
    // 获取储蓄帐号列表
    getCash() {
      if (this.getCashInfoSign) {
        return
      }
      this.getCashInfoSign = true
      getCash().then((res) => {
        var cashInfo = res || []
        this.$store.commit('setCashInfo', cashInfo)
      }).finally(() => {
        this.getCashInfoSign = false
      }).catch(() => {})
    },
    getCurrencyList() {
      getCurrencyList({
        type: 1
      }).then(res => {
        var list = res.list || []
        var obj = {
          'USD': 1,
          'CNY': 1,
          'HKD': 1,
        }
        list.forEach(item => {
          if (obj[item.symbol]) {
            obj[item.symbol] = item.rate
          }
        })
        this.$store.commit('setCurrencyList', obj)
      }).catch(() => {
        
      })
    },
    updateAssets(list) {
      if (!this.isLogin) {
        return
      }
      if (this.updateTradeAssetSocket && this.updateTradeAssetSocket.socket.readyState == 3) {
        this.sendTimer && clearInterval(this.sendTimer)
        this.creatSocket1(getCookie('userToken') || Math.random())
      }
      if (list) {
        list.forEach(item => {
          this[item]()
        })
      }
    }
  }
}