<template>
  <div>
    <dm-layout is-app :first-menu-code="menu.menuCode" :class="{ 'hide-left': extraHideLeft === 'hide' || !showLeft}">
      <!-- maside插槽 替换asidemenu title -->
      <div slot="maside">
        <!-- :hide-timeout="100000" -->
        <el-dropdown class="m-title" :hide-on-click="false">
          <div class="el-dropdown-link">
            <div><p class="ellipsis">{{ currentAreaName || '未选择域' }}</p><i class="el-icon-arrow-down el-icon--right"></i></div>
          </div>
          <el-dropdown-menu slot="dropdown" class="m-title-menu">
            <el-dropdown-item v-for="(item, idx) in areaSubList" :key="`${item.areaId}-${idx}`" :class="{ checked: item.areaId === currentAreaId }">
              <dl @click="setCurrentApp(item)">
                <dd>
                  <span>{{ item.areaName }}</span>
                  <el-tag v-if="item.deleteFlag" effect="plain" class="ml5" type="info">已删除</el-tag>
                </dd>
              </dl>
              <i class="el-icon-check select-icon"></i>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <aside-menu ref="asideMenu" />
      </div>
      <!-- bread插槽 -->
      <div slot="bread">
        <app-info force-init ref="appInfo" />
      </div>
    </dm-layout>
    <el-dialog :visible="noAreaWarnVisible" append-to-body width="500px" :close-on-press-escape="false" :close-on-click-modal="true" :show-close="false"  lock-scroll>
      <div class="text-center">
        <p class="gray02 fz16" style="display:flex;justify-content: center;align-items: center;"><i class="el-icon-warning fz30 mr5 warning-color"></i>暂无资源权限</p>
        <p class="fz13 gray03 mt20">没有资源权限，如：可操作的会员卡、服务号等，请联系管理员进行配置</p>
      </div>
      <span slot="footer">
        <div class="text-center pb20">
          <el-button @click="toAppCenter"> 返回应用中心</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import commonApi from '@/api/common.js';
const menuList = {};
import { reRreshRoute, formatDateTimeByType } from '@/utils/index';
import { dealMkStorage } from '@/utils/common';
import asideMenu from './aside-menu.vue';
const { getAppInfo, loginUserMenuOfApp, getSubappList }  = commonApi;


export default {
  name: 'Layout',
  components: {
    asideMenu
  },
  data() {
    return {
      manageAppDialogVisible: false, // 管理子应用dialog
      chooseAppDialogVisible: false, // 选择默认子应用
      addSubResVisible: false, // 子应用结果dialog
      showLeft: true, // 根据config/index显示left 即使后端配置了菜单也去掉边距
      noAreaWarnVisible: false, // 没有域list警告(子应用列表请求后为空显示)
    };
  },
  mounted() {
    if(this.$route.name != 'compile') {
      this.init();
    }
  },
  methods: {
    toAppCenter() {
      window.location.href = '/app-center/applyIndex';
    },
    formatDateTimeByType,
    // 设置当前子应用、设置默认
    // handleChoose({ areaId, isDefault }) {
    //   this.$store.commit('setCurrentSubApp', areaId);
    //   if (isDefault) {
    //     this.setDefaultApp({ areaId });
    //   }
    // },
    // 处理提交创建子应用的回调
    handleSubApp({ type, areaId, reason }) {
      this.addSubResVisible = true;
      this.$refs.addSubRes.setData({ type, areaId, reason });
    },
    // 添加子应用
    addSubApp() {
      this.subAppDialogVisible = true;
    },
    // 设置当前子应用
    setCurrentApp({ areaId }) {
      // 【ID1024023】 产品需求：应用右上角切换服务号或会员卡后跳转至当前应用的首页，不再停留在当前页面
      this.$router.push('/' + this.$route.path.split('/')[1]);
      // if (this.$route.meta.type && this.$route.meta.type !== 'add') {
      //   this.$tips({ message: '当前页不可切换状态', type: 'warning' });
      //   return;
      // }
      this.$store.commit('setCurrentSubApp', areaId);
    },
    // 设置默认子应用
    // setDefaultApp({ areaId }) {
    //   this.$store.commit('setDefaultSubAppId', areaId);
    // },
    async init() {
      this.manageAppDialogVisible = false;
      this.chooseAppDialogVisible = false;
      this.addSubResVisible = false;
      const current = menuList[this.project];
      // this.showLeft = menuList[this.project].showLeft;
      const moduleCode = this.$store.getters.moduleCode;
      if(!current) {
        // 没有有对应的子应用 -- 没有此场景
        return;
      }
      let appInfo = {};
      try {
        appInfo = await getAppInfo({ appCode: moduleCode });
        this.$refs.appInfo.dealRes(appInfo);
      } catch (error) {
        this.$store.commit('updateLock', true);
        return;
      }
      this.$store.commit('updateAppInfo', appInfo.result); // 设置应用信息
      document.title = appInfo.result.appName; // 设置页面的title layout里有设置，这里就不设置了
      const { serveStatus, limitFlag } = appInfo.result;
      if(serveStatus === 1 ||  serveStatus === 2 && limitFlag == 1) {
        // serveStatus 0正常 1未购买 2已过期   limitFlag 过期后1限制0不限制
        // 未购买 || 过期限制  更新lock禁止一切操作
        this.$store.commit('updateLock', true);
        return;
      } else {
        this.$store.commit('updateLock', false);
      }
      if(this.showLeft) {
        // 获取左侧菜单
        const aside = await loginUserMenuOfApp({ menuCode: this.$store.state.menu.menuCode });
        this.$refs.asideMenu.getMenu(aside.result);
      }

      if (current.showLeft) {
        // 获取子应用列表
        const subApp = await getSubappList({}, { moduleCode });
        this.$store.commit('setSubAppList', subApp.result.result || []);
        if(this.areaSubList.length) {
          try {
            const areaId = this.$route.query.areaId || ''; // url中代入的aredId
            if(areaId && this.areaSubList.map(v => v.areaId).includes(areaId)) {
              // url存在且在list中存在  设置为url中指定的数据
              this.$store.commit('setCurrentSubApp', areaId); // 设置当前子应用id
              return;
            }
            const mCodeValue = dealMkStorage(moduleCode);
            // console.log(mCodeValue);
            // console.log(this.areaSubList.map(v => v.areaId));
            if(mCodeValue && this.areaSubList.some(v => v.areaId == mCodeValue)) {
              // 存在 且在当前子应用list里（防止切换账号）
              this.$store.commit('setCurrentSubApp', mCodeValue); // 设置当前子应用id
            } else {
              // 不存在
              this.$store.commit('setCurrentSubApp', this.areaSubList[0].areaId); // 设置当前子应用id
            }
          } catch (error) {
            this.$store.commit('setCurrentSubApp', this.areaSubList[0].areaId); // 设置当前子应用id
          }
        } else {
          this.noAreaWarnVisible = true;
        }
      }

    }
  },
  computed: {
    ...mapState([
      'default_areaId',
      'currentAreaName',
      'currentAreaId',
      'areaSubList',
      'project',
      'menu',
      'extraHideLeft',
      'appInfo',
      'lock'
    ]),
    cConfig() {
      return menuList[this.$store.state.project];
    }
  },
  watch: {
    currentAreaId(newv, oldV) {
      // 有左侧的根据监听currentAreaId的变化
      reRreshRoute();
    },
    lock(val) {
      // 没有左侧的根据监听lock的变化
      if(!this.showLeft) {
        reRreshRoute();
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.simu-el-item {
  margin-top: 6px;
  padding-left: 20px;
  cursor: pointer;
  color: #909399;
  font-size: 13px;
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid #e4e7ed;
}
.tips {
  div {
    height: 22px;
    font-size: 13px;
    color: rgba(255, 255, 255, 1);
    line-height: 22px;
    &.lighter {
      opacity: 0.8;
    }
  }
}
.m-title {
  display: block;
  // height: 50px;
  line-height: 50px;
  .el-dropdown-link {
    display: block;
    height: 22px;
    font-size: 16px;
    font-weight: 500;
    color: rgba(48, 49, 51, 1);
    line-height: 22px;
    margin: 14px 20px;
    > div {
      max-width: 100%;
      display: inline-block;
      position: relative;
      p {
        padding-right: 10px;
      }
      i {
        position: absolute;
        right: -8px;
        top: 5px;
      }
    }
  }
}
.m-title-menu {
  left: 22px !important;
  // width: 240px;
  // max-height: 400px;
  // overflow-y: auto;
  /deep/ {
    .el-dropdown-menu__item {
      position: relative;
      padding-right: 50px;
      &.checked {
        color: $blue;
        background-color: #ecf5ff;
      }
    }
    .popper__arrow {
      left: 36px !important;
    }
  }
  dl {
    padding: 10px 0 10px;
    dd {
      height: 14px;
      font-size: 14px;
      font-weight: 500;
      line-height: 14px;
      color: $gray02;
      display: flex;
      align-items: center;
    }
    dt {
      line-height: 17px;
      margin-top: 6px;
      /deep/ label {
        height: 17px;
        font-size: 12px;
        font-weight: 400;
        color: $gray03;
        line-height: 17px;
      }
    }
  }
  .checked .select-icon {
    display: block;
  }
  .select-icon {
    position: absolute;
    right: 10px;
    top: 30%;
    font-size: 14px;
    display: none;
    color: $blue;
  }
  /deep/ .exp.el-dropdown-menu__item--divided {
    height: 40px;
    line-height: 34px;
  }
  .exp {
    color: $gray02 !important;
    height: 34px;
    line-height: 34px;
    &:hover {
      background: $gray-disable;
    }
  }
}
// .mybread {
//   // overflow: hidden;
//   height: 14px;
//   display: flex;
//   align-items: center;
//   .tags {
//     border-radius: 13px;
//     padding: 0 13px;
//   }
//   /deep/ .el-divider--vertical {
//     margin: 0 10px;
//   }
// }
.layout.hide-left {
  padding-left: 0 !important;
  /deep/ {
    .dm-aside-menu {
      display: none;
    }
    .dm-bread {
      padding-left: 20px !important
    }
  }
}
.lock-block {
  text-align: center;
  span.png {
    width:42px;
    height: 42px;
    background: url('../../assets/images/yqts.png') center center;
    display: inline-block;
  }
}
// .temp {
//   .temp-div {
//     position: fixed;
//     left: 20px;
//     top: 110px;
//     z-index: 4;
//     &.hide-left {
//       display: none;
//     }
//   }
//   .layout:not(.hide-left) {
//     padding-left: 200px !important;
//   }
// }
</style>
