<template>
  <div class="navbar">
    <div class="left-menu">
      <hamburger
        id="hamburger-container"
        :is-active="sidebar.opened"
        class="hamburger-container"
        @toggleClick="toggleSideBar"
      />
      <template v-if="device !== 'mobile'">
        <breadcrumb id="breadcrumb-container" class="breadcrumb-container" />
      </template>
    </div>

    <div class="right-menu">
      <div class="right-menu-item">
        <company-select
          ref="companySelect"
          select-all
          global
          placeholder="请选择供应商"
          :style="{ width: device === 'mobile' ? '200px' : '400px' }"
        />
      </div>

      <el-tooltip placement="bottom" :content="switchAccountModeText">
        <i
          v-if="isSupertube"
          class="el-icon-sort right-menu-item hover-effect"
          style="
            height: 50px;
            width: 35px;
            line-height: 52px;
            font-size: 22px;
            transform: rotate(90deg);
          "
          @click="onSwitchCompanyMode"
        />
      </el-tooltip>

      <el-tooltip
        v-if="device !== 'mobile'"
        placement="bottom"
        content="登录采销结算平台"
      >
        <i
          class="el-icon-coin right-menu-item hover-effect"
          style="height: 50px; width: 40px; line-height: 52px; font-size: 22px"
          @click="openSettlementSystem(JSurl)"
        />
      </el-tooltip>
      <el-tooltip
        v-if="device !== 'mobile' && Number(currentLevel) !== 3"
        placement="bottom"
        content="登录采销数据统计"
      >
        <i
          class="el-icon-data-line right-menu-item hover-effect"
          style="height: 50px; width: 40px; line-height: 52px; font-size: 22px"
          @click="openSettlementSystem(DBurl)"
        />
      </el-tooltip>
      <el-tooltip
        v-if="device !== 'mobile'"
        placement="bottom"
        content="登录工单管理系统"
      >
        <p
          class="username"
          style="font-size:14px;color:#5a5e66;font-weight:500;line-height:54px;margin:0px 5px;cursor:pointer"
          @click="openSettlementSystem(GDurl)"
        >
          工单
        </p>
      </el-tooltip>

      <template v-if="device !== 'mobile'">
        <i
          v-if="isShow"
          class="el-icon-message-solid right-menu-item hover-effect shake"
          style="height: 50px; width: 40px; line-height: 52px; font-size: 22px"
          @click="openNotice()"
        />
        <screenfull id="screenfull" class="right-menu-item hover-effect" />
        <!-- <el-tooltip content="Global Size" effect="dark" placement="bottom">
          <size-select id="size-select" class="right-menu-item hover-effect" />
        </el-tooltip> -->
      </template>

      <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
        <div class="avatar-wrapper">
          <!-- <img :src="avatar + '?imageView2/1/w/80/h/80'" class="user-avatar"> -->

          <template v-if="userInfo.nickname && userInfo.nickname.length <= 3">
            <div class="username">
              {{ userInfo.nickname }}
              <i class="el-icon-caret-bottom" />
            </div>
          </template>

          <template v-if="userInfo.nickname && userInfo.nickname.length > 3">
            <el-tooltip
              class="item"
              effect="dark"
              :content="userInfo.nickname"
              placement="left-start"
            >
              <div class="username">
                {{ getUserName(userInfo.nickname) }}
                <i class="el-icon-caret-bottom" />
              </div>
            </el-tooltip>
          </template>
        </div>

        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="visible = true">
            <span style="display: block">修改密码</span>
          </el-dropdown-item>
          <el-dropdown-item @click.native="logout">
            <span style="display: block">退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

    <!-- <el-select
      class="fr right-menu-item"
      v-model="companyNo"
      :size="'mini'"
      style="width: 350px; margin: 12px 16px 0 0"
      @change="business_companyNo_change"
      placeholder="请选择供应商"
    >
      <el-option
        v-for="(item, index) in companyList"
        :key="item.supplierNo + item.id + index"
        :label="item.supplierName"
        :disabled="item.status !== '1'"
        :value="item.supplierNo"
      >
      </el-option>
    </el-select> -->

    <password-modal :visible.sync="visible" />
    <notify-modal ref="notifyModal" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import asyncRequest from '@/apis/service/system/updates'
import resToken from '@/mixins/resToken'
import CompanySelect from './company-select/index.vue'
import PasswordModal from '@/layout/components/password-modal/index.vue'
import NotifyModal from "./NotifyModal.vue"
import config from '@/config/index'

import {
  getNotice,
  setNotice,
  get_business_companyNo,
  get_business_company,
  getToken
} from '@/utils/auth'

import CryptoJS from 'crypto-js'
import { userStoreActions } from '@/store/modules/user'
import { accountLevels } from '@/assets/js/statusList'

export default {
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'device',
      'userInfo',
      'currentLevel',
      'navList',
      'isSupertube'
    ]),
    switchAccountModeText() {
      return this.currentLevel === '3' ? '切换到业务公司' : '切换到供应商'
    }
  },
  components: {
    CompanySelect,
    PasswordModal,
    NotifyModal
  },
  mixins: [resToken],
  data() {
    return {
      JSurl: config.settlementPlatformUrl + '/#/accept?t=',
      DBurl: config.dashboardUrl + '/#/accept?t=',
      GDurl: config.GDUrl + '#/demand/index?t=',
      companyNo: '',
      companyNoName: '',
      showModel: false,
      loading: false,
      isShow: true,
      statsTime: 0,
      endTime: 0,
      checked: true,
      visible: false,
      lastNotice: null, // 最后一次提示时间
      parmValue: {
        type: '',
        page: 1, // 页码
        size: 15 // 每页显示条数
      },
    }
  },
  mounted() {
    this.companyNo = get_business_companyNo() || ''
    this.companyNoName = get_business_company() || ''
  },
  methods: {
    openNotice(){
      this.$refs.notifyModal.openNotifyModal()
    },
    getUserName(username) {
      const chunks = username.split('')
      return chunks[0] + chunks[1] + '...'
    },
    openAlert() {
      this.$alert('正在开发中，敬请期待！', '提示', {
        type: 'warning'
      })
    },
    openSettlementSystem: function(url) {
      // 加密token
      const encJson = CryptoJS.AES.encrypt(
        JSON.stringify({ token: getToken() }),
        config.secretKey
      )
      const encData = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(encJson))
      // 跳转至结算平台携带加密后的token
      window.open(url + encData)
    },
    business_companyNo_change(e) {
      // const index = this.companyList.findIndex((si) => si.supplierNo === e);
      // if (index !== -1) {
      //   const { supplierNo, supplierName } = this.companyList[index];
      //   this.companyNo = supplierNo;
      //   this.companyNoName = supplierName;
      //   this.$store
      //     .dispatch("user/change_company", { supplierNo, supplierName })
      //     .then((res) => {
      //       console.log(res);
      //     })
      //     .catch(() => {});
      // }
    },
    is_Tips() {
      const nowtime = new Date().valueOf()
      const { sys_type, addtime } = this.activeMsg
      const timeV = new Date(addtime).valueOf()
      if (sys_type === 'VER') {
        this.statsTime = timeV
        this.endTime = this.statsTime + 1000 * 60 * 60 * 24 * 7
        if (nowtime >= this.statsTime && nowtime <= this.endTime) {
          return true
        } else {
          return false
        }
      } else {
        this.statsTime = 0
        this.endTime = timeV
        if (nowtime <= this.endTime) {
          return true
        } else {
          return false
        }
      }
    },
    toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=${this.$route.fullpath}`)
    },
    submit() {
      this.page_set_notice()
      this.showModel = false
    },
    // 保存提交结果
    page_set_notice() {
      const { sys_type, addtime } = this.activeMsg
      const model = {
        type: this.checked ? '1' : '0',
        sys_type: sys_type,
        addtime: addtime
      }
      setNotice(JSON.stringify(model));
    },

    // 切换以供应商或业务公司视角
    async onSwitchCompanyMode() {
      const level =
        this.currentLevel === accountLevels.supplier ? accountLevels.super : accountLevels.supplier
      this.$refs.companySelect && this.$refs.companySelect.selectAllCompany()
      this.$store.commit(userStoreActions.setCompanyList, [])
      this.$store.commit(userStoreActions.setCurrentLevel, level)
      await this.$store.dispatch(userStoreActions.reloadMenu, level)

      const parentRoute = this.navList[0]
      if (!parentRoute) return
      const toRoute = parentRoute.children[0]
      if (!toRoute) return
      const { url } = toRoute
      this.$router.replace('/reload?redirect=' + url.split('/index')[0])
    }
  }
}
</script>

<style lang="scss" scoped>
@keyframes shake {
  /* 水平抖动，核心代码 */
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }

  20%,
  80% {
    transform: translate3d(+2px, 0, 0);
  }

  30%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }

  40%,
  60% {
    transform: translate3d(+4px, 0, 0);
  }

  50% {
    transform: translate3d(-4px, 0, 0);
  }
}

.shake {
  animation: shake 800ms ease-in-out;
}

.navbar {
  height: 50px;
  position: relative;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  justify-content: space-between;

  .left-menu {
    display: flex;
    max-width: 1300px;
    .hamburger-container {
      line-height: 46px;
      height: 100%;
      cursor: pointer;
      transition: background 0.3s;
      -webkit-tap-highlight-color: transparent;

      &:hover {
        background: rgba(0, 0, 0, 0.025);
      }
    }

    .breadcrumb-container {
      display: flex;
      flex-wrap: nowrap;
      overflow: hidden;
      // width: 500px;
      //min-width: calc(1200px - 200px - 150px);
    }
  }

  .errLog-container {
    display: inline-block;
    vertical-align: top;
  }

  .right-menu {
    height: 100%;
    line-height: 50px;
    display: flex;
    flex-wrap: nowrap;

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;

      &.hover-effect {
        cursor: pointer;
        transition: background 0.3s;

        &:hover {
          background: rgba(0, 0, 0, 0.025);
        }
      }
    }

    .avatar-container {
      margin-right: 30px;

      .username {
        float: right;
        font-size: 14px;
        margin-left: 10px;
        margin-bottom: 10px;
        white-space: nowrap;
      }

      .avatar-wrapper {
        margin-top: 5px;
        position: relative;
        display: flex;

        .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
        }

        .el-icon-caret-bottom {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }
      }
    }
  }
}
</style>
