<template>
  <nav class="site-navbar" :class="'site-navbar--' + navbarLayoutType">
    <div class="site-navbar__header">
      <!--      @click="$router.push({ name: 'home' })"-->
      <h1 class="site-navbar__brand">
        <el-menu
          class="site-navbar__menu"
          mode="horizontal">
          <el-menu-item class="site-navbar__switch" index="0" @click="sidebarFold = !sidebarFold">
            <icon-svg name="zhedie"></icon-svg>
          </el-menu-item>
        </el-menu>
        <a class="site-navbar__brand-lg" href="javascript:;">WMS</a>
        <a class="site-navbar__brand-mini" href="javascript:;">{{ pageLanguage.abbreviation }}</a>
      </h1>

    </div>

    <div class="site-navbar__body clearfix">

      <el-menu
        class="site-navbar__menu site-navbar__menu--right"
        mode="horizontal">
        <el-menu-item class="site-navbar__factory" index="0.5" v-if="siteList.length > 0">
          <div class="factory-selector">
            <i class="el-icon-office-building factory-icon"></i>
            <el-select
              v-model="selectedSite"
              @change="handleSiteChange"
              placeholder="选择工厂"
              class="factory-select"
              popper-class="factory-select-dropdown"
              size="small">
              <el-option
                v-for="item in siteList"
                :key="item.siteCode"
                :label="item.siteName"
                :value="item.siteCode">
              </el-option>
            </el-select>
          </div>
        </el-menu-item>
        <el-menu-item class="site-navbar__avatar" index="1">
         <span class="el-dropdown-link" @click="userSetting">
            <icon-svg name="editTable"  style="width: 25px;height: 25px;margin-top: 5px"></icon-svg>
          </span>
        </el-menu-item>
        <el-menu-item v-if="isAuth('review:show')" class="site-navbar__avatar" index="1">
         <span class="el-dropdown-link">
            <router-link :to="{path:'purchaseorder-procurementReview',query:{'': ''}}">
              工具待审核
            </router-link>
            <el-badge isAuth :value="pending.pendingReview" class="item" style="margin-top: 10px"/>
          </span>
        </el-menu-item>
        <el-menu-item class="site-navbar__avatar" index="2">
                      <span style="    color: #909399;" @click="helpFileList()">
                        帮助
                        <!--                             <icon-svg name="help"  style="width: 25px;height: 25px;margin-top: 5px"></icon-svg>-->
                      </span>
        </el-menu-item>
        <el-submenu index="3">
          <template slot="title">{{ pageLanguage.setting }}</template>
          <el-submenu index="2-1">
            <template slot="title">{{ pageLanguage.languageSetting }}</template>
            <el-menu-item index="2-1-1" :key="index" :value="item.languageCode" v-for="(item,index) in languageList "
                          @click.native="switch_the_language(item.languageCode)">{{ item.languageName }}
            </el-menu-item>
          </el-submenu>
          <el-submenu index="2-2">
            <template slot="title">{{ pageLanguage.userSetting }}</template>
            <el-menu-item index="2-2-1" @click.native="updatePasswordHandle()">{{ pageLanguage.updatePassword }}
            </el-menu-item>
            <el-menu-item index="2-2-2" @click.native="updateLanguageHandle()">{{ pageLanguage.updateDefaultLanguage }}
            </el-menu-item>
          </el-submenu>
          <el-menu-item index="2-3" @click="$router.push({ name: 'theme' })">{{ pageLanguage.cssSetting }}
          </el-menu-item>
          <el-menu-item index="2-4" @click="printList()">{{ pageLanguage.printSetting }}</el-menu-item>
        </el-submenu>
        <el-menu-item class="site-navbar__avatar" index="4">
          <el-dropdown :show-timeout="0" placement="bottom">
                      <span class="el-dropdown-link">
                        <img src="~@/assets/img/ccl.png" :alt="userName">{{ userName }}
                      </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="logoutHandle()">退出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-menu-item>
      </el-menu>

    </div>
    <!-- 弹窗, 修改密码 -->
    <update-password v-if="updatePassowrdVisible" ref="updatePassowrd"></update-password>
    <!-- 弹窗, 修改默认语言 -->
    <update-language v-if="updateLanguageVisible" ref="updateLanguage"></update-language>
    <!-- 文件列表 -->
    <FileListView ref="fileListView" v-if="helpFileVisible"></FileListView>
    <!-- 打印机列表 -->
    <UserPrintList ref="userPrintList" v-if="printListVisible"></UserPrintList>

    <!-- 动态列    -->
    <column v-if="visible" ref="column" @refreshData="getTableUserColumn" v-drag></column>
  </nav>
</template>

<script>
import UpdatePassword from './main-navbar-update-password'
import UpdateLanguage from './main-navbar-update-language'
import {clearLoginInfo} from '@/utils'
import FileListView from './modules/common/file-list-view'
import UserPrintList from './modules/common/user-print-list'
import column from "./modules/common/column";
import {
  searchFunctionButtonList,
  saveButtonList,
  searchSysLanguage,
} from "@/api/sysLanguage.js"
import {getUserAuthorizedSites} from '@/api/factory/accessSite.js'

export default {
  inject: ['refresh'],
  data() {
    return {
      visible: false,
      updatePassowrdVisible: false,
      updateLanguageVisible: false,
      helpFileVisible: false,
      printListVisible: false,
      message: this.$t('language.name'),
      languageList: [],
      siteList: [],
      selectedSite: '',
      pageLanguage: {
        XjSysManage: '旭捷管理系统',
        abbreviation: '旭捷',
        setting: '设置',
        languageSetting: '语言设置',
        userSetting: '用户设置',
        updatePassword: '修改密码',
        updateDefaultLanguage: '修改默认语言',
        cssSetting: '主提设置',
        printSetting: '打印设置',
      },
      // 导出 end
      pageLanguageList: [
        {
          functionId: "systemInformation",
          languageValue: '旭捷管理系统',
          objectId: 'XjSysManage',
          objectType: "label",
          tableId: "systemInformation"
        },
        {
          functionId: "systemInformation",
          languageValue: '首页',
          objectId: 'homePage',
          objectType: "label",
          tableId: "systemInformation"
        },
        {
          functionId: "systemInformation",
          languageValue: '旭捷',
          objectId: 'abbreviation',
          objectType: "label",
          tableId: "systemInformation"
        },
        {
          functionId: "systemInformation",
          languageValue: '设置',
          objectId: 'setting',
          objectType: "label",
          tableId: "systemInformation"
        },
        {
          functionId: "systemInformation",
          languageValue: '语言设置',
          objectId: 'languageSetting',
          objectType: "label",
          tableId: "systemInformation"
        },
        {
          functionId: "systemInformation",
          languageValue: '用户设置',
          objectId: 'userSetting',
          objectType: "label",
          tableId: "systemInformation"
        },
        {
          functionId: "systemInformation",
          languageValue: '修改密码',
          objectId: 'updatePassword',
          objectType: "label",
          tableId: "systemInformation"
        },
        {
          functionId: "systemInformation",
          languageValue: '修改用户语言',
          objectId: 'updateDefaultLanguage',
          objectType: "label",
          tableId: "systemInformation"
        },
        {
          functionId: "systemInformation",
          languageValue: '主题设置',
          objectId: 'cssSetting',
          objectType: "label",
          tableId: "systemInformation"
        },
        {
          functionId: "systemInformation",
          languageValue: '打印设置',
          objectId: 'printSetting',
          objectType: "label",
          tableId: "systemInformation"
        }
      ],
      pending: {
        pendingReview: 0,
        pendingSum: 0,
      },
      queryToolReview: {
        site: this.$store.state.user.site,
        userId: this.$store.state.user.name,
        strUserId: this.$store.state.user.id,
      },
      toolReviewTimer: null,
    }
  },
  watch: {
    pending: {
      deep: true,
      handler: function (newV, oldV) {
        this.pending.pendingSum = this.pending.pendingReview
      }
    },
  },
  components: {
    UpdatePassword,
    UpdateLanguage,
    FileListView,
    UserPrintList,
    column,
  },
  computed: {
    navbarLayoutType: {
      get() {
        return this.$store.state.common.navbarLayoutType
      }
    },
    sidebarFold: {
      get() {
        return this.$store.state.common.sidebarFold
      },
      set(val) {
        this.$store.commit('common/updateSidebarFold', val)
      }
    },
    mainTabs: {
      get() {
        return this.$store.state.common.mainTabs
      },
      set(val) {
        this.$store.commit('common/updateMainTabs', val)
      }
    },
    userName: {
      get() {
        return this.$store.state.user.userDisplay
      }
    }
  },
  activated() {

  },
  mounted() {
  },
  beforeDestroy() {
    clearInterval(this.toolReviewTimer);
  },
  methods: {
    // 打开页面设置
    userSetting() {
      this.visible = true;
      let queryTable = {
        userId: this.$store.state.user.name,
        functionId: this.$route.meta.menuId,
        languageCode: this.$i18n.locale,
        tableId: '',
      }
      this.$nextTick(() => {
        this.$refs.column.init(queryTable);
      })
    },
    getTableUserColumn() {
      this.$nextTick(() => {
        this.refresh()
      })
    },
    // 打印机列表
    printList() {
      this.printListVisible = true;
      this.$nextTick(() => {
        this.$refs.userPrintList.init()
      })
    },
    // 帮助文档列表
    helpFileList() {
      let fileMappingDto = {
        fileId: '',
        fileType: '功能帮助文档',
        orderRef1: this.$route.meta.menuId,
        orderRef2: '',
        orderRef3: '',
      }
      this.helpFileVisible = true;
      this.$nextTick(() => {
        this.$refs.fileListView.init(fileMappingDto)
      })
    },
    // 获取多语言列表
    getLanguageList() {
      searchSysLanguage({languageCode: this.$i18n.locale}).then(({data}) => {
        this.languageList = data.rows
      })
    },
    // 获取页面多语言数据
    getFunctionButtonList() {
      let queryButton = {
        functionId: 'systemInformation',
        tableId: 'systemInformation',
        languageCode: this.$i18n.locale,
        objectType: 'label'
      }
      searchFunctionButtonList(queryButton).then(({data}) => {
        if (data.code === 0) {
          this.pageLanguage = data.data
        }
      })
    },
    // 注3：增加语言切换函数
    switch_the_language(val) {
      localStorage.setItem('locale', val)
      this.$i18n.locale = val; // 修改当前语言
      location.reload()
    },
    // 修改密码
    updatePasswordHandle() {
      this.updatePassowrdVisible = true
      this.$nextTick(() => {
        this.$refs.updatePassowrd.init()
      })
    },
    // 修改用户默认语言
    updateLanguageHandle() {
      this.updateLanguageVisible = true
      this.$nextTick(() => {
        this.$refs.updateLanguage.init()
      })
    },
    // 退出
    logoutHandle() {
      this.$confirm(`确定进行[退出]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/sys/logout'),
          method: 'post',
          data: this.$http.adornData()
        }).then(({data}) => {
          if (data && data.code === 0) {
            clearLoginInfo()
            this.$router.push({name: 'login'})
          }
        })
      }).catch(() => {
      })
    },
    // 初始化工厂选择
    initSiteSelection() {
      // 从localStorage获取当前选择的工厂
      this.selectedSite = localStorage.getItem('site') || '';

      // 获取当前用户的工厂列表
      const userName = localStorage.getItem('userName');
      if (userName) {
        this.getUserSiteList(userName);
      }
    },
    // 获取用户授权的工厂列表
    getUserSiteList(userName) {
      if (!userName || !userName.trim()) {
        this.siteList = [];
        return;
      }

      getUserAuthorizedSites({ userName: userName.trim() }).then(({data}) => {
        if (data && data.code === 0) {
          this.siteList = data.data || data.list || [];

          // 如果当前选择的工厂不在列表中，清空选择
          if (this.selectedSite && !this.siteList.find(site => site.siteCode === this.selectedSite)) {
            this.selectedSite = '';
            localStorage.removeItem('site');
          }

          // 如果没有选择工厂但有工厂列表，选择第一个
          if (!this.selectedSite && this.siteList.length > 0) {
            this.selectedSite = this.siteList[0].siteCode;
            localStorage.setItem('site', this.selectedSite);
          }
        } else {
          this.siteList = [];
          console.error('获取工厂列表失败:', data.msg);
        }
      }).catch(error => {
        this.siteList = [];
        console.error('获取工厂列表失败:', error);
      })
    },
    // 工厂选择变更处理
    handleSiteChange(siteCode) {
      const selectedSite = this.siteList.find(site => site.siteCode === siteCode);
      const siteName = selectedSite ? selectedSite.siteName : siteCode;

      localStorage.setItem('site', siteCode);

      this.$message({
        message: `已切换到工厂：${siteName}`,
        type: 'success',
        duration: 2000,
        showClose: true
      });

      // 添加切换动画效果
      const factorySelect = document.querySelector('.factory-select');
      if (factorySelect) {
        factorySelect.style.transform = 'scale(1.05)';
        setTimeout(() => {
          factorySelect.style.transform = 'scale(1)';
        }, 200);
      }
    }
  },
  created() {
    this.getLanguageList()
    this.getFunctionButtonList()
    this.initSiteSelection()
  }
}
</script>

<style lang="scss">
.icon-svg {
  width: 2em;
}

.el-menu--collapse .el-menu .el-submenu, .el-menu--popup, .el-menu-item {
  min-width: 50px !important;
}

.site-navbar__brand-lg, .site-navbar__brand-mini {
  margin: 0 5px;
  color: #fff;
  margin-left: -45px;
}

// 工厂选择器样式
.site-navbar__factory {
  padding: 0 15px !important;

  .factory-selector {
    display: flex;
    align-items: center;
    gap: 8px;

    .factory-icon {
      color: #409EFF;
      font-size: 16px;
      margin-right: 4px;
    }

    .factory-select {
      width: 140px;
      transition: transform 0.2s ease;

      .el-input__inner {
        background: rgba(64, 158, 255, 0.1);
        border: 1px solid rgba(64, 158, 255, 0.3);
        border-radius: 20px;
        color: #409EFF;
        font-size: 13px;
        height: 32px;
        line-height: 32px;
        transition: all 0.3s ease;

        &:hover {
          background: rgba(64, 158, 255, 0.15);
          border-color: #409EFF;
          box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
        }

        &:focus {
          background: rgba(64, 158, 255, 0.1);
          border-color: #409EFF;
          box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
        }
      }

      .el-input__suffix {
        .el-input__suffix-inner {
          .el-select__caret {
            color: #409EFF;
            transition: transform 0.3s ease;
          }
        }
      }

      &.is-focus {
        .el-input__suffix-inner .el-select__caret {
          transform: rotateZ(180deg);
        }
      }
    }
  }

  &:hover {
    background-color: rgba(64, 158, 255, 0.05) !important;
  }
}

// 工厂选择下拉选项样式 - 使用popper-class限制作用域，避免影响全局下拉框
.factory-select-dropdown {
  .el-select-dropdown__item {
    &:hover {
      background-color: rgba(64, 158, 255, 0.1);
      color: #409EFF;
    }

    &.selected {
      background-color: #409EFF;
      color: #fff;
      font-weight: 500;

      &::after {
        content: '✓';
        position: absolute;
        right: 15px;
        font-weight: bold;
      }
    }
  }
}

.el-menu--horizontal > .el-menu-item {
  color: #3b4249;
}

</style>

