<template>
  <div class="navbar" :class="'nav' + navType">
    <hamburger id="hamburger-container" :is-active="sidebar.opened" class="hamburger-container" @toggleClick="toggleSideBar" />

    <breadcrumb v-if="navType == 1" id="breadcrumb-container" class="breadcrumb-container" />
    <top-nav v-if="navType == 2" id="topmenu-container" class="topmenu-container" />
    <template v-if="navType == 3">
      <logo v-show="showLogo" :collapse="false"></logo>
      <top-bar id="topbar-container" class="topbar-container" />
    </template>
    <div class="right-menu">
       <!-- 商户经营账号：切换当前店铺（须含 merchant 角色，admin  alone 不展示） -->
      <div v-if="showShopSelector" class="right-menu-item shop-select-item">
        <span class="shop-select-label">当前店铺</span>
        <el-select
          v-model="currentShopId"
          size="small"
          placeholder="请选择店铺"
          :loading="shopLoading"
          @change="handleShopChange"
        >
          <el-option
            v-for="item in shopOptions"
            :key="item.shopId"
            :label="item.shopName"
            :value="item.shopId"
          />
        </el-select>
      </div>
      <template v-if="device!=='mobile'">
        <search id="header-search" class="right-menu-item" />

        <!-- <el-tooltip content="源码地址" effect="dark" placement="bottom">
          <ruo-yi-git id="ruoyi-git" class="right-menu-item hover-effect" />
        </el-tooltip> -->

        <!-- <el-tooltip content="文档地址" effect="dark" placement="bottom">
          <ruo-yi-doc id="ruoyi-doc" class="right-menu-item hover-effect" />
        </el-tooltip> -->

        <screenfull id="screenfull" class="right-menu-item hover-effect" />

        <el-tooltip content="布局大小" effect="dark" placement="bottom">
          <size-select id="size-select" class="right-menu-item hover-effect" />
        </el-tooltip>

        <!-- <el-tooltip content="消息通知" effect="dark" placement="bottom">
          <header-notice id="header-notice" class="right-menu-item hover-effect" />
        </el-tooltip> -->

      </template>


      <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="hover">
        <div class="avatar-wrapper">
          <img :src="avatar" class="user-avatar">
          <span class="user-nickname"> {{ nickName }} </span>
        </div>
        <el-dropdown-menu slot="dropdown">
          <router-link to="/user/profile">
            <el-dropdown-item>个人中心</el-dropdown-item>
          </router-link>
          <el-dropdown-item @click.native="setLayout" v-if="setting">
            <span>布局设置</span>
          </el-dropdown-item>
          <el-dropdown-item @click.native="lockScreen">
            <span>锁定屏幕</span>
          </el-dropdown-item>
          <el-dropdown-item divided @click.native="logout">
            <span>退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Breadcrumb from '@/components/Breadcrumb'
import TopNav from './TopNav'
import TopBar from './TopBar'
import Logo from './Sidebar/Logo'
import Hamburger from '@/components/Hamburger'
import Screenfull from '@/components/Screenfull'
import SizeSelect from '@/components/SizeSelect'
import Search from '@/components/HeaderSearch'
import RuoYiGit from '@/components/RuoYi/Git'
import RuoYiDoc from '@/components/RuoYi/Doc'
import HeaderNotice from './HeaderNotice'
import { getSellerContext, switchSellerShop } from '@/api/agri/seller/context'
import { setSellerShopContext, getSellerShopId } from '@/utils/sellerShop'

export default {
  components: {
    Breadcrumb,
    Logo,
    TopNav,
    TopBar,
    Hamburger,
    Screenfull,
    SizeSelect,
    Search,
    RuoYiGit,
    RuoYiDoc,
    HeaderNotice
  },
  data() {
    return {
      // 当前店铺 ID（X-Shop-Id）
      currentShopId: undefined,
      // 可切换店铺列表
      shopOptions: [],
      // 店铺上下文加载中
      shopLoading: false
    }
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'device',
      'nickName',
      'roles'
    ]),
    /** 仅 roles 含 merchant 时展示（admin  alone 不展示） */
    showShopSelector() {
      const roles = this.roles || []
      return roles.indexOf('merchant') !== -1
    },
    setting: {
      get() {
        return this.$store.state.settings.showSettings
      }
    },
    navType: {
      get() {
        return this.$store.state.settings.navType
      }
    },
    showLogo: {
      get() {
        return this.$store.state.settings.sidebarLogo
      }
    }
  },
  watch: {
    showShopSelector(val) {
      if (val) {
        this.loadSellerShopContext()
      }
    }
  },
  mounted() {
    if (this.showShopSelector) {
      this.loadSellerShopContext()
    }
  },
  methods: {
    toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
    /** 加载商家端店铺上下文 */
    loadSellerShopContext() {
      this.shopLoading = true
      getSellerContext().then(response => {
        const data = response.data || {}
        if (data.shopId != null) {
          setSellerShopContext(data.shopId, data.shopName)
          this.currentShopId = data.shopId
        }
        this.shopOptions = data.shops || []
        if (!this.shopOptions.length && data.shopId) {
          this.shopOptions = [{ shopId: data.shopId, shopName: data.shopName || '当前店铺' }]
        }
      }).catch(() => {
        this.shopOptions = []
      }).finally(() => {
        this.shopLoading = false
      })
    },
    /** 切换当前店铺，完成后刷新页面 */
    handleShopChange(shopId) {
      if (!shopId) {
        return
      }
      const prevShopId = getSellerShopId()
      this.shopLoading = true
      switchSellerShop({ shopId: shopId }).then(response => {
        const data = response.data || {}
        // setSellerShopContext(data.shopId, data.shopName)
        location.reload()
      }).catch(() => {
        this.shopLoading = false
        if (prevShopId) {
          this.currentShopId = Number(prevShopId) || prevShopId
        }
      })
    },
    setLayout(event) {
      this.$emit('setLayout')
    },
    lockScreen() {
      const currentPath = this.$route.fullPath
      this.$store.dispatch('lock/lockScreen', currentPath).then(() => {
        this.$router.push('/lock')
      })
    },
    logout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('LogOut').then(() => {
          location.href = '/index'
        })
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.navbar.nav3 {
  .hamburger-container {
    display: none !important;
  }
}

.navbar {
  height: 50px;
  overflow: hidden;
  position: relative;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
  display: flex;
  align-items: center;
  // padding: 0 8px;
  box-sizing: border-box;

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    cursor: pointer;
    transition: background .3s;
    -webkit-tap-highlight-color:transparent;
    display: flex;
    align-items: center;
    flex-shrink: 0;
    margin-right: 8px;

    &:hover {
      background: rgba(0, 0, 0, .025)
    }
  }

  .breadcrumb-container {
    flex-shrink: 0;
  }

  .topmenu-container {
    position: absolute;
    left: 50px;
  }

  .topbar-container {
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
    overflow: hidden;
    margin-left: 8px;
  }

  .right-menu {
    height: 100%;
    line-height: 50px;
    display: flex;
    align-items: center;
    margin-left: auto;

    &: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 .3s;

        &:hover {
          background: rgba(0, 0, 0, .025)
        }
      }
    }

    .shop-select-item {
      display: inline-flex;
      align-items: center;
      padding: 0 12px;
      font-size: 14px;

      .shop-select-label {
        color: #606266;
        margin-right: 8px;
        white-space: nowrap;
        line-height: 50px;
      }

      ::v-deep .el-select {
        width: 150px;
      }

      ::v-deep .el-input__inner {
        height: 28px;
        line-height: 28px;
      }
    }

    .avatar-container {
      margin-right: 0px;
      padding-right: 0px;

      .avatar-wrapper {
        margin-top: 10px;
        right: 8px;
        position: relative;

        .user-avatar {
          cursor: pointer;
          width: 30px;
          height: 30px;
          border-radius: 50%;
        }

        .user-nickname{
          position: relative;
          bottom: 10px;
          left: 2px;
          font-size: 14px;
          font-weight: bold;
        }

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