<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="登录工单管理系统"
      >
        <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>

      <el-tooltip
        v-if="device !== 'mobile'"
        placement="bottom"
        content="登录采销结算平台"
      >
        <i
          class="el-icon-s-promotion right-menu-item hover-effect"
          style="height: 50px; width: 40px; line-height: 52px; font-size: 22px"
          @click="openSettlementSystem(JSurl)"
        />
      </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">
          <!-- <router-link to="/person/my-message">
            <el-dropdown-item>我的信息</el-dropdown-item>
          </router-link>
          <router-link to="/person/change-phone">
            <el-dropdown-item>更换手机号</el-dropdown-item>
          </router-link> -->
          <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" />

    <el-dialog
      title="系统公告"
      :center="true"
      align="left"
      top="6vh"
      width="900px"
      :close-on-click-modal="false"
      :visible.sync="showModel"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      append-to-body
      @close="submit"
    >
      <el-card style="margin-top: -20px">
        <el-row v-if="activeMsg !== null" :gutter="10">
          <el-col :span="24">
            <div style="padding: 0 0 22px 0">
              <el-alert
                :closable="false"
                show-icon
                center
                class="my-el-alert"
                :title="activeMsg.module"
                :type="activeMsg.sys_type === 'VER' ? 'success' : 'warning'"
              />
            </div>
            <el-form
              :size="'mini'"
              label-position="left"
              label-width="82px"
              class="demo-table-expand"
              style="padding-left: 25px"
            >
              <el-row>
                <el-col v-if="activeMsg.sys_type === 'VER'" :span="12">
                  <el-form-item label="版本编号：">
                    <p style="margin: 0">{{ activeMsg.version }}</p>
                  </el-form-item>
                </el-col>
                <el-col :span="activeMsg.sys_type === 'VER' ? 12 : 24">
                  <el-form-item
                    :label="activeMsg.sys_type === 'VER' ? '更新时间：' : '预计时间：'"
                  >
                    <p style="margin: 0">
                      {{ activeMsg.addtime }}
                    </p>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="更新内容：">
                    <p style="margin: 0" v-html="activeMsg.system" />
                  </el-form-item>
                </el-col>
                <el-col :span="24" style="text-align: right">
                  <el-checkbox
                    v-model="checked"
                    class="fl"
                    style="padding-top: 5px"
                  >我已知晓，后续不再提示！</el-checkbox>
                  <el-button
                    type="primary"
                    plain
                    :size="'mini'"
                    @click="submit"
                  >关闭
                  </el-button>
                </el-col>
              </el-row>
            </el-form>
          </el-col>
        </el-row>
      </el-card>
    </el-dialog>
  </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 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'
import { userInfo } from 'os'

export default {
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'device',
      'userInfo',
      'currentLevel',
      'navList',
      'isSupertube'
    ]),
    switchAccountModeText() {
      return this.currentLevel === '3' ? '切换到业务公司' : '切换到供应商'
    }
  },
  components: {
    CompanySelect,
    PasswordModal
  },
  mixins: [resToken],
  data() {
    return {
      JSurl: config.settlementPlatformUrl + '/#/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 // 每页显示条数
      },
      activeMsg: null // 消息展示对象
    }
  },
  mounted() {
    this.companyNo = get_business_companyNo() || ''
    this.companyNoName = get_business_company() || ''
    this.openNotice(true)
  },
  methods: {
    getUserName(username) {
      const chunks = username.split('')
      return chunks[0] + chunks[1] + '...'
    },
    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
      // console.log(url + encData)
      // window.open(url + encData)

      this.$alert('正在开发中', '提示', {
        type: 'warning'
      })
    },
    async openNotice(is) {
      if (getNotice() && getNotice().length > 0) {
        this.lastNotice = JSON.parse(getNotice())
      } else {
        this.lastNotice = null
      }
      const { code, count, item, message } = await this.initData()
      if (code === 0) {
        if (count != 0) {
          this.activeMsg = item
          if (is) {
            this.typeShow()
          } else {
            this.showModel = true
          }
        } else {
          this.$message.warning('暂无系统消息！')
        }
      } else if (code >= 100 && code <= 104) {
        await this.logout()
      } else {
        this.$message.warning(message)
      }
    },
    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(() => {});
      // }
    },
    async initData() {
      const res = {
        code: 0,
        count: 0,
        item: {},
        message: ''
      }

      this.loading = true
      const { code, data, message } = await asyncRequest.list(this.parmValue)
      this.loading = false
      res.code = code
      res.message = message
      if (code === 0) {
        const { list, count } = data
        res.count = count
        if (count !== 0) {
          res.item = JSON.parse(JSON.stringify(list[0]))
        }
      }
      return res
    },
    typeShow() {
      const is = this.is_Tips()
      if (!is) {
        return
      }
      if (this.lastNotice + '' === 'null' && is) {
        this.showModel = true
      } else {
        const { addtime: laddtime, type: ltype, sys_type: lsys_type } = this.lastNotice
        const { sys_type, addtime } = this.activeMsg

        if (laddtime === addtime && lsys_type === sys_type) {
          if (ltype + '' === '1') {
            this.showModel = false
          } else {
            this.showModel = true
          }
        } else {
          this.showModel = true
        }
      }
    },
    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>
