<!-- 前台头部 -->
<template>
  <el-header style="height: fit-content">
    <div class="header-container">
      <!--      @click="goIndex"-->
      <div class="header-left">
        <img :src="frontLogoPath" alt class="logo" />
        <span class="title-name">{{ systemInformation.name }}</span>
      </div>
      <div class="first-menus">
        <div
          v-for="item in frontMenus"
          :key="item.alias"
          :class="`first-menus-item ${currentMenu.alias == item.alias ? 'active-menu' : ''}`"
          @click="handleClickMenu(item)"
        >
          <svg-icon :icon-class="item.menuIcon ? item.menuIcon : ''" icon-style="icon header-icon" />
          {{ item.name }}
        </div>
      </div>
      <div style="margin-right: 40px">
        <el-popover :visible-arrow="false" popper-class="header-popper" trigger="hover" width="250">
          <ht-avatar slot="reference" :user="currentUser" class="avatar" />
          <template>
            <div>
              <div class="flex user-box-header">
                <ht-avatar :user="currentUser" style="margin-right: 15px" />
                <div>
                  <h3 v-if="$store.state.login.currentUser" style="margin: 5px 0">
                    {{ $store.state.login.currentUser.username }}
                  </h3>
                </div>
              </div>
              <div>
                <ul class="user-link-ul">
                  <li @click="openPersonalCenter">
                    <i class="el-icon-user" />
                    个人中心
                  </li>
                  <li @click="openResetPwdDialog">
                    <i class="icon-set" />
                    修改密码
                  </li>
                  <li v-if="userType !== 2" @click="handleSysPlat">
                    <i class="icon-monitor" />
                    系统管理
                  </li>
                </ul>
              </div>
              <div class="flex user-box-logout" @click="logout">
                <el-link :underline="false">退出系统</el-link>
              </div>
            </div>
          </template>
        </el-popover>
      </div>
    </div>

    <ht-sidebar-dialog
      id="modlfy-dialog"
      :before-close="() => (modifyPwdDialogVisible = false)"
      :close-on-click-modal="false"
      :visible.sync="modifyPwdDialogVisible"
      title="修改密码"
      width="28%"
    >
      <el-form ref="pwdForm" :model="pwdForm" :rules="pwdRules" label-width="120px" size="mini">
        <el-form-item label="旧密码" prop="old">
          <el-input v-model="pwdForm.old" placeholder="请输入旧密码" type="password" />
        </el-form-item>
        <el-form-item label="新密码" prop="new">
          <el-input v-model="pwdForm.new" placeholder="请输入新密码" type="password" />
        </el-form-item>
        <el-form-item label="重复新密码" prop="newRepeat">
          <el-input v-model="pwdForm.newRepeat" placeholder="请再次输入新密码" type="password" />
        </el-form-item>
      </el-form>
      <span class="dialog-footer" style="text-align: center; bottom: auto">
        <el-button size="small" type="primary" @click="submitForm()">确认</el-button>
        <el-button size="small" @click="modifyPwdDialogVisible = false">取 消</el-button>
      </span>
    </ht-sidebar-dialog>
  </el-header>
</template>

<script>
import HtAvatar from '@/components/common/HtAvatar.vue';
import { mapGetters, mapState } from 'vuex';

export default {
  name: 'Navigator',
  components: { HtAvatar },
  props: ['menuShow', 'showTopMenu'],
  data() {
    var validateNew = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      }
      const config = this.pwdStrategy;
      if (config.enable == 1) {
        const pwdRule = config.pwdRule;
        const pwdLength = config.pwdLength;
        if (pwdRule) {
          if (value.length < pwdLength) {
            callback(new Error(`新密码长度至少为${pwdLength}`));
          } else if (pwdRule == 2) {
            var re = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])');
            if (!re.test(value)) {
              callback(new Error('新密码必须包含数字、字母'));
            } else {
              callback();
            }
          } else if (pwdRule == 3) {
            var re = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9])');
            if (!re.test(value)) {
              callback(new Error('新密码必须包含数字、字母、特殊字符'));
            } else {
              callback();
            }
          } else if (pwdRule == 4) {
            var re = new RegExp('(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9])');
            if (!re.test(value)) {
              callback(new Error('新密码必须包含数字、大小字母、特殊字符'));
            } else {
              callback();
            }
          } else {
            callback();
          }
        }
      } else {
        if (value.length < 6) {
          callback(new Error('新密码长度至少为6'));
        } else {
          callback();
        }
      }
    };
    var validateold = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入旧密码'));
      } else {
        callback();
      }
    };
    var validateNewReapeat = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'));
      } else {
        callback();
      }
    };
    return {
      currentMenu: {},
      modifyPwdDialogVisible: false,
      pwdForm: {
        old: '',
        new: '',
        newRepeat: '',
      },
      pwdRules: {
        old: [{ validator: validateold, trigger: 'blur' }],
        new: [{ validator: validateNew, trigger: 'blur' }],
        newRepeat: [{ validator: validateNewReapeat, trigger: 'blur' }],
      },
    };
  },
  created() {},
  mounted() {
    this.init();
  },
  computed: {
    ...mapState({
      currentUser: (state) => state.user.currentUserDetail,
      token: (state) => state.login.currentUser.token,
      frontMenus: (state) => {
        return state.menu.frontMenus;
      },
      sysMenus: (state) => state.menu.sysMenus,
      userType: function () {
        if (this.currentUser && this.currentUser.user) {
          return this.currentUser.user.userType;
        }
      },
      pwdStrategy: (state) => state.user.pwdStrategy,
      systemInformation: (state) => state.system.systemInformation || {},
    }),
    ...mapGetters('system', ['frontLogoPath']),
  },
  methods: {
    async init() {
      !this.currentUser && this.$store.dispatch('user/loadCurrentUserDetail');
      const currentUser = this.$store.state.login.currentUser;
      if ((!this.frontMenus || this.frontMenus.length == 0) && currentUser) {
        await this.$store.dispatch('menu/actionFrontMenus');
      }
      this.activePage();
    },
    goIndex() {
      this.$router.push({
        path: '/frontPlat/gis',
      });
    },
    openResetPwdDialog() {
      this.$store.dispatch('user/getDefPwdStrategy');
      this.modifyPwdDialogVisible = true;
      if (this.$refs['pwdForm']) {
        this.$refs['pwdForm'].resetFields();
      }
    },
    openPersonalCenter() {
      this.$router.push({
        path: '/bizPlat/PersonalInfo',
      });
    },
    handleSysPlat() {
      if (!this.sysMenus.length) {
        this.$store.dispatch('menu/actionSysMenus').then((res) => {
          if (res) {
            window.open(
              `${
                window.context.manage
                // "http://localhost:8081/mvue"+
              }/sysplat/` +
                `${this.sysMenus[0].children[0].alias}` +
                `?token=${this.token}`,
              '_blank',
            );
          }
        });
      } else {
        window.open(
          `${
            window.context.manage
            // "http://localhost:8081/mvue"+
          }/sysplat/` +
            `${this.sysMenus[0].children[0].alias}` +
            `?token=${this.token}`,
          '_blank',
        );
      }
    },
    logout() {
      this.$store.dispatch('menu/clearMenus');
      this.$store.dispatch('user/clearUser');
      this.$store.dispatch('menu/setCopyMenus', []); // 菜单
      const loginRouthPath = localStorage.getItem(`${this.$store.state.login.currentUser.account}loginRoutePath`) || '/login';
      this.$store.dispatch('login/logoutAndCleanUp').then(() => {
        switch (window.ssoConfig.mode) {
          case 'cas':
          case 'oauth':
            window.sessionStorage.removeItem('currentUser');
            window.location.href = `${window.ssoConfig.logout}?service=${window.location.href.split('?')[0]}`;
            break;
          default:
            this.$router.push({
              path: loginRouthPath,
            });
            break;
        }
      });
    },
    handleClickMenu(item = this.currentMenu) {
      const hasSideMenu = !!item.children.length;
      this.$emit('update:menuShow', hasSideMenu);
      this.currentMenu = item;
      let path = '';
      if (item.children.length > 0) {
        const childrens = item.children;
        const subPath = childrens[0].alias;

        this.$emit('onChangeTopMenu', item);

        if (childrens[0]?.children?.length) {
          const threeChildrens = childrens[0].children || childrens[0].href;
          const threePath = threeChildrens[0].alias || threeChildrens[0].href;
          path = `/bizPlat/${item.alias}/${subPath}/${threePath}`;
        } else {
          path = `/bizPlat/${item.alias}/${subPath}`;
        }
      } else {
        path = `/bizPlat/${item.alias || item.href}`;
        this.currentMenu = item;
      }
      // const {resolved: route} = this.$router.resolve(path);
      const route = this.$router.resolve(path);
      console.log(route);
      // this.$router.push(path)
    },
    activePage() {
      if (!this.frontMenus.length) return;
      this.currentMenu = this.frontMenus[0];
      this.handleClickMenu();
      // let fullPath = this.$route.path
      // let path = fullPath.split('/')
      // let urlAnchor = path[path.indexOf('bizPlat') + 1]
      // console.log(this.frontMenus)
      // this.frontMenus.filter((item) => {
      //   console.log(item.alias, urlAnchor)
      //   if (item.alias == urlAnchor) {
      //     console.log(item)
      //     this.currentMenu = item
      //     this.$emit('update:menuShow', !!item.children?.length)
      //     item.children?.length && this.$emit('onChangeTopMenu', item)
      //   }
      // })
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';

.el-header {
  padding: 0;
}

.header-container {
  width: 100%;
  height: 65px;
  display: flex;
  align-items: center;
  background-color: $--biz-main-color;
  color: #fff;
  z-index: 999;
}

.header-left {
  width: fit-content;
  display: flex;
  justify-content: space-around;
  align-items: center;
  cursor: pointer;
  padding: 0 30px;

  .logo {
    width: 50px;
    height: auto;
    vertical-align: middle;
  }

  .title {
    width: 260px;
    margin-left: 10px;
    height: 30px;
    vertical-align: middle;
  }

  .title-name {
    margin-left: 10px;
    color: #fff;
    font-size: 18px;
    font-weight: bold;
    letter-spacing: 3px;
    vertical-align: middle;
  }
}

.first-menus {
  display: flex;
  flex: 1;
  margin-left: 50px;
}

.first-menus-item {
  margin: 0 5px;
  padding: 10px 10px;
  position: relative;
  cursor: pointer;
  font-size: 14px;
  color: #fff;
  opacity: 0.7;
  border-radius: 3px;
  transition: all 0.4s;

  .header-icon {
    font-size: 18px;
  }
}

.first-menus-item.active-menu {
  // // color: #fff; //#00ccff;
  // color: $--biz-main-color;
  // opacity: 1;
  // // background-color: #5eb2ff;
  // background-color: #fff;

  color: #fff; //#00ccff;
  opacity: 1;
  background-color: #5eb2ff;
}

.first-menus-item:hover {
  // color: #fff; //#00ccff;
  color: $--biz-main-color;
  background-color: #ccebff;
}

.header-right {
  margin-right: 10px;
}

.el-avatar {
  width: 40px;
  height: 40px;
  line-height: 40px;
}

.el-avatar i {
  font-size: 16px;
  color: #c0c4cc;
}

.user-box-header {
  padding: 10px;
  //background: $--biz-main-color;

  h3 {
    color: #333;
  }
}

.user-link-ul {
  list-style: none;
  padding: 0;
  margin: 0;

  > li {
    padding: 8px 10px;
    cursor: pointer;
    color: #555;
  }

  > li > i {
    margin-right: 5px;
    font-size: 16px;
    font-weight: bold;
  }

  > li:hover {
    color: $--biz-main-color;
    background-color: #e6f7ff;
  }

  .el-link {
    color: #606266 !important;

    i {
      font-size: 16px;
      margin-right: 5px;
      vertical-align: middle;
    }
  }
}

.user-box-logout {
  justify-content: center;
  // margin-top: 10px;
  color: $--biz-main-text-color !important;
}

.user-box-logout:hover {
  background: #e6f7ff;
}

.user-box-logout > .el-link {
  line-height: 46px;
  width: 100%;
}

.user-box-logout > .el-link:hover,
.user-box-logout > .el-link:focus {
  color: $--biz-main-color;
}
</style>
