import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {SelectPersonComponent} from '../../../modal/select-person/select-person.component';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {WorkService} from '../../work.service';
import {NzMessageService, UploadFile} from 'ng-zorro-antd';
import {DatePipe} from '@angular/common';
import {remind_time} from '../../work.constants';
import {ProjectModalComponent} from '../../../project-manager/modal/project-modal/project-modal.component';
import {LocalStorageService} from 'ngx-webstorage';

@Component({
    selector: 'smart-plan-config',
    templateUrl: './plan-config.component.html',
    styles: []
})
export class PlanConfigComponent implements OnInit {
    @ViewChild('smartSelectPerson') smartSelectPerson: SelectPersonComponent;
    @ViewChild('smartProjectModal') smartProjectModal: ProjectModalComponent;
    @Output() done = new EventEmitter<any>();

    remindTime = remind_time;
    planList;
    planId;
    title;
    isVisiable = false;
    isLoading = false;
    isDisabled = false;
    validateForm: FormGroup;
    fileList = [];

    modalTitle;

    participantsList = []; //参与人
    principalsList = [];   //负责人

    constructor(private workSer: WorkService, private message: NzMessageService,
                private localStorage: LocalStorageService,
                private fb: FormBuilder, private datePipe: DatePipe) {
    }

    ngOnInit() {
        this.initForm();
        this.getPlanType();
    }

    initForm() {
        this.fileList = [];
        this.isDisabled = false;
        this.participantsList = [];
        this.principalsList = [];
        this.validateForm = this.fb.group({
            title: [null, [Validators.required]],
            typeId: [null, [Validators.required]],
            startTime: [null, [Validators.required]],
            endTime: [null, [Validators.required]],
            cycleType: [null, [Validators.required]],
            cycleNum: [null],
            workload: [null],
            description: [null],
            principals: [null],   //负责人
            participants: [null],   //参与人
            maintainProjectId: [null],   //关联部门Id
            maintainProjectName: [null],   //关联部门Name
            createUserName: [null],  //创建人
            createUserId: [null],  //创建人
            createOrganizationName: [null],  //创建人部门
            remindTime: [null]
        });
        const userInfo = this.localStorage.retrieve('userInfo');
        this.validateForm.patchValue({
            createUserName: userInfo.userName,
            createUserId: userInfo.userId,
            createOrganizationName: userInfo.organizationName,
        });
    }

    getPlanType() {
        const data = {
            type: 1
        };
        this.workSer.findByType(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.planList = res.data;
                }
            }
        );
    }

    beforeUpload = (file: UploadFile): boolean => {
        const isLt5M = file.size / 1024 < 5000;
        if (!isLt5M) {
            this.message.error(' 文件必须小于5M!');
        } else {
            this.fileList[0] = file;
        }
        return false;
    };

    showAddModal() {
        this.title = '添加计划';
        this.isVisiable = true;
    }

    showEditModal(id) {
        this.title = '编辑计划';
        this.planId = id;
        this.isVisiable = true;
        this.workSer.findPlan(id).subscribe(
            (res) => {
                res.data.number += '';
                res.data.cycleNum += '';
                this.participantsList = res.data.participants;
                this.principalsList = res.data.principals;
                if (res.data.fileName) {
                    this.fileList = [
                        {
                            name: res.data.fileName,
                        }
                    ];
                }
                this.validateForm.patchValue(res.data);
                this.validateForm.patchValue({
                    startTime: new Date(res.data.startTime),
                    endTime: new Date(res.data.endTime),
                });
                if (res.data.status == 1) {
                    this.isDisabled = true;
                }
            }
        );
    }

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

        if (this.validateForm.invalid) {
            return false;
        }

        if (this.principalsList.length == 0) {
            this.message.error('请选择负责人');
            return false;
        }

        this.validateForm.patchValue({
            principals: this.principalsList,
            participants: this.participantsList,
            startTime: this.datePipe.transform(this.validateForm.value.startTime, 'yyyy-MM-dd HH:mm:ss'),
            endTime: this.datePipe.transform(this.validateForm.value.endTime, 'yyyy-MM-dd HH:mm:ss'),
        });
        this.isLoading = true;
        if (this.title == '添加计划') {
            this.create();
        }
        if (this.title == '编辑计划') {
            this.update();
        }
    }

    create() {
        let formData = new FormData();
        this.fileList.forEach((file: any) => {
            formData.append('file', file);
        });

        formData.append('json', JSON.stringify(this.validateForm.value));
        this.workSer.createPlan(formData).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.initForm();
                    this.isVisiable = false;
                    this.done.emit();
                    this.message.success('新增计划成功');
                }
                this.isLoading = false;
            }
        );
    }

    update() {
        let formData = new FormData();
        this.fileList.forEach((file: any) => {
            formData.append('file', file);
        });
        this.validateForm.value.id = this.planId;
        formData.append('json', JSON.stringify(this.validateForm.value));
        this.workSer.updatePlan(formData).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.message.success('修改计划成功');
                    this.initForm();
                    this.done.emit();
                    this.isVisiable = false;
                }
                this.isLoading = false;
            }
        );
    }

    handleEditCancel() {
        this.isVisiable = false;
        this.initForm();
    }

    selectPerson2() {
        this.modalTitle = '选择负责人';
        this.smartSelectPerson.showModal(this.modalTitle, null);
    }

    getUser(e) {
        const arr = [];
        e.forEach(res => {
            const data = {
                username: res.name,
                userId: res.id
            };
            arr.push(data);
        });
        if (this.modalTitle == '选择参与人') {
            this.participantsList = arr;
        }
        if (this.modalTitle == '选择负责人') {
            this.principalsList = arr;
        }
    }

    //删除参与人
    delete1(index) {
        this.participantsList.splice(index, 1);
    }

    //删除负责人
    delete2(index) {
        this.principalsList.splice(index, 1);
    }

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

    //获取选择的项目
    getProject(e) {
        console.log(e);
        const d = {
            maintainProjectId: e.id,
            maintainProjectName: e.name
        };
        this.validateForm.patchValue(d);
    }
}
