<template>
  <div>
    <TraceHeader :type="'traceDynamic'" />

    <div class="form-inline">
      <div class="form-group">
        <label for="exampleInputName2">任务内容</label>
        <input
          id="exampleInputName2"
          v-model="searchText"
          type="text"
          class="form-control"
          placeholder="任务名称"
          style="width: 200px"
          @keyup.enter="query"
        />
      </div>
      <div class="form-group">
        <label for="exampleInputEmail2">项目</label>
        <div class="input-group">
          <VueSimpleSuggest
            v-model="selectedProjectName"
            :list="projects"
            :filter-by-query="true"
            :styles="suggestStyles"
            :min-length="-1"
            display-attribute="name"
            value-attribute="id"
            @suggestion-click="selectProject"
          />
        </div>
      </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>
      <button
        class="btn btn-default"
        @click="query"
      >
        查询
      </button>
    </div>

    <div class="row">
      <div class="col-sm-12">
        <div
          v-for="(items,key) in traceLogMap"
          :key="key"
        >
          <h4>{{ getDateFormat(key) }}</h4>

          <hr />

          <ul class="list-group">
            <li
              v-for="item in items"
              :key="item.id"
              class="list-group-item"
              @click="openLineTrace(item.traceId)"
            >
              <span class="badge">{{ formatDate(item.dateTime) }}</span>
              <span style="color: #000000;">{{ item.projectName }}&nbsp;</span>
              {{ item.operatorUserName }}&nbsp;
              {{ getContent(item.content) }} {{ item.traceContent }}
            </li>
          </ul>
        </div>
      </div>
      <div class="col-sm-12">
        <Pagination
          :pagination="pagination"
          :callback="getDatas"
          @click="updateRouter"
        />
      </div>
    </div>
  </div>
</template>

<script>
var Notify = require('pc-component-v3').default.Notify;
var Common = require('../common/Common.js');
var Uuid = require('pc-component-v3').default.Uuid;
import TraceCommon from './TraceCommon.js';

import TraceHeader from './TraceHeader.vue';
var Pagination = require('pc-component-v3').default.VueBootstrapPagination;;
var Navbar = require('pc-component-v3').default.Navbar;
// var VueSimpleSuggest = require('vue-simple-suggest').default;

export default {
  components: {
    Pagination, Navbar, TraceHeader, 
    // VueSimpleSuggest,
  },
  data: function () {
    return {
      searchText: '',
      selectedUserId: '',
      selectedUserName: '',
      selectedProjectId: '',
      selectedProjectName: '',
      users: [],
      projects: [],
      pagination: {
        total: 0,
        per_page: Common.pageSize,    // required
        current_page: 1, // required
        last_page: 10,    // required
      },
      traceLogMap: {},
      formatDate: TraceCommon.formatDate,
      suggestStyles: {
        'defaultInput': 'form-control',
      },
    };
  },

  watch: {
    selectedProjectName: function (newValue, oldValue) {
      if (newValue == null) {
        this.selectedProjectId = null;
      }
      if (newValue.length < oldValue.length) {
        this.selectedProjectId = null;
      }
    },

    selectedUserName: function (newValue, oldValue) {
      if (newValue == null) {
        this.selectedUserId = null;
      }
      if (newValue.length < oldValue.length) {
        this.selectedUserId = null;
      }
    },
  },

  mounted: function () {
    this.pagination.current_page = this.$route.query.currentPage;
    this.pagination.per_page = this.$route.query.pageSize;
    this.initUser();
    this.initProject();
    this.getDatas();
  },

  methods: {
    query: function () {
      this.pagination.total = 0;
      this.pagination.per_page = Common.pageSize;   // required
      this.pagination.current_page = 1; // required
      this.pagination.last_page = 10;    // required
      this.pagination.from = 1;
      this.pagination.to = 10;           // required
      this.getDatas();
    },

    updateRouter: function () {
      // var uuid = Uuid.createUUID();
      this.$router.push({
        path: '/trace/traceDynamic/',
        query: {
          currentPage: this.pagination.current_page,
          pageSize: this.pagination.per_page,
        },
      });
      console.log(this.$route);
      // console.log(this.$router.query.currentPage);
      // console.log(this.$router.query.pageSize);
      this.getDatas();
    },

    /**
         * 查询数据
         * @param {Object} success
         * @param {Object} error
         */
    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.searchText,
        projectId: _self.selectedProjectId,
        operatorUserId: _self.selectedUserId,
      };
      $.ajax({
        url: Common.getApiURL('TraceLogResource/queryByCondition'),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(queryParam),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.traceLogMap = data.map;
                   
          _self.pagination.total = data.totalSize;
          _self.pagination.last_page = Math.ceil(data.totalSize / data.range.length);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
         * 选择了项目
         */
    selectProject: function (project) {
      if (project) {
        this.selectedProjectId = project.id;
      } else {
        this.selectedProjectId = '';
      }
    },
    /**
         * 选择了用户
         */
    selectUser: function (user) {
      if (user) {
        this.selectedUserId = user.id;
      } else {
        this.selectedUserId = '';
      }
    },

    /**
         * 打开明细
         * @author GuoZhiBo 20180116
         */
    openLineTrace: function (traceId) {
      var _self = this;
      if (traceId != null && traceId != undefined) {
        this.$router.push({
          path: '/trace/trace/' + traceId,
        });
      } else {
        Notify.error('提示', '找不到这个任务了！');
      }
    },

    /**
         * 获取日期格式
         */
    getDateFormat: function (date1) {
      var _self = this;
      if (date1 == undefined && date1 == '') {
        return;
      }
      var date2 = _self.getNowFormatDate();
      if (date1 == date2) {
        return '今天';
      }
      var day = _self.dateDifference(date1, date2);
      if (day == 1) {
        return '昨天';
      }
      var month = _self.convertDateFromString(date1);
      return month;
    },

    /**
         * 获取当前日期
         */
    getNowFormatDate: function () {
      var date = new Date();
      var seperator1 = '-';
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = '0' + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },

    /**
         * 计算时间差
         * @param {Object} sDate1
         * @param {Object} sDate2
         */
    dateDifference: function (sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式  
      var dateSpan,
        tempDate,
        iDays;
      sDate1 = Date.parse(sDate1);
      sDate2 = Date.parse(sDate2);
      dateSpan = sDate2 - sDate1;
      dateSpan = Math.abs(dateSpan);
      iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
      return iDays;
    },

    /**
         * 获取日期
         * @param {Object} dateString
         */
    convertDateFromString: function (dateString) {
      if (dateString) {
        var date = new Date(dateString.replace(/-/, '/'));
        var month = date.getMonth() + 1;
        return month + '/' + date.getDate();
      }
    },

    /**
         * 初始化项目
         */
    initProject: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('ProjectItemResource/projectItem'),
        dataType: 'json',
        type: 'get',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          if (data != null) {
            data.unshift({
              name: '全部项目',
            });
            _self.projects = data;
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
         * 初始化用户
         */
    initUser: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('userResource/listByClientId'),
        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);
        },
      });
    },

    getContent: function(content){
      if(content == null){
        return '';
      }
      var result = content.replace(/<[^>]+>/g,'');
      result = result.replace(/&nbsp;/ig, '');
      return result;
    },
  },
};
</script>

<style scoped>
.mui-card {
    margin: 0px;
    margin-top: 0px;
}
.mui-card-footer:before,
.mui-card-header:after {
    background-color: #ffffff;
}
.mui-card-content {
    padding: 0px 10px;
}
.mui-card-content p {
    margin: 0px;
}
p {
    font-size: 14px !important;
    padding: 2px 0px;
    color: #000000;
}
.time {
    /*color: #8f8f94;*/
    font-weight: bold;
}
.index {
    font-size: 16px;
    font-weight: bold;
}
.div-statis {
    margin-bottom: 5px;
    font-size: 0.8em;
    text-align: center;
}
.mui-card-header {
    padding-bottom: 0px;
}
.mui-div {
    word-wrap: break-word;
    white-space: normal;
}
.mui-div1 {
    padding-left: 8%;
    color: blue;
}
.mui-div2 {
    color: cadetblue;
}

.mui-divs {
    width: 50px;
    height: 50px;
    line-height: 44px;
    text-align: center;
    border-radius: 50%;
    border: 4px solid #d2e8ea;
    float: left;
    margin-top: -3%;
}
img {
    width: 50px;
}
</style>