<template>
  <div style="display: inline-flex">
    <span class="i-layout-header-trigger i-layout-header-trigger-min i-layout-header-trigger-in">
      <Notification
        :wide="isMobile"
        :badge-props="badgeProps"
        class="i-layout-header-notice"
        :class="{ 'i-layout-header-notice-mobile': isMobile }"
        auto-count
        @on-load-more="handleLoadMore"
        @on-clear="handleClear"
      >
        <Icon slot="icon" custom="i-icon i-icon-notification" />
        <NotificationTab
          :title="$t('Front_Label_Todo')"
          name="task"
          :count="taskCount"
          :loaded-all="taskFilter.page * taskFilter.per >= taskCount"
          :loading="taskLoading"
          :scroll-to-load="false"
          :show-clear="false"
        >
          <NotificationItem
            v-for="(item, index) in taskList"
            :key="index"
            :title="item.title"
            :icon="item.icon"
            :icon-color="item.iconColor"
            :content="item.content"
            :read="item.read"
            @on-item-click="$refs.taskForm.open(item.task)"
          />
        </NotificationTab>
        <NotificationTab
          :title="$t('Front_Label_Notification')"
          name="notification"
          :count="unreadCount"
          :loaded-all="notificationFilter.page * notificationFilter.per >= notificationCount"
          :loading="notificationLoading"
          :scroll-to-load="false"
        >
          <NotificationItem
            v-for="(item, index) in notificationList"
            :key="index"
            :title="item.notification.title"
            :icon="item.icon"
            :icon-color="item.iconColor"
            :time="item.notification.sendTime"
            :read="item.notification.isRead ? 1 : 0"
            @on-item-click="openNotification(item.notification)"
          />
        </NotificationTab>
      </Notification>
    </span>
    <task-form ref="taskForm"></task-form>
    <modal-form ref="notificationForm" view-code="NotificationView" :save-enable="false"></modal-form>
  </div>
</template>
<script>
  import { mapState } from 'vuex';
  import taskApi from '../../../api/task';
  import notificationApi from '../../../api/notification';
  import mixinPage from '../../../mixins/page';
  import taskForm from '../../../pages/common/task-form';

  export default {
    name: 'iHeaderNotice',
    mixins: [mixinPage],
    components: { taskForm },
    data() {
      return {
        badgeProps: {
          offset: [20, 0]
        },
        taskList: [],
        taskLoading: false,
        taskFilter: {},
        taskCount: 0,
        notificationList: [],
        notificationLoading: false,
        notificationFilter: {},
        notificationCount: 0,
        unreadCount: 0
      };
    },
    computed: {
      ...mapState('admin/layout', ['isMobile']),
      unreadMessage() {
        let unread = 0;
        this.notificationList.forEach(item => {
          if (!item.read) unread++;
        });
        return unread;
      }
    },
    async mounted() {
      this.init();
    },
    methods: {
      // 初始化
      init() {
        this.taskList = [];
        this.taskLoading = false;
        this.taskFilter.page = 0;
        this.taskFilter.per = 5;
        this.taskFilter.orderBy = '-createTime';
        this.taskCount = 0;

        this.notificationList = [];
        this.notificationLoading = false;
        this.notificationFilter.page = 0;
        this.notificationFilter.per = 5;
        this.notificationFilter.orderBy = '-createTime';
        this.notificationCount = 0;
        this.unreadCount = 0;

        this.loadMore('notification');
        this.loadMore('task');
      },
      handleLoadMore(tab) {
        this.loadMore(tab.name);
      },
      async loadMore(type) {
        if (this[`${type}Loading`]) return;
        this[`${type}Loading`] = true;

        if (type == 'notification') {
          this.notificationFilter.page++;
          const res = await notificationApi.queryMy(this.notificationFilter);
          this.unreadCount = res.unreadCount;
          this.notificationCount = res.totalCount;

          this.notificationList = this.notificationList.concat(
            res.data.map(item => {
              let icon = '';
              let iconColor = '';
              if (item.notificationType == 'Notification') {
                icon = 'md-mail';
                iconColor = '#3391e5';
              } else if (item.notificationType == 'Notice') {
                icon = 'md-home';
                iconColor = '#87d068';
              } else if (item.notificationType == 'Alert') {
                icon = 'md-warning';
                iconColor = '#fe5c57';
              }

              return {
                icon: icon,
                iconColor: iconColor,
                notification: item
              };
            })
          );
        } else {
          this.taskFilter.page++;
          const res = await taskApi.queryMy(this.taskFilter);
          this.taskCount = res.totalCount;

          this.taskList = this.taskList.concat(
            res.data.map(item => {
              let icon = 'ios-create';
              let iconColor = '#ff9900';
              return {
                icon: icon,
                iconColor: iconColor,
                title: item.processInst.applicationType.name + ' - ' + item.activityInst.activity.name,
                content: item.processInst.title,
                read: 1,
                task: item
              };
            })
          );
        }

        this[`${type}Loading`] = false;
      },
      handleClear(tab) {
        this.clearUnread(tab.name);
      },
      clearUnread(type) {
        if (type == 'notification') {
          this.confirm('确定要清空收件箱吗？', async () => {
            await notificationApi.clear();

            this.notificationFilter.page = 1;
            this.notificationCount = 0;
            this.unreadCount = 0;
            this.notificationList = [];
            this.$forceUpdate();
          });
        }

        this[`${type}List`] = this[`${type}List`].map(item => {
          item.read = 1;
          return item;
        });
      },
      loadTask() {
        this.taskList = [];
        this.taskFilter.page = 0;
        this.loadMore('task');
      },
      openNotification(item) {
        if (!item.isRead) {
          this.unreadCount--;
          item.isRead = true;
          notificationApi.read(item.id);
        }

        this.$refs.notificationForm.open(item);
      }
    }
  };
</script>
