import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { ProjectService } from '../../project.service';

@Component({
  selector: 'smart-project-modal',
  templateUrl: './project-modal.component.html',
  styles: []
})
export class ProjectModalComponent implements OnInit {

  @Output() done = new EventEmitter<any>();

  isVisiable = false;
  obj = {
    keyword: ''
  };

  page = {
    list: [],
    isLoading: false,
    totalNum: 0,
    pageNum: 1,
    pageCount: 5,
  };

  inSelect;
  selectType;
  selectAll = [];

  constructor(private projectSer: ProjectService) {
  }

  ngOnInit() {
    // this.getList();
  }

  showModal(type?: string, data?: any) {
    this.selectAll = [];
    let idArr = [];
    let nameArr = [];
    
    if(data) {
      idArr = (data.relevMaintainId && data.relevMaintainId.split(',')) || [];
      nameArr = (data.relevMaintainId && data.relevMaintainName.split(',')) || [];
    }
    this.selectAll = idArr.map((id, index) => ({
      id: id,
      name: nameArr[index]
    }))
    console.log(this.selectAll);
    
    this.selectType = type || '';

    this.isVisiable = true;

    this.getList();
  }

  getList() {
    this.page.isLoading = true;
    const obj = {
      obj: this.obj,
      pageNum: this.page.pageNum,
      pageCount: this.page.pageCount
    };
    this.projectSer.selectMaintainProject(obj).subscribe(
      (res) => {
        if (res.errCode == 10000) {
          this.page.list = res.data.data.map(item => {
            const inx = this.selectAll.findIndex(child => child.id === item.id);
            item.checked = inx !== -1;
            return item;
          });
          this.page.totalNum = res.data.totalNum;
          this.page.isLoading = false;
        }
      }
    );
  }

  PageDataChange(e) {

  }

  changePage(e) {
    this.page.pageNum = e;
    this.getList();
  }

  selectItem(item, e) {
    // console.log('selectItem', item);
    if (this.selectType === 'more') {
      const inx = this.selectAll.findIndex(child => child.id === item.id);
      if (item.checked) {
        if (inx === -1) {
          this.selectAll.push(item);
        }
      } else {
        if (inx !== -1) {
          this.selectAll.splice(inx, 1);
        }
      }
      // console.log('selectItem', this.selectAll);
    } else {
      if (e) {
        const arr = this.page.list.map(data => {
          return data.itemId;
        });
        const old = this.inSelect;
        if (old) {
          const index = arr.indexOf(old.itemId);
          this.page.list[index].checked = false;
        }
        this.inSelect = item;
      } else {
        this.inSelect = null;
      }
    }
  }

  handleOk() {
    this.isVisiable = false;
    if (this.selectType === 'more') {
      this.done.emit(this.selectAll);
    } else {
      this.done.emit(this.inSelect);
    }
  }

  handleCancel() {
    this.isVisiable = false;
  }

}
