<template>
  <div class="menu-wrapper">
    <!-- <div class="logo">
      <img :src="logo">
    </div> -->
    <div
      v-if="!isCollapse"
      class="title">
      售检票系统
    </div>
    <template
      v-for="item in activeRoutes"
    >
      <a
        @click="openLink(item)"
        v-if="item.url"
        :key="item.name">
        <el-menu-item
          :class="{'submenu-title-noDropdown':!isNest}"
        >
          {{ item.meta.title }}
        </el-menu-item>
      </a>

      <router-link
        v-else-if="hasOneShowingChildren(item.children) && !item.children[0].children&&!item.alwaysShow && !item.url"
        :to="item.path+'/'+item.children[0].path"
        :key="item.children[0].name"
      >
        <el-menu-item
          :index="item.path+'/'+item.children[0].path"
          :class="{'submenu-title-noDropdown':!isNest}"
        >
          <i
            v-if="item.children[0].meta&&item.children[0].meta.icon"
            class="iconfont svg-icon"
            :class="`icon-${item.children[0].meta.icon}`"
          />
          <span
            v-if="item.children[0].meta&&item.children[0].meta.title"
            slot="title"
          >
            {{ item.children[0].meta.title }}
          </span>
        </el-menu-item>
      </router-link>

      <el-submenu
        v-else
        :index="item.name||item.path"
        :key="item.name+item.path"
      >
        <template slot="title">
          <i
            class="iconfont svg-icon"
            v-if="item.meta&&item.meta.icon"
            :class="`icon-${item.meta.icon}`"
          />
          <span
            v-if="item.meta&&item.meta.title"
            slot="title"
          >
            {{ item.meta.title }}
          </span>
        </template>

        <template
          v-for="child in getVisibleChildren(item.children)"
        >
          <sidebar-item
            :is-nest="true"
            class="nest-menu"
            v-if="child.children && child.children.length > 0"
            :routes="[child]"
            :key="child.path"
          />

          <router-link
            v-else
            :to="item.path+'/'+child.path"
            :key="child.name"
          >
            <el-menu-item
              :index="item.path+'/'+child.path"
              v-if="child.meta&&!child.meta.hidden">
              <i
                v-if="child.meta&&child.meta.icon"
                class="iconfont svg-icon"
                :class="`icon-${child.meta.icon}`"
              />
              <span
                v-if="child.meta&&child.meta.title"
                slot="title"
              >
                {{ child.meta.title }}
              </span>
            </el-menu-item>
          </router-link>
        </template>
      </el-submenu>
    </template>
  </div>
</template>

<script>
import { mgtlogin, otalogin, mgtlogout, otalogout } from '@/api/login'
import { getSystemConfigList } from '@/api/systemConfig'

const isDev = process.env.NODE_ENV === 'development'
export default {
  name: 'SidebarItem',
  computed: {
    activeRoutes () {
      const menus = this.routes.filter(item => {
        return !item.hidden && item.children
      })
      const roleList = this.$store.state.app.account && this.$store.state.app.account.roles
      const isSaler = roleList && roleList.some(item => item.name === '售票员')
      const newMenus = menus.concat([{
        url: isDev ? '' : '',
        meta: {
          title: '票务自营渠道销售系统'
        },
        children: [],
        type: 'mgt',
        login: mgtlogin,
        logout: mgtlogout
      }, {
        url: isDev ? '' : '',
        meta: {
          title: '票务OTA分销系统'
        },
        type: 'ota',
        children: [],
        login: otalogin,
        logout: otalogout
      }])

      return ['demo', 'mazu'].includes(this.projectName) && !isSaler ? newMenus : menus
    },
    logo () {
      return this.$store.state.app.customLogo
    }
  },
  props: {
    routes: {
      type: Array,
      default: () => { return [] }
    },
    isNest: {
      type: Boolean,
      default: false
    },
    isCollapse: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      projectName: process.env.VUE_APP_PROJECT
    }
  },
  methods: {
    hasOneShowingChildren (children) {
      const showingChildren = children.filter(item => {
        return !item.hidden
      })
      if (showingChildren.length === 1) {
        return true
      }
      return false
    },
    getVisibleChildren (data) {
      return data.filter(item => {
        return !item.hidden
      })
    },
    async openLink (item) {
      let url = item.url
      // 获取系统设置的账户密码并判断是否完整
      getSystemConfigList().then(async res => {
        let configArr = res.list.find(item => item.configKey === 'online_username_password').configValue || []
        const passwordArr = (configArr && configArr.length !== 0 && configArr.split(';')) || []
        if (!configArr || passwordArr.length < 2) {
          this.$message.error('请确认是否配置了OTA及自营系统的账号密码')
          return
        }
        const usernameMgt = passwordArr[0].split(',')[0]
        const passwordMgt = passwordArr[0].split(',')[1]
        const usernameOta = passwordArr[1].split(',')[0]
        const passwordOta = passwordArr[1].split(',')[1]

        const paramsMap = {
          mgt: {
            authcode: '',
            password: passwordMgt,
            project_name: 'YINXIANGMAZU',
            username: usernameMgt
          },
          ota: {
            authcode: '',
            password: passwordOta,
            project_name: 'YINXIANGMAZU',
            username: usernameOta
          }
        }

        const params = paramsMap[item.type]

        try {
          await item.logout()
        } catch (e) {
          console.log('%c [ e ]-203', 'font-size:13px; background:pink; color:#bf2c9f;', e)
        }
        item.login(params).then(res => {
          if (res && res.resCode === 200) {
            url += `#/loading?token=${res?.data.token}`
            const { shell } = require('electron')
            shell.openExternal(url)
            console.log('%c [ url ]-210', 'font-size:13px; background:pink; color:#bf2c9f;', url)
          }
        }).catch(e => {
          this.$message.error('请确认账号密码是否正确')
          console.log('%c [ e ]-188', 'font-size:13px; background:pink; color:#bf2c9f;', e)
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.title{
  text-align: center;
  padding: 20px 0;
  color: #333;
  font-size: 24px;
  font-weight: bold;
}
.logo{
  text-align: center;
  img{
    height: 60px;
    padding: 10px 0;
  }
  &:after{
    content: '';display: block; height: 0;border-bottom: 1px solid lighten($blue,8%);border-top: 1px solid darken($blue,8%);
  }
}
.side-icon{
  font-size: 24px; vertical-align: middle !important;
}
</style>
