<template>
  <div class="header-layout" >
    <div class="h-left" v-if="!isBack" @click="active = !active">
      <div class="l-con" :class="{active:active}" >
        <span class="l1"></span>
        <span class="l2"></span>
        <span class="l3"></span>
      </div>
    </div>
    <div @click="backHome?$router.push({name:'home'}):$router.back()" class="h-left back" v-else>
      <i class="iconfont icon-jiantou"></i>
    </div>
    <div class="h-center" @click="$router.push({name: 'home'})">
      <vcenter>
        <h-icon :type="language === 'zh' ? 'logo' : 'hengbiaoEN'" class="logo-icon"></h-icon>
        <!-- <img v-if="!isBack||$route.name==='useimg'" :src="language==='en'?`${$cdn}images/logo-en.png`:`${$cdn}images/logo.png`"  @click="()=>{goto({name:'home'})} " alt> -->
        <!-- <div v-else>{{$route.name==='consumpdetail'?titleName[$route.name][$route.params.id]:titleName[$route.name]}}</div> -->
      </vcenter>
    </div>
    <div class="h-right">
      <div class="h-user"  v-if="isAccout||isLogin">
          <i class="iconfont icon-cart" :style="{opacity:language==='en'?0:1}" @click="gocart"><span>{{count>99?'99+':count}}</span></i>
          <img ref="userList" :src="`${$cdn}images/icon/nav_icon.png`" @click="userList=!userList,active = false" alt="">
          <ul :style="{width:language==='en'?'160px':'110px'}" :class="{'ul-active':userList}" >
            <li v-for="(item,i) in langHeader.manage" :key="i" @click="handleClick(item)">{{item.name}}</li>
          </ul>
      </div>
      <div class="btn-buy" v-else-if="$route.name!=='purchase'&&$route.name!=='purchasetwo'&&$route.name!=='purchasezhijia'" @click="buy" >{{$t('header.online_shop')}}</div>
    </div>
    <div class="nav-active" :style="{maxHeight:active?'100vh':'0'}">
      <div class="nav-mask" :style="{position: active? 'fixed' : 'absolute'}"></div>
      <div class="nav-content">
        <ul v-for="(item, index) in navs" :key="index">
          <li>
            <div class="n-name" @click="clickItem(item, index)">
              <span>{{item.name}}</span>
              <h-icon type="shang" class="icon" :class="{active: activeIdx===index}"></h-icon>
            </div>
            <div class="n-child" :class="{'open':activeIdx === index}">
              <div  v-for="(sub,i) in item.childs" :key="i" @click="goto(sub.url)">
                <i class="iconfont" :class="sub.icon"></i>
                <span :style="{minWidth:index==='cpgm'?'120px':'60px'}"  v-html="sub.name"></span>
                <img v-if="sub.isNew" class="new-icon" :src="`${$cdn}images/new.png`" alt="">
              </div>
            </div>
          </li>
        </ul>
      <ul  v-if="!noEnglish">
        <li>
          <div class="n-name" @click="activeIdx = 'language'">
            <span>{{ languageName }}</span>
            <h-icon type="shang" class="icon" :class="{active: activeIdx==='language'}"></h-icon>
          </div>
          <div class="n-child" :class="{'open':activeIdx === 'language'}">
            <div  v-for="(sub,i) in languageList" :key="i" @click="changLang(sub.value)">
              <span :style="{minWidth:i==='cpgm'?'120px':'60px'}"  v-html="sub.name"></span>
            </div>
          </div>
        </li>
      </ul>
      </div>
    </div>
  </div>
</template>

<script>
import vcenter from '@/components/vcenter/'
import { mapState } from 'vuex'
import Paging from '@/components/Paging'

import browser from '@/util/browser'

let hasBack = [
  'introduce',
  'introtow',
  'openInvoice',
  'orderInvoice',
  'consumpdetail',
  'useimg'
]

let showUser = [
  'purchase',
  'purchasezhijia',
  'purchasetwo',
  'about',
  'useimg',
  'location',
  'service'
]

let noEngList = {
  'cart': true,
  'confirm': true,
  'paytype': true,
  'openInvoice': true,
  'vieworder': true
}

let titleName = {
  'introduce': '扩充容量',
  'introtow': '点数充值',
  'consumpdetail': {
    0: '扩容记录',
    1: '充值记录',
    2: '增值记录'
  },
  'openInvoice': '开具发票'
}

let titleNameEn = {
  'introduce': 'Expansion',
  'introtow': '点数充值',
  'consumpdetail': {
    0: 'Billing Records',
    1: '充值记录',
    2: '增值发票'
  },
  'openInvoice': '开具发票'
}

let typeArr = {
  2: '房地产',
  1: '博物馆',
  5: '家居',
  4: '餐饮',
  0: '其他'
}

let typeArrEn = {
  2: 'Real estate',
  1: 'Museum',
  5: 'Home',
  4: 'Catering',
  0: 'Others'
}
export default {
  computed: {
    ...mapState({
      token: state => state.user.token,
      langHeader: state => state.language.home.headers,
      language: state => state.language.current,
      languageList: state => state.language.languageList,
      info: state => state.user.info
    }),
    languageName () {
      let language = this.languageList.filter(item => item.value === this.language)
      return language[0] ? language[0].name : '简体中文'
    },
    typeArr: function () {
      return this.language === 'en' ? typeArrEn : typeArr
    },
    titleName: function () {
      return this.language === 'en' ? titleNameEn : titleName
    },
    noEnglish () {
      return noEngList[this.$route.name]
    },
    isBack: function () {
      for (let i = 0; i < hasBack.length; i++) {
        let ele = hasBack[i]
        if (this.$route.name === ele) {
          return true
        }
      }
      return false
    },
    isAccout: function () {
      if (this.$route.name === 'introduce' || this.$route.name === 'introtow') {
        return true
      }
      if (this.$route.matched.length > 0) {
        return this.$route.matched[0]['name'] === 'manage'
      }
      return false
    },
    isLogin: function () {
      if (this.$route.name === 'scenesearch') {
        return true
      }
      if (this.token) {
        for (let i = 0; i <= showUser.length; i++) {
          if (this.$route.name === showUser[i]) {
            return true
          }
        }
      }
      return false
    }
  },
  data () {
    return {
      active: false,
      searchActive: false,
      searchTxt: '',
      activeIdx: '',
      count: 0,
      backHome: false,
      total: 0,
      pageSize: 10,
      currentPage: 1,
      scene: [],
      showCount: false,
      userList: false,
      browserLang: browser.language,
      navs: [
        {
          name: this.$t('header.core_product'),
          url: '/coreProduct'
        },
        {
          name: this.$t('header.solutions'),
          childs: [
            {
              name: this.$t('header.solutionsHouse'),
              url: '/conduct/house'
            },
            {
              name: this.$t('header.solutionsExi'),
              url: '/conduct/exhibition'
            },
            {
              name: this.$t('header.solutionsSubject'),
              url: '/conduct/subject'
            },
            {
              name: this.$t('header.solutionsShop'),
              url: '/conduct/shop'
            },
            {
              name: this.$t('header.solutionsSec'),
              url: '/conduct/secury'
            }
          ]
        },
        {
          name: this.$t('header.kankan_space'),
          url: '/cases/全部'
        },
        {
          name: this.$t('header.core_tech'),
          url: '/location'
        },
        {
          name: this.$t('header.service'),
          childs: [
            {
              name: this.$t('header.serviceApp'),
              url: '/service/app'
            },
            {
              name: this.$t('header.serviceUse'),
              url: '/service/use'
            },
            {
              name: this.$t('header.serviceBaoxiu'),
              url: '/service/clause'
            },
            {
              name: this.$t('header.serviceVideo'),
              url: '/video-course'
            }
          ]
        },
        {
          name: this.$t('header.about'),
          childs: [
            {
              name: this.$t('header.aboutCompany'),
              url: '/about'
            },
            {
              name: this.$t('header.aboutNews'),
              url: '/news'
            },
            {
              name: this.$t('header.aboutAgent'),
              url: '/agent'
            }
          ]
        },
        {
          name: this.$t('header.myAccount'),
          url: '/login',
          needLogin: true
        }
      ]
    }
  },
  watch: {
    '$route.query': function (newVal) {
      if (newVal.lang) {
        newVal.lang === 'en' ? this.$store.commit('change_language', 'en') : this.$store.commit('change_language', '中')
      }
      this.backHome = newVal.token
      // let lang = this.$route.query.lang
      // this.$store.commit('change_language', lang)
    },
    currentPage () {
      this.getData()
    },
    language (newVal) {
      document.title = newVal === 'en' ? '4DKanKan' : '四维看看'
    },
    searchTxt (newVal) {
      if (newVal) {
        this.currentPage === 1 ? this.getData() : this.currentPage = 1
      } else {
        this.scene = []
      }
    }
  },
  mounted () {
    // let lang = ~this.browserLang.indexOf('zh') ? 'zh' : 'en'
    // this.$store.commit('change_language', lang)
    document.addEventListener('click', (e) => {
      if (this.$refs.userList) {
        if (!this.$refs.userList.contains(e.target)) {
          this.userList = false
        }
      }
    })
    if (this.token) {
      let cart = JSON.parse(this.$store.state.user.cart)
      let count = 0
      cart.forEach(item => {
        count += item.goodsCount
      })
      this.count = count
    }
    this.$bus.$on('updateCart', data => {
      this.count = data
    })
  },
  methods: {
    gocart () {
      if (this.language !== 'en') {
        this.active = false
        this.$router.push({path: '/cart'})
      }
    },
    handleClick (item) {
      if (item.to === 'logout') {
        this.$toast.showConfirm('warn', this.language === 'en' ? 'Are you sure to log out?' : '确定要退出登录吗？', async () => {
          await this.$store.dispatch('logout')
          this.$router.push({name: 'home'})
        })
      } else {
        this.$router.push(item.to)
      }
      this.userList = false
    },
    clickItem (item, index) {
      if (item.url) {
        this.active = false
        if (item.url === '/login' && this.token) {
          this.$router.push({
            path: '/information'
          })
        } else {
          this.$router.push({
            path: item.url,
            query: {
              id: item.id
            }
          })
        }
        this.activeIdx = ''
      } else if (this.activeIdx !== index) {
        this.activeIdx = index
      } else {
        this.activeIdx = ''
      }
    },
    changLang (lang) {
      this.$store.commit('change_language', lang)
      window.location.reload()
      this.active = false
    },
    linkto (url) {
      location.href = url.replace('http://', 'https://') + (this.language === 'en' ? '&lang=en' : '')
    },
    maskTitle (name) {
      if (!name) { return '' }
      let html = ''
      var arr = name.split(this.searchTxt)
      html = arr.join('<span style="background:#feced4;">' + this.searchTxt + '</span>')
      return html
    },
    buy () {
      let name = this.$route.name
      if (name === 'binocular' || name === 'purchasetwo') {
        this.$router.push({name: 'purchasetwo'})
      } else if (name === 'zhijia' || name === 'purchasezhijia') {
        this.$router.push({name: 'purchasezhijia'})
      } else {
        this.$router.push({name: 'purchase'})
      }
      this.active = false
    },
    goto (to) {
      this.$router.push(to)
      this.active = false
    },
    format (time) {
      let date = new Date(time)
      return date.format('yyyy-MM-dd')
    },
    async getData () {
      document.querySelector('#search-result').scrollTo(0, 0)
      let params = {
        pageSize: this.pageSize,
        pageNum: this.currentPage,
        searchKey: this.searchTxt
      }
      let result = await this.$http({
        method: 'post',
        data: params,
        url: '/scene/search'
      })
      let data = result.data.data
      this.scene = data.list
      this.total = data.total
      this.showCount = true
    }
  },
  components: {
    vcenter,
    Paging
  }
}
</script>

<style lang="scss" scoped>
@import './style.scss';
</style>
