import {Component, ElementRef, Input, OnInit, ViewChild, Output, EventEmitter} from '@angular/core';
import {FrameRequest} from '../../shared/frame/frame-request';
import {ToasterService} from 'angular2-toaster';
import {AppComponent} from '../../app.component';
import {CookieService} from 'ngx-cookie-service';
import * as _ from 'lodash';
const swal = require('sweetalert');

@Component({
  selector: 'frame-pager',
  templateUrl: './pager.component.html',
  styleUrls: ['./pager.component.scss']
})
export class FramePagerComponent implements OnInit {
  paging = false;

  // 查询框宽度
  @Input()
  searchWidth = 60;
  // 当前显示几页
  @Input()
  pageLength = 5;
  // 每页条数
  @Input()
  pageLimit;
  // 是否允许修改每页条数
  @Input()
  bChangeLimit = true;
  // 是否允许修改当前页
  @Input()
  bChangeIndex  = true;
  // 是否隐藏pager框
  @Input()
  hidePager = false;
  // 是否隐藏查询框
  @Input()
  hideSearch = false;
  // 是否隐藏分页区域
  @Input()
  hidePagination = false;
  // 是否隐藏分页区域
  @Input()
  pageParams = {};
  // 请求的Url
  @Input()
  url = '';
  // 是否自动加载记录
  @Input()
  autoLoad = true;

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

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

  // 总组数
  totalGroup = 0 ;
  currentGroup = 0;
  // 分页数据
  records: any;

  ckPageLimit = 10;

  private CookiesPageLimintName = 'Frame.PageLimit';
  pages: any;

  @Output() 
  preReqEvent = new EventEmitter()

  @Input()
  hasCheck = false;
  
  constructor(private cookieService: CookieService) {
    this.pages = new Array();
    this.records = new Array();
  }

  ngOnInit() {
    if (this.pageLimit === undefined) {
      if (this.cookieService.get(this.CookiesPageLimintName)) {
        this.ckPageLimit = parseInt(this.cookieService.get(this.CookiesPageLimintName), 10);
        if (this.ckPageLimit !== undefined && !isNaN(this.ckPageLimit)) {
          this.pageLimit = this.ckPageLimit;
        }
      } else {
        this.pageLimit = this.ckPageLimit;
      }
    }

    for (let i = 0; i < this.pageLength; i++) {
      this.pages.push({
        active: false,
        number: i + 1,
        data: false
      });
    }
    this.pages[4].active = true;
    if (this.autoLoad) {
      this.requestPage();
    }
    // this.elPageLimit.nativeElement.

  }

  // 修改每页条数
  protected 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.requestPage();
      this.cookieService.set(this.CookiesPageLimintName,  `${this.pageLimit}`);
    }
  }

  // 修改当前页面
  protected 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.pageLimit + 1;
      this.requestPage();
    }
  }


  // 实际的分页请求
  protected requestPage() {
    if (this.url === '') {
      return;
    }
    if (!this.pageParams) {
      this.pageParams = {};
    }
    this.pageParams['limit'] = this.pageLimit;
    this.pageParams['start'] = this.pageStart - 1;
    if (this.query && this.query.trim().length > 0) {
      this.pageParams['query'] = this.query;
    } else {
      this.pageParams['query'] = '';
    }
    if (this.orderColumn !== '') {
      this.pageParams['order'] = this.orderColumn;
    }
    if (this.orderType !== '') {
      this.pageParams['type'] = this.orderType;
    }
    this.paging = true;
    if(this.preReqEvent.observers.length > 0){
      this.preReqEvent.emit(this.pageParams)
      if(this.pageParams['rtn'] === true){
        this.paging = false;
        return;
      }
    }

    FrameRequest.requestPage(this.url, this.pageParams, (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.pageLength);
      // 当前分组
      this.currentGroup = Math.ceil(page.index / this.pageLength);

      // 如果是第一分组，不显示
      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.pageLength; i++) {
        const pageNumber = (this.currentGroup - 1) * this.pageLength + 1 + i;
        this.pages[i] = {
          active: pageNumber === pIndex ? true : false,
          number: pageNumber,
          data: pageNumber <= this.pageTotal ? true : false
        };
      }
      this.paging = false;
      // console.log(page);
    },  () => {
      this.paging = false;
    });

  }

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

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

  // 跳转到第一页
  protected goFirst() {
    this.pageStart =  1;
    this.requestPage();
  }
  // 跳转到最后一页
  protected goLast() {
    this.pageStart = (this.pageTotal - 1 ) * this.pageLimit + 1;
    this.requestPage();
  }
  // 跳转到上一组
  protected goPrevGroup() {
    this.pageStart = ((this.currentGroup - 2) * this.pageLength ) * this.pageLimit + 1;
    this.requestPage();
  }
  // 跳转到下一组
  protected  goNextGroup() {
    this.pageStart = (this.currentGroup * this.pageLength ) * this.pageLimit + 1;
    this.requestPage();
  }

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

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


  // 获取数据
  public getRecords() {
    return this.records;
  }

  // 排序
  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.requestPage();
  }

  public sortType(column,type) {
    this.orderColumn = column;
    this.orderType = type;
    this.requestPage();
  }

  // 删除一条数据
  public optr(url: string, value: any, warn?: string, success?: string, callback?: Function) {
    const scope = this;
    const thisCallback = () => {
      // 请求数据
      FrameRequest.request(url, value, (data) => {
        if (success !== undefined) {
          if (success === '') {
            success = '操作成功！';
          }
          AppComponent.GobalComponent.getToaster().pop('success', '', success);
        }
        if (callback !== undefined) {
          // 调用函数
          callback.call(scope, data);
        }
        // 刷新
        this.reload();
      });
    };

    if (warn !== undefined) {
      if (warn === '') {
        warn = '此操作即将提交到服务器进行保存，请确认要进行此操作';
      }
      swal({
        title: '操作确认',
        text: warn,
        // type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#17a2b8',
        confirmButtonText: '确定提交',
        cancelButtonText: '取消操作',
        closeOnConfirm: false,
        closeOnCancel: true
      }, (isConfirm) => {
        if (isConfirm) {
          swal.close();
          thisCallback();
        }
      });
    } else {
      thisCallback();
    }
  }

  // 编辑
  private edit(url:string, key: any, callback: Function) {
    FrameRequest.request(url, {key: key }, (data) => {
      callback.call(undefined, data);
    });
  }

  private req(url, param , fn ) {
    FrameRequest.request(url, param, fn);
  }

  public reload() {
    this.autoLoad = true;
    this.requestPage();
  }

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

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