import {Component, Input, OnDestroy, OnInit, Output, EventEmitter} from '@angular/core';
import {CookieService} from '../../../service/cookie.service';
import {FrameService} from '../../../service/frame.service';
import {MsgService} from '../../../service/msg.service';
import {AjaxService} from '../../../service/ajax.service';
import {Pager} from '../../../service/pager';
import {Ajax} from '../../../service/ajax';

@Component({
  selector: 'frame-pager',
  templateUrl: './frame-pager.html'
})
export class FramePager implements OnInit, OnDestroy {
  /**********************
   * 请求地址
   */
  @Input()
  url: string;
  /**********************
   * 请求参数
   */
  @Input()
  pagerParams: {};
  /*************************
   * 每个多少条数据
   */
  @Input()
  pagerLimit: number = 20;
  /**********************
   * 一组显示几页
   */
  @Input()
  pagerLength = 10;
  /**********************
   * 是否自动去请求数据
   */
  @Input()
  autoRequest: boolean = true;
  /*********************
   * 是否需要定时加在数据
   */
  @Input()
  loopRequestTicket: number = 0;
  /**********
   * 请求数据时是否显示加载等待界面
   */
  @Input()
  requestWithLoading: boolean = false;
  /*********************
   * 是否显示查询框
   */
  @Input()
  showSearch = true;
  /*******************
   * 是否显示分页组件
   */
  @Input()
  showPagination = true;
  /********************
   * 是否允许修改每个大小
   */
  @Input()
  allowChangePagerLimit = true;
  /**********************
   * 是否允许修改当前页面
   */
  @Input()
  allowChangePagerCurrent = true;
  /********************
   * 查询框样式
   */
  @Input()
  searchCss: string;
  /********************
   * 查询框样式
   */
  @Input()
  searchStyle = {'width': '60px'};

  @Input()
  hasCheck = false;

  /****************
   * 数据加载完毕
   */
  @Output()
  pageAjaxComplete = new EventEmitter<Pager>();
  /********************
   * 操作完毕
   */
  @Output()
  optrAjaxComplete = new EventEmitter<Ajax>();
  

  // 内部定时器，用于定时刷新时使用
  intervalId: any;
  // 所有分页数据
  pageArray: any;
  // 当前分页数据
  pageRecords: any;
  // 开始的记录条数
  pageStart = 1;
  // 当前第几页
  pageIndex = 1;
  // 总的页码
  pageTotal = 1;
  // 总记录数
  recordTotal = 0;
  // 返回的参数
  responseMap;


  // 总组数
  totalGroup = 0;
  // 当前在第几组
  currentGroup = 0;
  // 是否有下一组页面
  hasNextGroup = false;
  // 是否有前一组页面
  hasPrevGroup = false;
  // 是否显示第一个页
  showFirstPage = false;
  // 是否显示最后一页
  showLastPage = false;

  // 是否正在加载数据
  dataLoading = false;
  // 查询值
  query: string;
  // 排序字段
  orderColumn = '';
  // 排序方式
  orderType = '';
  disabled = false;


  static cookieName_PageLimit = 'Frame.PagerLimit';

  constructor() {
    this.pageArray = [], this.pageRecords = [];
  }

  ngOnInit(): void {
    // 取每页多少条记录
    this.pagerLimit = this.pagerLimit || CookieService.get(FramePager.cookieName_PageLimit) ||
      parseInt(FrameService.getParamValue('FramePageLimit', 20), 10);
    // 初始化分页的页面数
    for (let i = 0; i < this.pagerLength; i++) {
      this.pageArray.push({active: false, number: i + 1, data: []});
    }
    if (this.autoRequest)
      setTimeout(this.requestData.bind(this), 0);

  }

  /**************************
   * 请求数据
   */
  requestData(params?: {}) {
    if (this.url === '' || this.url === undefined) {
      MsgService.errorAlert('未设置请求地址，请检查！');
      return;
    }
    const rData = Object.assign({}, this.pagerParams, params);
    rData['limit'] = this.pagerLimit;
    rData['start'] = this.pageStart - 1;
    if (this.query && this.query.trim().length > 0)
      rData['query'] = this.query;
    if (this.orderColumn !== '')
      rData['order'] = this.orderColumn;
    if (this.orderType !== '')
      rData['type'] = this.orderType;
    this.dataLoading = true;
    AjaxService.requestPage(this.url, rData, (page) => {
        page.index = page.index + 1;
        this.pageIndex = page.index;
        // 总记录数
        this.recordTotal = page.total;
        // 记录
        this.pageRecords = page.records;
        // 总页数
        this.pageTotal = page.count;
        // 参数信息

        this.responseMap = page.param;
        // 当前页面
        const pIndex = page.index;
        //
        // 计算在第几组
        this.totalGroup = Math.ceil(page.count / this.pagerLength);
        // 当前分组
        this.currentGroup = Math.ceil(page.index / this.pagerLength);

        // 如果是第一分组，不显示
        if (this.currentGroup === 1) {
          this.hasPrevGroup = false;
          this.showFirstPage = false;
        } else {
          this.hasPrevGroup = true;
          this.showFirstPage = true;
        }

        // 判断是否显示最后一组
        if (this.currentGroup >= this.totalGroup) {
          this.hasNextGroup = false;
          this.showLastPage = false;
        } else {
          this.hasNextGroup = true;
          this.showLastPage = true;
        }

        for (let i = 0; i < this.pagerLength; i++) {
          const pageNumber = (this.currentGroup - 1) * this.pagerLength + 1 + i;
          this.pageArray[i] = {
            active: pageNumber === pIndex ? true : false,
            number: pageNumber,
            data: pageNumber <= this.pageTotal ? true : false
          };
        }
        this.dataLoading = false;
        // 判断是否需要间隔获取数据
        if (this.loopRequestTicket > 0 && this.intervalId === undefined) {
          this.intervalId = setInterval(this.requestData.bind(this), this.loopRequestTicket * 1000);
        }
        this.pageAjaxComplete.emit(page);
        // console.log(page);
      }, {
        'RequestWithLoading': this.requestWithLoading,
        'ErrorCallback': () => {
          this.dataLoading = false;
          // 判断是否需要间隔获取数据
          if (this.loopRequestTicket > 0 && this.intervalId === undefined) {
            this.intervalId = setInterval(this.reload.bind(this), this.loopRequestTicket * 1000);
          }
        }
      }
    );
  }

  /***************
   * 重新请求数据
   */
  public reload(param?: any) {
    this.requestData(param);
  }

  //全选复选切换
  public checkedMasterToggle(event){
    this.setCheckedAll(event.currentTarget.checked)
  } 
  
  //设置全选 反选状态
  public setCheckedAll(checkStatus){
    
    //if(!this.hasCheck) return [];
    this.pageRecords.forEach((item) => {
      item['isChecked'] = checkStatus;
      
     });

  }

  //获取checked数组
  public getCheckedArray(func?){
   // if(!this.hasCheck) return [];
    let checkedArray = [];
    this.pageRecords.forEach((item) => {
      if(item['isChecked'] === true) 
      if(func){
        checkedArray.push(func.call(this,item));
      }else{
        checkedArray.push(item);
      }
      
     });

    return checkedArray;
  }

  /********************
   * 修改每页条数
   */
  changePageLimit(event) {
    if (event.keyCode === 13) {
      const temp = parseInt(`${this.pageIndex}`, 10);
      if (isNaN(temp) || temp < 1) {
        this.pageIndex = 1;
      } else {
        this.pageIndex = temp;
      }
      this.pageStart = 1;
      this.requestData();
      CookieService.set(FramePager.cookieName_PageLimit, `${this.pagerLimit}`);
    }
  }

  /******************
   * 修改当前页面
   */
  changePageIndex(event) {
    if (event.keyCode === 13) {
      const temp = parseInt(this.pageIndex + '', 10);
      if (isNaN(temp) || temp < 1) {
        this.pageIndex = 1;
      } else if (this.pageIndex > this.pageIndex) {
        this.pageIndex = temp;
      } else {
        this.pageIndex = temp;
      }
      this.pageStart = (this.pageIndex - 1) * this.pagerLimit + 1;
      this.requestData();
    }
  }

  /*******************
   * 敲回车或者点击查询按钮
   */
  goSearch(event) {
    if (event) {
      if (event.keyCode !== 13) {
        return;
      }
    }
    this.pageStart = 1;
    this.requestData();
  }

  /****************
   * 点击页面跳转
   */
  goPage(page) {
    // 开始页面
    this.pageStart = (page.number - 1) * this.pagerLimit + 1;
    this.requestData();
  }

  /********************
   * 跳转到第一页
   */
  goFirst() {
    this.pageStart = 1;
    this.requestData();
  }

  /******************
   * 跳转到最后一页
   */
  goLast() {
    this.pageStart = (this.pageTotal - 1) * this.pagerLimit + 1;
    this.requestData();
  }

  /*******************
   * 跳转到上一组
   */
  goPrevGroup() {
    this.pageStart = ((this.currentGroup - 2) * this.pagerLength) * this.pagerLimit + 1;
    this.requestData();
  }

  /*******************
   * 跳转到下一组
   */
  goNextGroup() {
    this.pageStart = (this.currentGroup * this.pagerLength) * this.pagerLimit + 1;
    this.requestData();
  }

  /***************
   * 排序
   */
  public sort(column) {
    if (column === this.orderColumn) {
      if (this.orderType === 'ASC') {
        this.orderType = 'DESC';
      } else {
        this.orderType = 'ASC';
      }
    } else {
      this.orderColumn = column;
      this.orderType = 'ASC';
    }
    this.pageStart = 1;
    this.requestData();
  }

  getPageLimitWidth() {
    return (8 + (this.pagerLimit + '').length * 6) + 'px';
  }

  getPageIndexWidth() {
    return (8 + (this.pageIndex + '').length * 6) + 'px';
  }

  /***************
   * 获取完数据后回调函数
   * @param response
   * @private
   */

  /********************
   * ajax请求后自动刷新page数据
   */
  public optrRecord(url: string, data: {}, param?: { successMsg?: string, successMsgType?: string, confirmMsg?: string, callback?: Function }, options?: { RequestWithLoading?: boolean }) {
    param = param || {};
    let callback = param.callback || function () {
    };
    let fn = function (response) {
      callback.call(undefined, response);
      this.reload();
      this.optrAjaxComplete.emit(response);
    };
    param.callback = fn.bind(this);
    AjaxService.ajaxRequest(url, data, param, options);
  }

  /********************
   * 获取本页数据
   */
  public getRecords() {
    return this.pageRecords;
  }

  public getResponseMap() {
    return this.responseMap;
  }
  /*********************
   * 销毁时清理定时器
   */
  ngOnDestroy(): void {
    clearTimeout(this.intervalId);
  }
  
  /*********************
   *清除数据
   */
  public clear(): void {
    this.pageRecords = [];
    this.pageStart = 1;
    // 当前第几页
    this.pageIndex = 1;
    // 总的页码
    this.pageTotal = 1;
    // 总记录数
    this.recordTotal = 0;
    // 是否有下一组页面
    this.hasNextGroup = false;
    // 是否有前一组页面
    this.hasPrevGroup = false;
    // 是否显示第一个页
    this.showFirstPage = false;
    // 是否显示最后一页
    this.showLastPage = false;
    // 总组数
    this.totalGroup = 0;
    this.currentGroup = 0;
}

}
