<template>
  <div>
    <div class="flex-container">
      <div class="flex-header">
        <Navbar
          title="消息"
          :is-go-back="true"
        />
        <div class="form-inline">
          <div class="form-group">
            <label>过滤条件</label>
            <input
              v-model="condition"
              autocomplete="off"
              class="form-control"
              placeholder="过滤条件"
              aria-describedby="basic-addon1"
              @keyup.enter="getDatas"
            />
          </div>
          <div class="form-group">
            <label for="exampleInputEmail2">选择用户组</label>
            <div class="input-group">
              <VueSimpleSuggest
                v-model="selectedUserName"
                :list="users"
                :filter-by-query="true"
                :styles="suggestStyles"
                :min-length="-1"
                display-attribute="name"
                value-attribute="id"
                @suggestion-click="selectUser"
              />
            </div>
          </div>
          <div class="form-group">
            <button
              type="button"
              class="btn btn-primary"
              @click="getDatas"
            >
              查询
            </button>
            <button
              type="button"
              class="btn btn-success"
              @click="signAllRead"
            >
              全部标记为已读
            </button>
          </div>
        </div>
      </div>
      <div class="flex-content">
        <!--<div class="notification"
                     v-for="item in messages"
                     @click="showSingleMessage(item)">
                    <div class="time">
                        {{item.timeInterval}}
                        <div class="float-right">
                            {{item.type}}
                        </div>
                    </div>
                    <div>
                        {{item.message}}
                    </div>
                </div>-->
        <ul class="list-group">
          <template v-for="item in messages" :key="item.id">
            <li class="list-group-item" @click="showSingleMessage(item)">
              <span class="badge">{{ item.timeInterval }}</span>
              {{ item.message }}
            </li>
          </template>
        </ul>
      </div>
      <div class=" flex-footer">
        <div class="pull-left">
          <span>第{{ (pagination.current_page-1)*pagination.per_page+1 }}-{{ pagination.current_page*pagination.per_page }}条,共计{{ pagination.total }}条,每页显示</span>
          <PageSizeSelect @page-size-changed="gridSizeSelect" />
          <span>条</span>
        </div>
        <div class="pull-right">
          <VueBootstrapPagination
            v-if="pagination.last_page > 0"
            :pagination="pagination"
            :callback="getDatas"
          />
        </div>
      </div>
    </div>
    <div>
      <Loading v-if="loading" />
    </div>
  </div>
</template>

<script>
import Common from '../common/Common.js';
import { Notify, Uuid } from 'pc-component-v3';
// import VueSimpleSuggest from 'vue-simple-suggest';





export default {
  components: {
  },
  data: function () {
    return {
      'loginInfo': '',
      'messages': [],
      users: [],
      userId: undefined,
      selectedUserName: '',
      condition: '',
      selectedUserId: undefined,
      pagination: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        last_page: 0, // required
      },
      suggestStyles: {
        'defaultInput': 'form-control',
      },
      loading: false,
    };
  },
  mounted: function () {
    this.getLocalStorage();
    this.initUser();
  },
  methods: {
    // 获取localStorage
    getLocalStorage: function () {
      var storage = localStorage;
      if (!storage) {
        alert('浏览器不支持localstorage');
      } else {
        var json = storage.getItem('#LoginInfo');
        this.loginInfo = JSON.parse(json);
        this.userId = this.loginInfo.userId;
        this.getDatas();
      }
    },

    /**
         * 修改每页显示的数量
         * @param {Object} newPageSize
         */
    gridSizeSelect: function (newPageSize) {
      this.pagination.per_page = newPageSize;
      this.page = newPageSize;
      this.pagination.current_page = 1;
      // 刷新界面
      this.getDatas();
    },

    /**
         * 选择了用户
         */
    selectUser: function (user) {
      if (user) {
        this.selectedUserId = user.id;
      } else {
        this.selectedUserId = null;
      }
    },


    getDatas: function () {
      var _self = this;
      var queryParam = {
        range: {
          start: (_self.pagination.current_page - 1) * _self.pagination.per_page,
          length: _self.pagination.per_page,
        },
        condition: _self.condition,
        userId: _self.userId,
        id: _self.selectedUserId,
      };
      _self.loading=true;
      $.ajax({
        url: Common.getApiURL('messageQueueResource/queryByCondition'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(queryParam),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading=false;
          if(data.errorCode != 0){
            Notify.error(_self.$t('lang.Notify.prompt'), data.errorMessage, false);
            return;
          }
          _self.showMessage(data.datas);
          _self.pagination.total = data.total;
          _self.pagination.last_page = Math.ceil(data.total / queryParam.range.length);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    // 渲染消息
    showMessage: function (data) {
      var _self = this;
      // 清空数据
      _self.messages.splice(0, _self.messages.length);
      if (data == undefined || data.length == 0) {
        return;
      }

      for (var i = 0, len = data.length; i < len; i++) {
        _self.messages.push(data[i]);
      }
    },
    /**
             * 阅读某条消息
             * @param  {Object} item 
             * @return {void}      
             */
    showSingleMessage: function (item) {
      var _self = this;
      _self.$router.push('/desktop/single-notification/' + item.id);
    },

    /**
         * 全部标记为已读
         */
    signAllRead: function () {
      var _self = this;
      _self.loading=true;
      $.ajax({
        url: Common.getApiURL('messageQueueResource/signAllRead'),
        type: 'get',
        dataType: 'json',
        data: {
          userId: _self.loginInfo.userId,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if(data.errorCode != 0){
            Notify.error(_self.$t('lang.Notify.prompt'), data.errorMessage, false);
            return;
          }
          _self.loading=false;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 初始化用户
     */
    initUser: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('groupResource/getGroupByClient'),
        dataType: 'json',
        type: 'get',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if (data != null) {
            data.unshift({
              name: '所有包含我的用户组',
            });
            _self.users = data;
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
  },
};
</script>

<style>
.notification-page {
    background-color: white;
    border: 1px solid #f1f1f1;
    border-radius: 5px;
    padding: 10px 15px;
}
.notification {
    border-bottom: 1px solid #eee;
    cursor: pointer;
    padding: 5px 10px;
}
.notification:hover {
    background-color: #f7f7f7;
}

.notification-inner {
    list-style: none;
    padding-left: 10px;
}
.image {
    width: 50px;
    height: 50px;
    border-radius: 50%;
}
.title {
    height: 50px;
    line-height: 50px;
    font-size: 22px;
    font-weight: block;
    padding-left: 15px;
    border-bottom: 1px solid #eee;
}
.time {
    color: #999;
    padding-left: 5px;
}
.float-right {
    float: right;
}
</style>

<style scoped>
.form-inline .form-group label {
    width: 80px;
    text-align: right;
    padding-right: 5px;
}

.form-inline .form-group input,
.form-inline .form-group select {
    width: 200px;
}
</style>

<style scoped>
.flex-container {
    display: flex;
    /* 垂直*/
    flex-direction: column;
    width: 100%;
    /*视口被均分为100单位的vh 占据整个窗口，扣掉顶部topNav的距离后，计算得到container的高度*/
    height: calc(100vh - 85px);
}

.flex-header {
    height: 200px;
    /*放大缩小比例为0 */
    flex: 0 0 100px;
}

.flex-footer {
    margin-top: 0.8em;
    height: 35px;
    /*放大缩小比例为0 */
    flex: 0 0 35px;
}

.flex-content {
    margin-top: 0.8em;
    flex: 1;
    overflow: scroll;
    width: 100%;
    height: 0;
}
</style>