<template>
  <!-- 顶部 -->
  <div class="top">
    <div class="con">
      <div class="left" :class="{ 'hide-sgin' : !news.length}">
        <!-- <span class="item">喜讯！蓝海多店铺商城上线了！</span> -->
        <!-- 消息播放 -->
        <div v-if="news.length >= 1">
          <el-carousel
            class="swiper-wrapper"
            direction="vertical"
            height="30px"
            style="overflow-y:visible; overflow-x:visible;"
          >
            <el-carousel-item
              class="swiper-slide"
              v-for="(news, index) in news"
              :key="index"
            >
              <div class="title item" @click="goNewsDet(news.id)">
                {{ news.title }}
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
        <!-- 消息播放end -->
      </div>
      <div class="right">
        <div class="item">
          <span class="text">{{language !== "en"?webConfigData.pcWelcomeCn:webConfigData.pcWelcomeEn}}</span>
          <span class="link" v-if="!nickName">
            <a href="javascript:void(0);" class="link-a" @click="showLoginPopup"
              >{{ $t('commonHead.login') }}</a
            >
            /
            <nuxt-link class="link-a" to="/register">{{ $t('commonHead.registration') }}</nuxt-link>
          </span>
          <span class="link" v-else>
            <a href="javascript:void(0)" class="link-name">{{ nickName }}</a>
            <span class="link-select">
              <nuxt-link to="/member-center/member-center" class="link-item"
                >{{ $t('commonHead.membershipCentre') }}</nuxt-link
              >
              <nuxt-link to="/user-center/uc-collection" class="link-item"
                >{{ $t('commonHead.myCollection') }}</nuxt-link
              >
              <nuxt-link to="/user-center/uc-coupons" class="link-item"
                >{{ $t('discountCoupon') }}</nuxt-link
              >
              <a href="javascript:void(0)" @click="loginOut" class="link-item"
                >{{ $t('commonHead.logout') }}</a
              >
            </span>
          </span>
        </div>
        <div class="item">
          <span @click="routeTo" data-route="index" class="item-a"
            >{{ $t('commonHead.mallHome') }}</span
          >
        </div>
        <!-- <div class="item">
          <span
            @click="routeTo"
            v-if="shopAuditStatus == 1"
            data-route="shopIndex"
            class="item-a"
            >{{ $t('commonHead.myShop') }}</span
          >
          <span @click="routeTo" v-else data-route="freeShop" class="item-a"
            >{{ $t('commonHead.freeShop') }}</span
          >
        </div> -->
        <div class="item">
          <span @click="routeTo" data-route="order" class="item-a"
            >{{ $t('commonHead.myOrder') }}</span
          >
        </div>
        <div class="item">
          <span @click="routeTo" data-route="userCenter" class="item-a"
            >{{ $t('commonHead.personalCenter') }}</span
          >
        </div>
        <div class="item mobile">
          <a href="javascript:void(0);" class="item-b">{{ $t('commonHead.sellersCentre') }}</a>
          <div class="mobile-select option">
            <div class="text" @click="toMerchantPlatformUrl" >{{ $t('commonHead.merchantPlatform') }}</div>
          </div>
        </div>
        <div class="item mobile">
          <a href="javascript:void(0);" class="item-a">{{ $t('commonHead.mobileMall') }}</a>
          <div class="mobile-select" :style="{height:language!='zh'?'170px':'145px'}">
            <div class="code">
              <div id="qrcode"></div>
              <!-- <img src="~/assets/images/mobile-code.png" alt /> -->
            </div>
            <div class="text">{{ $t('commonHead.cellPhoneScanCodeExperience') }}</div>
          </div>
        </div>
        <!-- 顶栏购物车 -->
        <div class="item top-cart">
          <span @click="routeTo" data-route="cart" class="item-a"
            >{{ $t('commonHead.shopCart') }}{{ isToken ? `(${totalCartCount})` : '' }}</span
          >
        </div>
        <div class="item">
          <span @click="switchingLanguages" class="item-a" :style="language!='zh'?'margin-right: 14px;':'margin-right: 24px;'"
            >{{ $t('commonHead.switchingLanguages') }}</span
          >
        </div>
        <!-- <div class="item top-cart top-cart-on" v-if="cartProdList.length">
          <span @click="routeTo" data-route="cart" class="item-a">
            购物车
            <span class="number">({{totalCartCount}})</span>
          </span>
          <div class="cart-select">
            <div class="cart-list">
              <div class="list-item" v-for="prod in cartProdList" :key="prod.prodId">
                <div class="goods-img">
                  <img :src="prod.pic" alt />
                </div>
                <div class="goods-msg">
                  <div class="name">{{prod.prodName}}</div>
                  <div class="info">
                    <span class="price">￥{{prod.price}}</span>
                    <span class="number">×{{prod.prodCount}}</span>
                  </div>
                </div>
                <div class="del" @click="delCartItem(prod.basketId)"></div>
              </div>
            </div>
            <div class="list-total">
              <div class="total-msg">
                <div class="total-number">共 {{totalCartCount}} 件商品</div>
                <div class="price">
                  ￥
                  <span class="big">{{parsePrice(totalCartAmount)[0]}}</span>
                  .{{parsePrice(totalCartAmount)[1]}}
                </div>
              </div>
              <nuxt-link to="/cart" class="total-btn">去购物车结算</nuxt-link>
            </div>
          </div>
        </div>
        <div class="item top-cart top-cart-empty" v-else>
          <span @click="routeTo" data-route="cart" class="item-a">
            购物车
            <span class="number">(0)</span>
          </span>
          <div class="no-goods">您的购物车中还没有商品，赶紧选购吧！</div>
        </div>-->
      </div>
    </div>
    <!-- 登录弹窗组件 -->
    <LoginPopup v-if="showLogin" v-on:hideLoginPop="hideLoginPop" />
    <!-- /登录弹窗组件 -->
  </div>
  <!-- /顶部 -->
</template>

<script>
import Cookie from 'js-cookie'
import config from '../plugins/config'
import LoginPopup from '~/components/login-popup'
import bus from '~/plugins/bus'
import util from '~/plugins/util'
import { h5Path, merchantPlatformUrl  } from '~/plugins/config'
import { setLanguage , addUrlParam} from '~/plugins/util.js'
import { Base64 } from 'js-base64'
export default {
  components: {
    LoginPopup
  },
  data () {
    return {
      merchantPlatformUrl: merchantPlatformUrl,
      showLogin: false,
      language: this.$store.state.locale,
      nickName: '',
      userId: this.$store.state.user.userId,
      news: [],
      swiperOption: {
        loop: true,
        spaceBetween: 0,
        speed: 800,
        autoplay: true,
        height: 34,
        direction: 'vertical', //垂直
        autoplayDisableOnInteraction: false,
      },
      cartProdList: [], // 顶栏购物车数据
      totalCartAmount: 0,
      shopAuditStatus: null,
      shopStatus: -1,
      webConfigData: {},
      isToken: !!Cookie.get('token')
    }
  },
  mounted () {
    // 购物车数量
    this.getCartCount()
    // 获取网站配置信息
    this.$axios.get('/webConfig/getPcWebConfig')
    .then(({ data }) => { 
    localStorage.setItem('webConfig', JSON.stringify(data)) 
    this.webConfigData = JSON.parse(localStorage.getItem('webConfig') || '{}')
    util.changeFavicon()
    })  

    if (config.imWsPath) {
      if ( !this.$store.state.websocket.websocketConnect && Cookie.get('token') ) {
        this.openWs()
        this.$store.commit('websocket/changeWebsocket', true)
      }
    }

    // 获取个人中心信息（店铺审核状态）
    if (Cookie.get('token')) {
      this.getUserCenterInfo()
    }

    this.showLogin = Cookie.get('showLogin')
    //请求顶部公告
    this.getNoticeList()
    if (Cookie.get('token')) {
      this.nickName = this.$store.state.user.nickName == null? '' : this.$store.state.user.nickName
    } else {
      this.nickName = ''
    }
    this.$nextTick(() => {
      this.loadQRCode()
    })

    this.$axios.get('/webConfig/getPcWebConfig')
    .then(({ data }) => { localStorage.setItem('webConfig', JSON.stringify(data)) })

    
    // 获取系统支付设置
		util.getSysPaySwitch()
  },
  created () {
    bus.$on('showLogin', msg => {
      this.showLogin = msg
    })
  },
  computed: {
    totalCartCount () {
      if (!this.nickName) {
        return 0
      } else {
        return this.$store.state.cartNumber.cartNumbers;
      }
    }
  },
  watch: {
    $route (to, from) {
      //要处理的操作
      this.nickName = this.$store.state.user.nickName
      this.$axios.get('/webConfig/getPcWebConfig')
      .then(({ data }) => { localStorage.setItem('webConfig', JSON.stringify(data)) 
      util.changeFavicon()})
    }
  },
  methods: {

    /**
     * 跳转商家后台
     */
    toMerchantPlatformUrl() {
      window.open(this.merchantPlatformUrl, '_blank')
    },

    /**
     * 开启webstocket
     */
    openWs () {
      var ths = this
      this.imSocketTask = new WebSocket(
        config.imWsPath + '/im/websocket/online/user/' + Base64.encode(Cookie.get('token')) + '/' + this.userId
      ) 
      this.imSocketTask.onopen = function (event) {
        heartCheck.reset().start() // 成功建立连接后，重置心跳检测
        ths.ortherUser = false
        ths.imSocketTask.send(
          JSON.stringify({
            content: 'HEART_BEAT',
            msgType: 0
          })
        )
      }
      this.imSocketTask.onmessage = (res) => {
        heartCheck.reset().start() // 成功建立连接后，重置心跳检测
        let result = JSON.parse(res.data)
        if (result.code !== '00000') {
          result.code = Number(result.code)
        }
        console.log('onMessage:' + result)
        if (result.code === 10) {
          console.log(this.$i18n.t('noGetUserInfor'))
          // this.openWs()
          return
        }
        if (result.code === 11) {
          this.ortherUser = true
        }
        if (result.code === 12) {
          console.log(this.$i18n.t('otherParIsNoOL'))
          return
        }
        if (result.code === 15) {
          this.$message.error(this.$i18n.t('chat.notYourResponsibility'))
          this.noAccountable = false
          return false
        }
        if (result.code === '00000' && result.data && result.success) {
          this.$store.commit('websocket/changeMessage', 1)
        }
      }
      var heartCheck = {
        timeout: 19000, // 19s发一次心跳，比server端设置的连接时间稍微小一点，在接近断开的情况下以通信的方式去重置连接时间。 尽量一个小时发送三次
        serverTimeoutObj: null,
        reset: function () {
          clearTimeout(this.serverTimeoutObj)
          return this
        },
        start: function () {
          this.serverTimeoutObj = setTimeout(function () {
            if (!ths.imSocketTask) {
              return
            }
            if (ths.imSocketTask.readyState === 1) {
              console.log('连接状态，发送消息保持连接')
              ths.imSocketTask.send(
                JSON.stringify({
                  content: 'HEART_BEAT',
                  msgType: 0
                })
              )
              heartCheck.reset().start() // 如果获取到消息，说明连接是正常的，重置心跳检测
            } else {
              ths.imSocketTask.close()
              ths.imSocketTask = null
              ths.lockReconnect = false
              console.log('断开状态，尝试重连')
            }
          }, this.timeout)
        }
      }
      this.imSocketTask.onclose = (res) => {
        if (!this.ortherUser) {
          console.log('断线,开始重连')
          this.ortherUser = false
          if (this.plooTime < 3) {
            this.plooTime ++
            if (this.lockReconnect) return
            this.lockReconnect = true
            setTimeout(() => {     // 没连接上会一直重连，设置延迟避免请求过多
              this.openWs()
              this.lockReconnect = false
            }, 2000)
          } else {
            // this.$confirm(ths.$i18n.t('chat.connetBroken'), ths.$i18n.t('chat.tips'), {
            //   confirmButtonText: ths.$i18n.t('chat.confirm'),
            //   cancelButtonText: ths.$i18n.t('chat.cancel'),
            //   type: 'warning'
            // }).then(() => {
            //   location.reload()
            // }).catch(() => {

            // })
          }
        }
      }
    },

    /**
     * 切换语言
     */
    switchingLanguages(){
      if( this.$store.state.locale !=='zh'){
         this.$store.commit('SET_LANGUAGE', 'zh')
         this.$i18n.locale = 'zh'
         this.language = 'zh'
      }else{
        this.$store.commit('SET_LANGUAGE', 'en')
        this.$i18n.locale = 'en'
        this.language = 'en'
      }
      // window.location.reload()
      window.location.href = addUrlParam(window.location.href, 'lang', this.language)
      // this.$router.push({path: this.$route.path, query: {...this.$route.query, lang: this.language}})
    },

    /**
     * 生成二维码
     */
    loadQRCode () {
      let qrcode = new QRCode('qrcode', {
        text: h5Path,
        width: 100,
        height: 100,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: 3
      })
    },
    /**
     * 统一跳转方法
     */
    routeTo (e) {
      let path = e.target.dataset.route
      if (path == 'index') {
        switch (path) {
          case 'index':
            this.$router.push({ path: '/' })
            break;
        }
      }
      else if (Cookie.get('token')) {
        switch (path) {
          case 'freeShop':
            this.$router.push({ path: '/user-center/uc-freeshop' })
            break;
          case 'order':
            this.$router.push({ path: '/user-center/uc-order' })
            break;
          case 'userCenter':
            this.$router.push({ path: '/user-center', query: { currentPage: '/home' } })
            break;
          case 'cart':
            this.$router.push({ path: '/cart' })
            break;
          case 'shopIndex':
            if (this.shopStatus==1) {
              this.$router.push({ path: `/shopIndex?sid=${this.shopId}` })
            } else {
              this.$message({
                type: 'warning',
                message: this.shopStatus == 0 ? this.$t('collection.storeReviewTips1') :  this.shopStatus == -1 ? this.$t('collection.storeReviewTips2') : this.$t('userCenter.theStoreOffline')
              })
            }
          default:
            break;
        }
      } else {
        this.showLogin = true
      }

    },

    /**
     * 显示登录弹窗
     */
    showLoginPopup () {
      this.showLogin = true
    },

    /**
     * 隐藏登录弹窗
     */
    hideLoginPop () {
      this.showLogin = false
      if (this.$route.path.indexOf('user-center')>-1) {
        this.$router.push({path:'/'})
      }
    },



    /**
     * 请求顶部公告
     */
    getNoticeList () {
      // 请求轮播图
      this.$axios.get('/shop/notice/topNoticeList/0').then(({ data }) => { this.news = data })
    },

    // 去公告详情
    goNewsDet (id) {
      this.$router.push({
        path: '/notice-detail',
        query: {
          id: id,
          shopId: 0
        }
      })
    },

    /**
     * 退出登录
     */
    loginOut () {
      this.$axios.post('/logOut').then(({ data }) => {
        const user = {
          nickName: '',
          userAvatar: ''
        }
        this.$store.commit('user/SET_USER', user)
        Cookie.remove('token')
        window.localStorage.clear()
        this.$route.path == '/' ? location.reload() : this.$router.push({ path: '/' })
      })
    },

    /**
     * 获取购物车列表
     */
    getCart () {
      let shopCartParams = []
      this.$axios.post('/p/shopCart/info', shopCartParams).then(({ data }) => {
        let list = []
        data.forEach(element => {
          return element.shopCartItemDiscounts.forEach(el => {
            return list.push(...el.shopCartItems)
          })
        })
        this.cartProdList = list
      })
    },

    /**
     * 计算购物车总价
     */
    getCartAmount () {
      let basketIds = []
      this.cartProdList.forEach(el => { basketIds.push(el.basketId) })
      this.$axios.post('/p/shopCart/totalPay', basketIds).then(({ data }) => {
        this.totalCartAmount = data.finalMoney
      })
    },

    /**
     * 删除购物车商品
     */
    delCartItem (basketId) {
      let basketIds = [basketId]
      this.$axios.delete('/p/shopCart/deleteItem', { data: basketIds }).then(({ data }) => {
        this.getCart()
      })
    },
    /**
     * 价格处理
     */
    parsePrice: (value) => {
      var val = Number(value)
      if (!val) {
        val = 0;
      }
      // 截取小数点后两位，并以小数点为切割点将val转化为数组
      return val.toFixed(2).split(".");
    },

    /**
     * 请求个人中心信息（店铺审核状态）
     */
    getUserCenterInfo () {
      this.$axios.get('/p/user/centerInfo', {
      }).then(({ data }) => {
        this.isSetPassword = data.isSetPassword  //是否已经设置过支付密码
        this.orderCountData = data.orderCountData  //订单状态信息
        this.shopAuditStatus = data.shopAuditStatus  //审核状态：0 未审核 1已通过 -1未通过 null 未开店
        this.shopStatus = data.shopStatus // 店铺状态(-1:未开通 0: 停业中 1:营业中 2:平台下线 3:平台下线待审核)，
        this.shopId = data.shopId  //店铺id
      })
    },
    /**
     * 获取购物车商品总数
     */
    getCartCount () {
      this.$axios.get('/p/shopCart/prodCount', {
        dontShowLogin: true
      }).then(({ data }) => {
        this.$store.commit('cartNumber/changeCartNumber', data)
      })
    }
  },
  beforeDestroy() {
    bus.$off('showLogin')
  }
}
</script>

<style>
.top .con .hide-sgin.left::before {
  display: none;
}
.left .el-carousel__indicators--vertical {
  display: none;
}
.left .swiper-slide {
  display: block !important;
  width: auto !important;
  text-align: left !important;
  font-weight: normal;
  background: inherit;
}
.swiper-slide .item {
  font-size: 12px;
}
.link-a,
.item-a {
  cursor: pointer;
}
/* 购物车数量角标 */
.total-cart-count {
  display: block;
  box-sizing: border-box;
  position: absolute;
  width: auto;
  height: auto;
  line-height: 1em;
  text-align: center;
  top: 6px;
  left: 75px;
  font-size: 12px;
  color: #fff;
  background: #e43130;
  z-index: 91;
  padding: 2px 4px;
  border-radius: 5px;
}
.total-cart-count::after {
  position: absolute;
  top: 2px;
  left: -5px;
  display: block;
  content: '';
  width: 0;
  height: 0;
  border-top: 6px solid transparent;
  border-bottom: 6px solid transparent;
  border-right: 6px solid #e43130;
}

.title {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  word-break:break-word;
  width: 187px;
}

.top .con .left .item {
    border-bottom: 1px solid;
    text-decoration: none;
    display: inline;
}
</style>
