<template>
  <div class="dc-page-header-container">
    <div class="dc-trademark">
      <div class="dc-logo">
        <div class="dc-logo-svg">
          <img v-if="logoSvg" :src="logoSvg" />
        </div>
        <div class="dc-logo-text" v-if="logoSlogan">{{ logoSlogan }}</div>
      </div>
      <div class="dc-company" :style="{ 'margin-left': nameOffset + 'px' }">
        <div class="dc-company-zh-cn" v-if="companyZnName">{{ companyZnName }}</div>
        <div class="dc-company-en-us" v-if="companyEnName">{{ companyEnName }}</div>
      </div>
    </div>
    <div class="dc-nav" :style="{ maxWidth: 'calc(100vw - ' + (enableMsgNotice && showSearch ? '825px' : '605px') + ')' }" v-if="isHideWhenOnlyOne ? sysFuiAppRels.length > 1 : sysFuiAppRels.length > 0">
      <a-tabs type="card" v-model="activeAppId" @tabClick="nav($event)">
        <a-tab-pane v-for="item in fuiSysAppInfos" :key="item.appId" :tab="item.appName">{{ item.appName }}</a-tab-pane>
      </a-tabs>
    </div>
    <div class="dc-opts">
      <div class="dc-search-box" v-if="enableSearch">
        <a-auto-complete class="dc-search-input" v-if="showSearch" :data-source="dataSource" placeholder="请输入合同编号" />
        <a-button size="small" class="dc-search-btn" type="link" @click="toggleSearchBox">
          <img class="dc-search-btn-icon" :src="searchSvg" />
          <div class="dc-search-btn-text">搜索</div>
        </a-button>
      </div>
      <div class="dc-message-box" v-if="enableMsgNotice">
        <a-badge class="dc-badge" :count="newMsgNum">
          <div class="dc-message-svg-box">
            <img class="dc-message-svg" :src="messageSvg" />
          </div>
        </a-badge>
      </div>
      <div class="dc-role">{{ "默认角色" }}</div>
      <div class="dc-user">
        <div class="dc-user-name">
          <a-dropdown v-if="$userStore.user" :getPopupContainer="getPopupContainer">
            <a class="dc-dropdown-link">
              <div class="dc-dropdown-link-text">{{ $userStore.user.userName }}</div>
              <a-icon type="down" />
            </a>
            <a-menu class="dc-user-dm-box" slot="overlay">
              <a-menu-item>
                <a class="dc-dm-item" href="javascript:;" @click="handleMyApp">我的应用</a>
              </a-menu-item>
              <a-menu-item>
                <a class="dc-dm-item" href="javascript:;" @click="handleChangePassword">修改密码</a>
              </a-menu-item>
              <a-menu-item>
                <a class="dc-dm-item" href="javascript:;" @click="handleLogout">退出系统</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </div>
      </div>
      <dc-my-app v-if="myAppVisible" :visible.sync="myAppVisible" :sysAppInfos="allSysAppInfos" :sysFuiAppRels="sysFuiAppRels" @close="handleModalClose"></dc-my-app>
      <dc-user-change-password v-if="changePasswordVisible" :visible.sync="changePasswordVisible"></dc-user-change-password>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { AutoComplete, Badge, Button, Dropdown, Icon, Menu, Tabs, message } from "ant-design-vue";
import { oauthService } from "../../services/oauth.service";
import { Prop, Watch } from "vue-property-decorator";
import { RestApi } from "../../model/RestApi";
import { RestfulResponse } from "../../model/RestfulResponse";
import { SysAppInfo } from "../../model/SysAppInfo";
import { Code } from "../../constants/enum/code.enum";
import { apiService } from "../../services/api.service";
import sysAppInfoApi from "../../constants/api/sys-app-info.api";
import { routerService } from "../../services/router.service";
import { MESSAGE_SVG_XML, SEARCH_SVG_XML } from "../../constants/encode-assets/svg";
import MyApp from "./MyApp.vue";
import { SysFuiAppRel } from "../../model/SysFuiAppRel";
import sysFuiAppRelApi from "../../constants/api/sys-fui-app-rel.api";
import { AppLink } from "../../constants/enum/app-link.enum";
import UserChangePassword from "./UserChangePassword.vue";

@Component({
  name: "PageHeader",
  components: {
    [Menu.name]: Menu,
    [Dropdown.name]: Dropdown,
    [Menu.Item.name]: Menu.Item,
    [Tabs.name]: Tabs,
    [Tabs.TabPane.name]: Tabs.TabPane,
    [Icon.name]: Icon,
    [AutoComplete.name]: AutoComplete,
    [Button.name]: Button,
    [Badge.name]: Badge,
    "dc-user-change-password": UserChangePassword,
    "dc-my-app": MyApp,
  },
})
export default class PageHeader extends Vue {
  searchSvg: any = SEARCH_SVG_XML; // 搜索图标
  messageSvg: any = MESSAGE_SVG_XML; // 消息图标

  @Prop() logoSvg: string | undefined; // logo图标
  @Prop() logoSlogan: string | undefined; // logo标语
  @Prop({ default: () => -13 }) nameOffset!: any; // 名称偏移量
  @Prop() companyZnName: string | undefined; // 公司中文名称
  @Prop() companyEnName: string | undefined; // 公司因为名称
  @Prop({ default: false }) dynamic!: boolean; // 是否动态加载系统信息
  @Prop({ default: () => [] }) staticAllSysAppInfos!: SysAppInfo[]; // 静态-全部导航列表
  @Prop({ default: false }) enableSearch!: boolean; // 启用搜索
  @Prop({ default: false }) enableMsgNotice!: boolean; // 启用消息通知
  @Prop({ default: false }) enableRole!: boolean; // 启用角色切换
  @Prop({ default: false }) isHideWhenOnlyOne!: boolean; // 只有一个时隐藏

  myAppVisible = false; // 我的应用弹窗
  changePasswordVisible = false; // 修改密码弹窗
  showSearch = false; // 展开搜索
  newMsgNum = 1; // 新消息数量

  activeAppId = ""; // 当前激活导航
  dataSource: any[] = []; // 搜索结果
  allSysAppInfos: SysAppInfo[] = []; // 全部导航列表
  sysFuiAppRels: SysFuiAppRel[] = []; // 常用导航关联列表

  getPopupContainer = (triggerNode: any) => {
    return triggerNode;
  }; // 下拉面板位置

  // 常用导航列表
  get fuiSysAppInfos(): SysAppInfo[] {
    return this.sysFuiAppRels?.map((item) => this.allSysAppInfos.find((it) => it.appId === item.appId)!)?.filter((item) => item != null) || [];
  }

  mounted(): void {
    if (this.dynamic) {
      this.loadSysInfo();
    } else {
      this.onStaticAllSysAppInfosChange(this.staticAllSysAppInfos);
    }
  }

  @Watch("$route", { immediate: true })
  onRouteChange() {
    this.toggleActiveNavMenus();
  }

  /**
   * @description: 静态数据变更处理
   * @author ChenRui
   * @date 2021/9/15 16:08
   */
  @Watch("staticAllSysAppInfos")
  onStaticAllSysAppInfosChange(val: SysAppInfo[]) {
    if (!this.dynamic) {
      this.allSysAppInfos = this.staticAllSysAppInfos || [];
      this.sysFuiAppRels = [];
      this.allSysAppInfos.forEach((item) => {
        this.sysFuiAppRels.push(
          new SysFuiAppRel({
            appId: item.appId,
          })
        );
      });
    }
  }

  /**
   * @description: 加载常用系统及所有系统
   * @author ChenRui
   * @date 2021/3/31 17:13
   */
  loadSysInfo(): Promise<any> {
    return Promise.all([this.loadAllSysInfo(), this.loadFuiAppRels()]).then(([resAll, resCom]: any[]) => {
      if (resAll.code === Code.SUCCESS.code && resCom.code === Code.SUCCESS.code) {
        this.toggleActiveNavMenus();
      } else {
        message.error({ duration: 1, content: "系统错误，请联系管理员" });
      }
    });
  }

  /**
   * @description: 加载所有应用
   * @author ChenRui
   * @date 2021/8/10 15:49
   */
  loadAllSysInfo(): Promise<RestfulResponse> {
    const restApi: RestApi = new RestApi(sysAppInfoApi.queryAuthorizedApp);
    restApi.url = this.$dc.baseApi + sysAppInfoApi.queryAuthorizedApp.url;
    return apiService.general(restApi).then((res: RestfulResponse) => {
      if (res.code === Code.SUCCESS.code) {
        this.allSysAppInfos = res.data || [];
      }
      return res;
    });
  }

  /**
   * @description: 加载常用应用
   * @author ChenRui
   * @date 2021/8/10 15:56
   */
  loadFuiAppRels(): Promise<RestfulResponse> {
    const restApi: RestApi = new RestApi(sysFuiAppRelApi.queryByUserId);
    restApi.url = this.$dc.baseApi + sysFuiAppRelApi.queryByUserId.url;

    const query = {
      userId: this.$userStore.user?.userId,
    };
    return apiService.general(restApi, query).then((res: RestfulResponse) => {
      if (res.code === Code.SUCCESS.code) {
        this.sysFuiAppRels = res.data || [];
      }
      return res;
    });
  }

  /**
   * @description: 无权访问
   * @author ChenRui
   * @date 2021/4/20 11:30
   */
  noAccessHandler(event: any): void {
    this.$emit("no-access", event);
  }

  /**
   * @description: 激活当前系统对应的选项卡
   * @author ChenRui
   * @date 2020/12/18 22:24
   */
  toggleActiveNavMenus(): void {
    const pathName: string = window.document.location.pathname;
    if (pathName && pathName.length > 0) {
      const projectName: string = pathName.substring(1, pathName.substr(1).indexOf("/") + 1);
      if (projectName && projectName.length > 0) {
        let systemNav: SysAppInfo | undefined = this.fuiSysAppInfos.find((item) => item.mountName === projectName);
        if (systemNav == null && this.allSysAppInfos != null && this.allSysAppInfos.length > 0) {
          systemNav = this.allSysAppInfos.find((item) => item.mountName === projectName);
          if (systemNav) {
            this.sysFuiAppRels.push(new SysFuiAppRel({ appId: systemNav.appId }));
          }
        }
        if (systemNav) {
          this.activeAppId = systemNav?.appId || "";
        }
      }
    }
  }

  /**
   * @description: 切换搜索框伸缩状态
   * @author ChenRui
   * @date 2021/8/10 20:41
   */
  toggleSearchBox() {
    this.showSearch = !this.showSearch;
  }

  /**
   * @description: 跨应用导航
   * @author ChenRui
   * @date 2021/8/10 16:00
   */
  nav(event: any): void {
    const sysAppInfo: SysAppInfo | undefined = this.allSysAppInfos.find((item) => item.appId === event);
    if (sysAppInfo && sysAppInfo.appUrl) {
      if (sysAppInfo.isLink === AppLink.OUT.code) {
        window.open(sysAppInfo.appUrl, "_blank");
      } else {
        const appUrl: string = sysAppInfo.appUrl.toLowerCase();
        const regex = /(http|https):\/\/([\w.]+\/?)\S*/;
        if (regex.test(appUrl)) {
          routerService.push(sysAppInfo.appUrl);
        } else {
          const url = window.location.protocol + "//" + location.host + sysAppInfo.appUrl;
          routerService.push(url);
        }
      }
    }
  }

  /**
   * @description: 我的应用
   * @author ChenRui
   * @date 2021/8/16 10:48
   */
  handleMyApp(): void {
    this.myAppVisible = true;
  }

  /**
   * @description: 修改密码
   * @author ChenRui
   * @date 2021/10/11 17:42
   */
  handleChangePassword(): void {
    this.changePasswordVisible = true;
  }

  /**
   * @description: 模态框关闭
   * @author Zhang Qishan
   * @date 2021/8/28 2:36
   */
  handleModalClose(response: RestfulResponse): void {
    if (response && response.code === Code.SUCCESS.code) {
      this.loadFuiAppRels().then();
    }
  }

  /**
   * @description: 用户登出
   * @author ChenRui
   * @date 2021/8/10 15:54
   */
  handleLogout(): void {
    oauthService.logOut().then((res: RestfulResponse) => {
      this.$emit("logout", res);
    });
  }
}
</script>

<style scoped lang="scss">
.dc-page-header-container {
  display: flex;
  align-items: center;
  background-color: #2462b2;
  height: 50px;
  padding: 0 10px;
  font-family: "lucida grande", "lucida sans unicode", lucida, helvetica, "Hiragino Sans GB", "MicrosoftYaHei", "WenQuanYi Micro Hei", sans-serif !important;
  .dc-trademark {
    display: flex;
    align-items: center;
    width: 235px;
    padding-top: 3px;
    .dc-logo {
      display: flex;
      flex-direction: column;
      .dc-logo-svg {
        display: flex;
        justify-content: center;
        img {
          width: 27px;
          height: 22px;
          display: block;
        }
      }
      .dc-logo-text {
        font-weight: 600;
        font-size: 12px;
        width: 100%;
        text-align: center;
        transform: scale(0.8);
        color: #ffffff;
      }
    }
    .dc-company {
      color: #ffffff;
      .dc-company-zh-cn {
        letter-spacing: 4px;
        text-align: center;
        font-size: 12px;
        font-weight: 600;
        margin-bottom: -3px;
        transform: scale(0.95);
        padding-left: 3px;
      }
      .dc-company-en-us {
        font-size: 12px;
        font-weight: 600;
        transform: scale(0.8);
      }
    }
  }
  .dc-nav {
    flex-grow: 1;
    height: 100%;
    ::v-deep {
      > .ant-tabs {
        height: 50px;
        .ant-tabs-bar {
          height: 100%;
          margin-bottom: 0;
          border-bottom: 0;
          .ant-tabs-nav-container {
            height: 100%;
            margin-bottom: 0;
            .ant-tabs-nav-wrap {
              height: 100%;
              .ant-tabs-nav-scroll {
                height: 100%;
                .ant-tabs-nav {
                  height: 100%;
                  & > div {
                    height: 100%;
                    display: flex;
                    flex-direction: row;
                    .ant-tabs-tab {
                      border: 0;
                      margin: 0;
                      padding: 0 16px;
                      height: 100%;
                      border-radius: 0;
                      background-color: initial;
                      color: white;
                      font-family: "苹方";
                      font-size: 15px;
                      display: flex;
                      align-items: center;
                      &.ant-tabs-tab-active {
                        background-color: #0b2e6e;
                        font-weight: 700;
                      }
                      &:hover {
                        font-weight: 700;
                      }
                    }
                  }
                }
              }
            }
            .ant-tabs-tab-arrow-show {
              color: white;
              transform: scale(1.2);
            }
          }
        }
        .ant-tabs-content {
          display: none;
        }
      }
    }
  }
  .dc-opts {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-left: auto;
    padding: 0 15px;
    .dc-search-box {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      .dc-search-input {
        margin-right: 10px;
        width: 250px;
      }
      .dc-search-btn {
        color: white;
        display: flex;
        align-items: center;
        .dc-search-btn-icon {
          display: block;
          margin-right: 5px;
        }
      }
    }
    .dc-message-box {
      margin: 0 30px 0 20px;
      .dc-badge {
        display: block;
        .dc-message-svg-box {
          width: 25px;
          height: 25px;
          border-radius: 12.5px;
          background-color: #5e94d4;
          display: flex;
          align-items: center;
          justify-content: center;
          .dc-message-svg {
            width: 22px;
            height: 22px;
            color: white;
          }
        }
        ::v-deep {
          .ant-badge-count {
            right: -1px;
            top: -3px;
            transform: scale(0.5);
          }
        }
      }
    }
    .dc-role {
      margin-right: 5px;
      color: white;
    }
    .dc-user {
      display: flex;
      align-items: center;
      margin: 0 10px;
      .dc-user-name {
        font-family: "MicrosoftYaHei", "Microsoft YaHei";
        text-align: right;
        .dc-dropdown-link {
          color: white;
          display: flex;
          align-items: center;
          .dc-dropdown-link-text {
            max-width: 55px;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            word-break: break-all;
          }
          ::v-deep {
            .anticon {
              display: block;
              margin-left: 5px;
              svg {
                transform: scale(1.2);
              }
            }
            .ant-dropdown {
              position: absolute !important;
              width: initial !important;
            }
          }
        }
      }
    }
  }
}
</style>
