<template>
  <ul class="es-handler">
    <template v-for="(item, index) in lists">
      <li v-if="!item.hide" :key="index" class="es-handler-item">
        <es-handle-user
          v-if="item.type === 'user'"
          class="es-handler-user"
          :data="item"
          :userModel="userModel"
          :job-scrollbar="jobScrollbar"
          @visible-change="handleVisibleChange"
          @click="handleClick"
          @change="handleChange"
        ></es-handle-user>
        <div
          v-else-if="item.type == 'contact'"
          class="es-handler-contact"
          :key="item.type"
        >
          <div class="es-contact-label">{{ item.label }}</div>
          <div class="es-contact-content">
            <div v-for="ele in item.content" :key="ele">{{ ele }}</div>
          </div>
        </div>
        <div v-else-if="item.type === 'dateTime'" class="es-handler-date">
          <div>
            {{ time }}
            <span v-if="show"
              >当前<span
                class="es-online-num"
                :class="{ 'es-pointer': onlineList }"
                @click.stop="onlineList ? handleClick({ type: 'online' }) : ''"
                >{{ online }}</span
              >人在线</span
            >
          </div>
          <div>今 天：{{ date }}</div>
        </div>
        <el-popover
          v-else-if="item.type === 'system'"
          placement="bottom"
          trigger="hover"
          ref="system"
          :popper-class="
            systemData.length > 4
              ? 'es-popper-sub-system is-width'
              : 'es-popper-sub-system'
          "
          @show="showPopper = true"
          @hide="showPopper = false"
        >
          <el-scrollbar :max-height="maxHeight" v-if="systemData.length">
            <ul class="es-sub-system">
              <li
                v-for="ele in systemData"
                class="es-sub-system-item"
                :class="{
                  'es-disabled':
                    (application && !ele.hasPermission) ||
                    (ele.extendData && ele.extendData.businessStatus == 0)
                }"
                :key="ele.id"
                :title="ele.text"
                @click.stop="handleSelect({ node: ele, ...item })"
              >
                <el-badge
                  :is-dot="typeof ele.tips === 'boolean'"
                  :hidden="!ele.tips"
                  :max="99"
                  :value="typeof ele.tips !== 'boolean' ? ele.tips : 0"
                >
                  <es-icon
                    class="es-sub-system-icon"
                    :contents="ele.icons || 'es-icon-yingyong'"
                  ></es-icon>
                </el-badge>
                <div class="es-sub-system-title">{{ ele.text }}</div>
              </li>
            </ul>
          </el-scrollbar>
          <div
            slot="reference"
            class="es-handler-icon"
            :title="item.title"
            :class="item.icon"
          ></div>
        </el-popover>
        <el-tooltip
          v-else
          :key="item.type"
          effect="dark"
          :content="item.title"
          placement="bottom"
        >
          <el-badge
            class="es-badge"
            v-if="item.type === 'notice'"
            :value="noticeNum"
            :max="99"
            :hidden="noticeNum < 1"
          >
            <es-icon
              class="es-handler-icon"
              @click.stop="handleClick(item)"
              :contents="item.icon"
            ></es-icon>
          </el-badge>
          <es-icon
            v-else
            class="es-handler-icon"
            @click.stop="handleClick(item)"
            :contents="item.icon"
          ></es-icon>
        </el-tooltip>
      </li>
    </template>
  </ul>
</template>
<script>
import { logout } from 'eoss-ui/src/config/api.js';
import util from 'eoss-ui/src/utils/util';
export default {
  name: 'EsHandler',
  inheritAttrs: false,
  inject: {
    onQuit: {
      default: ''
    }
  },
  props: {
    contact: Object,
    jobScrollbar: Boolean,
    data: Array,
    color: {
      type: String,
      default: '#333333'
    },
    userModel: Object,
    subSystem: {
      type: Array,
      default() {
        return [];
      }
    },
    hide: {
      type: Object,
      default() {
        return {};
      }
    },
    photo: String,
    storage: String,
    application: {
      type: Boolean,
      default: false
    },
    maxHeight: {
      type: String,
      default: '100%'
    },
    user: {
      type: Object,
      default() {
        return {
          type: 'user'
        };
      }
    },
    dateTime: {
      type: Object,
      default() {
        return {
          type: 'dateTime'
        };
      }
    },
    system: {
      type: Object,
      default() {
        return {
          type: 'system',
          icon: 'es-icon-yingyong',
          title: '切换子系统'
        };
      }
    },
    home: {
      type: Object,
      default() {
        return {
          type: 'home',
          icon: 'es-icon-zuomian',
          title: '个人工作台'
        };
      }
    },
    search: {
      type: Object,
      default() {
        return {
          type: 'search',
          icon: 'es-icon-sousuo',
          title: '搜索'
        };
      }
    },
    im: {
      type: Object,
      default() {
        return {
          type: 'im',
          icon: 'es-icon-message',
          title: 'IM'
        };
      }
    },
    index: {
      type: Object,
      default() {
        return {
          type: 'index',
          icon: 'es-icon-home',
          title: '门户'
        };
      }
    },
    home: {
      type: Object,
      default() {
        return {
          type: 'home',
          icon: 'es-icon-zhuye',
          title: '个人工作台'
        };
      }
    },
    notice: {
      type: Object,
      default() {
        return {
          type: 'notice',
          icon: 'es-icon-xiaoxi1',
          title: '通知消息'
        };
      }
    },
    refresh: {
      type: Object,
      default() {
        return {
          type: 'refresh',
          icon: 'es-icon-shuaxin',
          title: '刷新'
        };
      }
    },
    quit: {
      type: Object,
      default() {
        return {
          type: 'quit',
          icon: 'es-icon-tuichu1',
          title: '退出'
        };
      }
    },
    set: {
      type: Object,
      default() {
        return {
          type: 'set',
          icon: 'es-icon-shezhi',
          title: '设置'
        };
      }
    },
    msgNum: {
      type: Number,
      default: 0
    },
    noticeNum: {
      type: Number,
      default: 0
    },
    online: {
      type: Number,
      default: 1
    },
    singleLogout: Array
  },
  watch: {
    subSystem: {
      handler(val) {
        if (this.showPopper) {
          this.$refs.system[0].doClose();
          this.$nextTick(this.$refs.system[0].doShow);
        }
      }
    }
  },
  computed: {
    lists() {
      let hide = {
        system: true,
        new: true,
        //im: true,
        ...this.hide
      };
      let data = this.data
        ? this.data
        : [
            this.user,
            this.contact ? { ...this.contact, type: 'contact' } : {},
            this.dateTime,
            this.system,
            this.search,
            this.im,
            this.index,
            this.home,
            this.notice,
            this.refresh,
            this.quit,
            this.set
          ];
      return data.filter((item) => {
        return (
          item && Object.keys(item).length && !item.hide && !hide[item.type]
        );
      });
    },
    systemData() {
      return this.subSystem;
    },
    show() {
      if (this.online === false) {
        return false;
      }
      return true;
    },
    onlineList() {
      return (
        this.useCaseCodes && this.useCaseCodes.includes('sys_user_onlineList')
      );
    }
  },
  data() {
    return {
      date: '',
      time: '',
      showPopper: false,
      useCaseCodes: util.getStorage('useCaseCodes')
    };
  },
  created() {
    this.time = util.timeCycle() + '好!';
    this.date = util.formatDate('', 'yyyy 年 M 月 d 日 ');
  },
  methods: {
    unicode(res) {
      if (!res) {
        return false;
      }
      var reg = new RegExp(/^es-\S+/, 'g');
      let len = res.match(reg) ? res.match(reg).length : 0;
      return len;
    },
    handleClick(res) {
      const { type, event } = res;
      if (event) {
        event();
      } else {
        switch (type) {
          case 'quit':
            this.handleQuit();
            break;
        }
        this.$emit('click', res);
      }
    },
    handleChange(item) {
      this.$emit('change', item);
    },
    handleSelect(res) {
      const { node } = res;
      this.$emit('click', res);
      if (node.extendData && node.extendData.businessStatus == 0) {
        this.$alert(
          node.extendData.businessWarnMsg
            ? node.extendData.businessWarnMsg
            : '此模块还在开发中',
          '提示',
          {
            type: 'warning'
          }
        );
      } else if (!this.application && !node.hasPermission) {
        this.$emit('select', res);
      }
    },
    handleQuit() {
      this.$confirm('确定退出吗?', '退出系统', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let iframes = document.getElementsByTagName('iframe');
          for (let i = 0; i < iframes.length; i++) {
            let src = iframes[i] ? iframes[i].src : null;
            let origin = util.win.location.origin;
            if (
              src &&
              util.startWith(src, 'http') &&
              src.indexOf(origin) === -1
            ) {
              iframes[i] && iframes[i].contentWindow.postMessage('logout', '*');
            }
          }
          if (this.singleLogout) {
            for (let i = 0; i < this.singleLogout.length; i++) {
              let iframe = document.createElement('iframe');
              iframe.style.display = 'none';
              iframe.src = this.singleLogout[i];
              document.body.appendChild(iframe);
            }
          }
          util
            .ajax({ method: 'post', url: logout })
            .then((res) => {
              if (res.rCode == 0) {
                util.removeStorage([
                  'Authorization',
                  'token',
                  'ssId',
                  'userId',
                  'userName',
                  'auth',
                  'deviceUnique',
                  'menus',
                  'useCaseCodes',
                  'mainConfig',
                  'jump'
                ]);
                if (this.onQuit && typeof this.onQuit === 'function') {
                  this.onQuit();
                } else {
                  try {
                    const loginPage =
                      util.getStorage('login') || util.getStorage('loginPage');
                    if (loginPage) {
                      let src;
                      if (!util.startWith(loginPage, ['http', '/'], true)) {
                        let pathname = util.getWinTop().location.pathname;
                        if (pathname !== '/') {
                          pathname = pathname.split('/');
                          pathname.splice(pathname.length - 1);
                          pathname = pathname.join('/');
                          src = pathname + '/' + loginPage.replace('./', '');
                        } else {
                          src = pathname + loginPage.replace('./', '');
                        }
                      } else {
                        src = loginPage;
                      }
                      util.getWinTop().location.href = src;
                    } else if (
                      util.getWinTop().location.href.indexOf('main.html') > -1
                    ) {
                      util.getWinTop().location.href = './login.html';
                    } else {
                      const hash = util.getWinTop().location.hash;
                      if (hash) {
                        const len = util
                          .getWinTop()
                          .location.href.indexOf(hash);
                        util.getWinTop().location.href =
                          util.win.location.href.slice(0, len) + '#/login';
                      } else {
                        util.getWinTop().location.href = '/login.html';
                      }
                    }
                  } catch (error) {}
                }
              }
            })
            .catch((err) => {
              if (err.message && err.message !== 'canceled') {
                this.$message.error(err.message);
              }
            });
        })
        .catch((e) => {});
    },
    handleVisibleChange(res) {
      this.$emit('visible-change', res);
    }
  }
};
</script>
