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

@Component({
  selector: 'frame-pager',
  templateUrl: './pager.component.html'
})
export class PagerComponent implements OnInit, OnDestroy {
  @Input()
  searchClass: {};
  @Input()
  searchStyle = {'width': '60px'};
  @Input()
  pagerLength = 10;
  @Input()
  pagerLimit: number;
  @Input()
  allowChangePagerLimit = true;
  @Input()
  allowChangePagerCurrent = true;
  @Input()
  showSearch = true;
  @Input()
  showPagination = true;
  @Input()
  url: string;
  @Input()
  pagerParams: {};
  @Input()
  autoRequest = true;
  @Input()
  showLoading = false;
  @Input()
  loopRequestTicket = 0;

  @Output()
  pagerChange = new EventEmitter<any>();
  @Output()
  recordChange = new EventEmitter<any>();

  // 开始的记录条数
  pageStart = 1;
  // 当前第几页
  pageIndex = 1;
  // 总的页码
  pageTotal = 1;
  // 总记录数
  recordTotal = 0;
  // 是否有下一组页面
  hasNextGroup = false;
  // 是否有前一组页面
  hasPrevGroup = false;
  // 是否显示第一个页
  showFirst = false;
  // 是否显示最后一页
  showLast = false;

  // 查询
  query: string;
  // 排序字段
  orderColumn = '';
  // 排序方式
  orderType = '';

  // 总组数
  private totalGroup = 0;
  private currentGroup = 0;
  // 所有分页数据
  private pages: any;
  // 当前分页数据
  private records: any;
  private cookieName_PageLimit = 'Frame.PagerLimit';

  // 是否正在加载数据
  dataLoading = false;

  private intervalId: any;


  constructor(private cookie: CookieService) {
    this.pages = [];
    this.records = [];
  }

  ngOnInit(): void {
    // 取每页多少条记录
    if (this.pagerLimit === undefined) {
      // 如果没有指定当前页面记录数，先从cookies获取
      if (this.cookie.get(this.cookieName_PageLimit)) {
        // 如果cookies有数据
        this.pagerLimit = parseInt(this.cookie.get(this.cookieName_PageLimit), 10);
      } else {
        // cookie没有数据，从系统获取
        if (FrameService.ParamMap['FramePageLimit']) {
          this.pagerLimit = parseInt(FrameService.ParamMap['FramePageLimit']['param_value'], 10);
        }
      }
      if (this.pagerLimit === undefined || isNaN(this.pagerLimit)) {
        this.pagerLimit = 20;
      }
    }

    // 初始化分页的页面数
    for (let i = 0; i < this.pagerLength; i++) {
      this.pages.push({
        active: false,
        number: i + 1,
        data: false
      });
    }

    if (this.autoRequest) {
      setTimeout(() => {
        this.requestData();
      }, 1);
    }
  }

  // 数据加载，实际的分页请求
  private requestData(params?: {}) {
    if (this.url === '' || this.url === undefined) {
      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.records = page.records;

        // 总页数
        this.pageTotal = page.count;
        // 当前页面
        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.showFirst = false;
        } else {
          this.hasPrevGroup = true;
          this.showFirst = true;
        }

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

        for (let i = 0; i < this.pagerLength; i++) {
          const pageNumber = (this.currentGroup - 1) * this.pagerLength + 1 + i;
          this.pages[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.reload.bind(this), this.loopRequestTicket * 1000);
        }
        this.pagerChange.emit(page);
        // console.log(page);
      }, {
        'RequestWithLoading': this.showLoading,
        'ErrorCallback': () => {
          this.dataLoading = false;
          // 判断是否需要间隔获取数据
          if (this.loopRequestTicket > 0 && this.intervalId === undefined) {
            this.intervalId = setInterval(this.reload.bind(this), this.loopRequestTicket * 1000);
          }
        }
      }
    );
  }

  // 修改每页条数
  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();
      this.cookie.set(this.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();
  }

  // 重新加载
  public reload(param?: any) {
    this.requestData(param);
  }

  // 清除数据
  public clear(): void {
    this.records = [];
    this.pageStart = 1;
    // 当前第几页
    this.pageIndex = 1;
    // 总的页码
    this.pageTotal = 1;
    // 总记录数
    this.recordTotal = 0;
    // 是否有下一组页面
    this.hasNextGroup = false;
    // 是否有前一组页面
    this.hasPrevGroup = false;
    // 是否显示第一个页
    this.showFirst = false;
    // 是否显示最后一页
    this.showLast = false;
    // 总组数
    this.totalGroup = 0;
    this.currentGroup = 0;
  }

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

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

  // 获取记录
  public getRecords(): [any] {
    return this.records;
  }

  // 删除数据
  public optrRecord(url: string, data: {}, param?: { successMsg?: string, successMsgType?: string, confirmMsg?: string, callback?: Function }, options?: { RequestWithLoading?: boolean }) {
    if (options === undefined) {
      options = {};
    }
    if (options.RequestWithLoading === undefined) {
      options.RequestWithLoading = true;
    }

    const confirmMsg = param ? param.confirmMsg : undefined;

    const fn = () => {
      AjaxService.request(url, data, () => {
        const successMsg = param ? (param.successMsg ? param.successMsg : '操作成功') : '操作成功';
        if (successMsg) {
          const successMsgType = param ? (param.successMsgType ? param.successMsgType : 'Toaster') : 'Toaster';
          if (successMsgType === 'Toaster') {
            MsgService.successToaster(successMsg);
          } else if (successMsgType === 'Swal') {
            MsgService.successAlert(successMsg);
          } else {
            alert(successMsg);
          }
        }
        this.reload();
        this.recordChange.emit(data);
        const callback = param ? param.callback : undefined;
        if (callback) {
          callback.call(undefined, data);
        }
      }, options);
    };

    if (confirmMsg) {
      MsgService.confirm(confirmMsg, fn);
    } else {
      fn.call(undefined);
    }

  }


  ngOnDestroy(): void {
    clearTimeout(this.intervalId);
  }

}
