import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { opr_company_type, project_type } from '../../project.constants';
import { SystemService } from '../../../system/system.service';
import { ProjectService } from '../../project.service';
import { ProjectModalComponent } from '../project-modal/project-modal.component';
import { CompanyModalComponent } from '../company-modal/company-modal.component';
import { TeamPeopleComponent } from '../team-people/team-people.component';
import { TeamModalComponent } from '../team-modal/team-modal.component';
import { TrackInfoComponent } from '../track-info/track-info.component';
import { WorkService } from '../../../work/work.service';

@Component({
  selector: 'smart-create-project',
  templateUrl: './create-project.component.html',
  styles: [
    `
            :host ::ng-deep .ant-input-disabled {
                color: rgba(0, 0, 0, .65);
                background-color: #fff;
            }
        `
  ]
})
export class CreateProjectComponent implements OnInit {
  @ViewChild('smartProjectModal') smartProjectModal: ProjectModalComponent;
  @ViewChild('smartCompanyModal') smartCompanyModal: CompanyModalComponent;
  @ViewChild('smartTeamModal') smartTeamModal: TeamModalComponent;
  @ViewChild('smartTrackInfo') smartTrackInfo: TrackInfoComponent;
  @Output() done = new EventEmitter<any>();
  tabNum = 0;    //tabs面板的序列号
  timeFormat = 'yyyy-MM-dd';

  title = '';
  isVisible = false;
  isOkLoading = false;
  validateForm: FormGroup;
  fileList: UploadFile[] = [];
  fileId = [];
  opr_company_type = project_type;

  cID;
  type = '';
  proData;
  selectProName = '';

  constructor(private fb: FormBuilder, private systemSer: SystemService,
    private workSer: WorkService,
    private message: NzMessageService, private projectSer: ProjectService) {
  }

  ngOnInit(): void {
    this.initForm();
  }

  initForm() {
    this.tabNum = 0;
    this.validateForm = this.fb.group({
      name: [null, [Validators.required, Validators.minLength(2), Validators.maxLength(50)]],
      officeName: [null],
      officePrincipal: [null],
      aPrincipal: [null],
      bprincipal: [null],
      bprincipalName: [null],
      amount: [null],
      type: [null],
      companyId: [null],
      companyName: [null],
      relevMaintainId: [null],
      relevMaintainName: [null],
      teamId: [null],
      principal: [null],
      startDate: [null],
      endDate: [null],
      status: [null],
    });
  }

  showAddModal(title) {
    this.isVisible = true;
    this.title = title;
  }

  showEditModal(data, title) {
    this.initForm();
    this.proData = data;
    this.isVisible = true;
    data.type += '';
    this.title = title;
    this.cID = data.id;
    this.smartTrackInfo.diffResource(data.id);
    this.validateForm.patchValue(data);
  }

  showLookModal(data) {
    this.isVisible = true;
    this.title = data.name;
    this.type = 'look';
    this.validateForm.patchValue(data);
  }

  handleCancel() {
    this.isVisible = false;
    this.isOkLoading = false;
    this.initForm();
  }

  beforeUpload = (file: UploadFile): boolean => {
    this.fileList.push(file);
    let file1 = <any>file;
    const formData = new FormData();
    formData.append('file', file1);
    this.workSer.sysFileUpload(formData).subscribe(
      (res) => {
        if (res.errCode == 10000) {
          this.fileId.push(res.data.id);
        }
      }
    );

    return false;
  };

  handleOk(status) {
    for (let i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (this.validateForm.invalid) {
      return false;
    }
    this.isOkLoading = true;
    if(this.validateForm.value.startDate === null && this.validateForm.value.endDate === null){
      this.validateForm.patchValue({
        startDate: null,
        endDate: null,
        status: status
      });
    }else {
      this.validateForm.patchValue({
        startDate: new Date(this.validateForm.value.startDate).getTime(),
        endDate: new Date(this.validateForm.value.endDate).getTime(),
        status: status
      });
    }
    if (this.title == '新增运维项目') {
      this.create();
    }
    if (this.title == '编辑运维项目') {
      this.update();
    }
  }

  create() {
    this.validateForm.addControl('fileId', new FormControl(this.fileId.join(',')));
    this.projectSer.addMaintainProject(this.validateForm.value).subscribe(
      (res) => {
        if (res.errCode == 10000) {
          this.isVisible = false;
          this.initForm();
          this.done.emit();
          this.message.success('新增运维项目成功');
        }
        this.isOkLoading = false;
      }
    );
  }

  update() {
    this.validateForm.addControl('id', new FormControl(this.cID));
    this.projectSer.updateMaintainProject(this.validateForm.value).subscribe(
      (res) => {
        if (res.errCode == 10000) {
          this.isVisible = false;
          this.initForm();
          this.done.emit();
          this.message.success('更新项目成功');
        }
        this.isOkLoading = false;
      }
    );
  }

  //tabs切换
  tabsChange(num) {
    this.tabNum = num;
  }

  // 选择的项目
  showProjectmodal() {
    this.smartProjectModal.showModal('more', this.proData);
  }

  //showCompanymodal
  showCompanymodal() {
    this.smartCompanyModal.showModal();
  }

  getProject(e) {
    // console.log('getProject', e);
    this.selectProName = e.map(item => item.name).join(',');
    const d = {
      relevMaintainId: e.map(item => item.id).join(','),
      relevMaintainName: e.map(item => item.name).join(',')
    };
    this.validateForm.patchValue(d);
  }

  getCompany(e) {
    const d = {
      companyId: e.id,
      companyName: e.name
    };
    this.validateForm.patchValue(d);
  }

  //    获取人员
  showSelectPeople() {
    if (!this.validateForm.value.companyId) {
      this.message.info('请选择乙方公司');
      return;
    }
    this.smartTeamModal.showModal(this.validateForm.value.companyId, '项目经理');
  }

  setPeople(e) {
    const d = {
      bprincipalName: e.userName,
      bprincipal: e.id
    };
    this.validateForm.patchValue(d);
    console.log(e);
  }
}
