<template>
  <div>
    <Navbar :title="projectName" :is-go-back="true">
      <button v-if="adminUserShow" type="button" class="btn btn-link" style="padding: 5px;" @click="goAdminPersonList()">
        编辑项目管理员({{ projectAdminUsers.length }})
      </button>
      <button v-if="userShow" type="button" class="btn btn-link" style="padding: 5px;" @click="goPersonList()">
        编辑项目人员({{ projectUsers.length }})
      </button>
    </Navbar>

    <h4>
      未完成的任务({{ pagination.total }})
      <div class="pull-right">
        <button v-if="timeShow" class="btn btn-link" style="padding: 0px;" @click="projectManagement(projectId)">项目任务</button>
        <button class="btn btn-link" style="padding: 0px;" @click="projectArchive(projectId)">项目归档</button>
        <button class="btn btn-link" style="padding: 0px;" @click="addTrace(projectId)">添加任务</button>
      </div>
    </h4>
    <div class="m-container">
      <div class="input-group">
        <input autocomplete="off" v-model="content" type="text" class="form-control" placeholder="任务名称、任务内容" @blur="listNotFinishedTask" @keyup.enter="listNotFinishedTask" />
        <span class="input-group-btn">
          <button style="width:100%;background-color: #007aff;color: white;" type="button" class="btn btn-blue search-button" @click="listNotFinishedTask()">
            查询
          </button>
        </span>
      </div>
    </div>
    <div class="panel panel-default" style="margin-bottom: 10px;margin-top: 10px;">
      <div class="panel-body">
        <vuedraggable v-model="noFinishedTraces" item-key="id" class="wrapper" :delay="500" :delay-on-touch-only="true" @change="end">
          <template #item="{element}">
            <div style="margin-top: 5px; cursor: pointer;">
              <span>
                <span>
                  <Checkbox
                    :id="'trace-finish-' + element.id" v-model="element.finished" class-name="terms" class="trace-checkbox"
                    @input="updateTracefinished(element)"
                  />
                </span>
                <span @click="openLine(element)">
                  <!-- eslint-disable-next-line -->
                    <span class="trace-summary" :class="{'font-color': element.timeLineCompletion==true}" v-html="element.summary" />
                  <span class="glyphicon glyphicon-option-vertical trace-icon" aria-hidden="true" />
                  <span class="label trace-user" :class="{'label-danger' : element.overdue == true, 'label-primary' : element.overdue != true}">
                    <!-- eslint-disable-next-line -->
                      <span v-html="element.receiveUserName" />&nbsp;
                    <span>{{ formatDate(element.planFinishedDate) }}</span>
                  </span>
                </span>
              </span>
              <a class="fa-pull-right" style="color: blue;" @click="edit(element)">编辑</a>
            </div>
          </template>
        </vuedraggable>
      </div>
    </div>
    <div v-if="noFinishedTraces.length" class="row" style="margin-left:0px; margin-right: 0px;">
      <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">
        <Pagination :pagination="pagination" :callback="listNotFinishedTask" @click="updateRouter" />
      </div>
    </div>
    <!-- <Pagination :pagination="pagination" :callback="listNotFinishedTask"  v-if="noFinishedTraces.length"></Pagination> -->
    <hr />

    <button type="button" class="btn btn-link" style="color:green" @click="openFinishedProjectTraces">
      查看已完成的任务
    </button>
  </div>
</template>

<script>
var Common = require('../common/Common.js');
var Uuid = require('pc-component-v3').default.Uuid;
import TraceCommon from './TraceCommon.js';
import TraceResource from './TraceResource.js';
var Navbar = require('pc-component-v3').default.Navbar;
var Pagination = require('pc-component-v3').default.VueBootstrapPagination;;
var PageSizeSelect = require('pc-component-v3').default.PageSizeSelect;
var Checkbox = require('pc-component-v3').default.Checkbox;
import vuedraggable from 'vuedraggable';

export default {
  components: {
    Navbar,
    Pagination,
    Checkbox,
    vuedraggable,
    PageSizeSelect,
  },
  data: function() {
    return {
      finishedTraces: [], //已完成的任务
      projectUsers: [],
      projectAdminUsers: [],
      projectName: '',
      projectId: '',
      noFinishedTraces: [], //未完成的任务
      pagination: {
        total: 0,
        per_page: 50, // 每页50条信息
        current_page: 1, // 当前页码
        last_page: 10, // 最后页码
      },
      formatDate: TraceCommon.formatDate,
      adminUserShow: false,
      userShow: false,
      timeShow: false,
      content: undefined,
    };
  },

  mounted: function() {
    var _self = this;
    this.projectId = _self.$route.params.projectId;
    this.projectName = _self.$route.query.projectName;
    this.pagination.current_page = this.$route.query.currentPage;
    this.pagination.per_page = this.$route.query.pageSize;
    this.personNumber();
    this.adminPersonNumber();
    this.listNotFinishedTask();
    this.personnelJurisdictionSet();
  },
  methods: {
    gridSizeSelect: function(newPageSize) {
      this.pagination.per_page = newPageSize;
      this.pagination.current_page = 1;
      // 刷新界面
      this.updateRouter();
    },
    end(evt) {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('TraceResource/sortNotFinished'),
        type: 'get',
        dataType: 'json',
        contentType: 'application/json',
        data: {
          'id': evt.moved.element.id,
          'projectId': _self.projectId,
          'oldIndex': evt.moved.oldIndex,
          'newIndex': evt.moved.newIndex,
          'currentPage': _self.pagination.current_page,
          'pageSize': _self.pagination.per_page,
          'content': _self.content,
        },
        beforeSend: function(request) {
          Common.addTokenToRequest(request);
        },
        success: function(data) {
          _self.listNotFinishedTask();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    /**
			 * 编辑
			 */
    edit: function(trace) {
      var _self = this;
      this.$router.push('/trace/traceUpdate/' + trace.id);
    },

    updateRouter: function () {
      this.$router.push({
        path: '/trace/notFinishedProjectTraces/' + this.projectId,
        query: {
          projectName: this.projectName,
          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.listNotFinishedTask();
    },

    /**
			 * 打开已完成的项目任务
			 */
    openFinishedProjectTraces: function() {
      var _self = this;
      this.$router.push({
        path: '/trace/finishedProjectTraces/' + _self.projectId,
        query: {
          projectName: _self.projectName,
          currentPage: 1,
          pageSize: 10,
        },
      });
      
    },

    listNotFinishedTask: function() {
      var _self = this;
      _self.noFinishedTraces.splice(0, _self.noFinishedTraces.length);
      $.ajax({
        url: Common.getApiURL('TraceResource/listNotFinishedByProjectId'),
        type: 'get',
        dataType: 'json',
        contentType: 'application/json',
        data: {
          'projectId': _self.projectId,
          'currentPage': _self.pagination.current_page,
          'pageSize': _self.pagination.per_page,
          'content': _self.content,
        },
        beforeSend: function(request) {
          Common.addTokenToRequest(request);
        },
        success: function(data) {
          if(data == null) {
            return;
          }
          _self.pagination.total = data.totalSize;
          _self.pagination.last_page = Math.ceil(_self.pagination.total / _self.pagination.per_page);
          _self.noFinishedTraces = data.traceDtos;
          console.log(_self.noFinishedTraces);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    //查询登录用户权限
    personnelJurisdictionSet: function() {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('TraceResource/queryPersonnelJurisdiction'),
        type: 'get',
        dataType: 'json',
        contentType: 'application/json',
        data: {
          'projectId': _self.projectId,
        },
        beforeSend: function(request) {
          Common.addTokenToRequest(request);
        },
        success: function(data) {
          if(data == null) {
            return;
          }
          if(data.levelOfPerson == 1) {
            _self.timeShow = true;
            return;
          }
          if(data.levelOfPerson == 2) {
            _self.timeShow = true,
            _self.adminUserShow = false,
            _self.userShow = true;
          }
          if(data.levelOfPerson == 3) {
            _self.timeShow = true,
            _self.adminUserShow = true,
            _self.userShow = true;
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
			 * 初始化接收该项目的人数
			 * @author ZhangTeng 20190212
			 */
    personNumber: function() {
      var _self = this;
      _self.projectUsers.splice(0, _self.projectUsers.length);

      $.ajax({
        url: Common.getApiURL('TraceResource/listByProjectId'),
        type: 'get',
        dataType: 'json',
        contentType: 'application/json',
        data: {
          'projectId': _self.projectId,
        },
        beforeSend: function(request) {
          Common.addTokenToRequest(request);
        },
        success: function(data) {
          if(data == null) {
            return;
          }
          console.log(data);
          for(var index = 0; index < data.length; index++) {
            _self.projectUsers[index] = data[index];
            // _self.$set(_self.projectUsers, index, data[index]);
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
			 * 初始化接收该项目的管理员人数
			 * @author TangWenXiang 20191009
			 */
    adminPersonNumber: function() {
      var _self = this;
      _self.projectAdminUsers.splice(0, _self.projectUsers.length);

      $.ajax({
        url: Common.getApiURL('TraceResource/listAdminByProjectId'),
        type: 'get',
        dataType: 'json',
        contentType: 'application/json',
        data: {
          'projectId': _self.projectId,
        },
        beforeSend: function(request) {
          Common.addTokenToRequest(request);
        },
        success: function(data) {
          if(data == null) {
            return;
          }
          for(var index = 0; index < data.length; index++) {
            _self.projectAdminUsers[index] = data[index];
            // _self.$set(_self.projectAdminUsers, index, data[index]);
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
    /**
			 * 打开明细
			 * @author ZhangTeng 20190131
			 */
    openLine: function(obj) {
      this.$router.push({
        path: '/trace/trace/' + obj.id,
      });
    },

    /**
			 * 添加任务
			 * @author ZhangTeng 20190201
			 */
    addTrace: function(projectId) {
      this.$router.push('/trace/traceCreate/' + projectId);
    },

    /**
			 * 项目归档
			 * @param {Object} projectId
			 * @author GuoZhiBo 20190926
			 */
    projectArchive: function(projectId) {
      var _self = this;
      this.$router.push({
        path: '/trace/projectArchive/' + projectId,
        query: {
          projectName: _self.projectName,
        },
      });
    },
    /**
			 * 项目任务
			 * @param {Object} projectId
			 * @author GuoZhiBo 20190926
			 */
    projectManagement: function(projectId) {
      var _self = this;
      this.$router.push({
        path: '/trace/projectManagement/' + projectId,
        query: {
          projectName: _self.projectName,
        },
      });
    },
    /**
			 *  跳转到人员界面
			 *  @author ZhangTeng 20190212
			 */
    goPersonList: function() {
      var _self = this;
      this.$router.push({
        path: '/trace/projectUserList/' + _self.projectId,
        query: {
          projectName: _self.projectName,
        },
      });
    },

    /**
			 *  跳转到项目管理人员界面
			 *  @author ZhangTeng 20190212
			 */
    goAdminPersonList: function() {
      var _self = this;
      this.$router.push({
        path: '/trace/projectAdminUserList/' + _self.projectId,
        query: {
          projectName: _self.projectName,
        },
      });
    },

    /**
			 * 修改追踪单的状态
			 * @author YangZhiJie 20171201
			 */
    updateTracefinished: function(trace) {
      var _self = this;
      TraceResource.updateTraceFinished(trace.id).then(successData => {
        _self.listNotFinishedTask();
      }, errorData => {
        Common.processException(errorData);
      });
    },

  },
};
</script>

<style scoped>
	.trace-summary {
		font-size: large;
		margin-left: 5px;
		margin-right: 5px;
	}
	
	.trace-icon {
		opacity: 0.5;
	}
	
	.trace-user {
		font-size: 100%;
	}
	
	.trace-checkbox {
		display: inline;
		font-size: large;
	}
</style>