import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {WorkService} from '../../work.service';
import {NzMessageService, UploadFile} from 'ng-zorro-antd';
import {SelectPersonComponent} from '../../../modal/select-person/select-person.component';

@Component({
    selector: 'smart-event',
    templateUrl: './event.component.html',
    styles: []
})
export class EventComponent implements OnInit {
    @ViewChild('smartSelectPerson') smartSelectPerson: SelectPersonComponent;
    @Output() done = new EventEmitter<any>();
    isVisiable = false;
    title;
    eventId;
    validateForm: FormGroup;

    fileList: UploadFile[] = [];
    operatorsList = [];    //处理人列表
    eventTypeList = [];   //事件分类列表
    constructor(private workSer: WorkService, private message: NzMessageService,
                private fb: FormBuilder) {
    }

    ngOnInit() {
        this.initForm();
    }

    initForm() {
        this.fileList = [];
        this.operatorsList = [];
        this.validateForm = this.fb.group(
            {
                title: [null, [Validators.required,Validators.maxLength(20)]],
                description: [null,Validators.maxLength(300)],
                type: [null, [Validators.required]],
                requester: [null, [Validators.required,Validators.maxLength(10)]],
                requesterPhone: [null, [Validators.required,Validators.maxLength(13)]],
                operators: [null],
            }
        );
    }

    getEventType() {
        const data = {
            type: 0
        };
        this.workSer.findByType(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.eventTypeList = res.data;
                }
            }
        );
    }

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

    showAddModal(title) {
        this.isVisiable = true;
        this.title = title;
        this.getEventType();
    }

    showEditModal(title, id) {
        this.isVisiable = true;
        this.title = title;
        this.eventId = id;
        this.getEventType();
        this.workSer.findByNo(this.eventId).subscribe(
            (res) => {
                this.validateForm.patchValue(res.data);
            }
        );
    }

    handEditleOk() {
        if (this.title == '新增事件') {
            this.create();
        }
        if (this.title == '编辑事件') {
            this.update();
        }
    }

    //新增
    create() {
        let formData = new FormData();
        this.fileList.forEach((file: any) => {
            formData.append('file', file);
        });
        if (this.operatorsList.length == 0) {
            this.message.error('请选择人员');
            return false;
        }
        this.validateForm.patchValue({
            operators: this.operatorsList
        });
        for (let i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
            this.validateForm.controls[i].updateValueAndValidity();
        }
        if (this.validateForm.invalid) {
            return false;
        }
        formData.append('json', JSON.stringify(this.validateForm.value));
        this.workSer.create(formData).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isVisiable = false;
                    this.initForm();
                    this.done.emit();
                    this.message.success('新增事件成功');
                }
            }
        );
    }

    //编辑
    update() {
        let formData = new FormData();
        this.fileList.forEach((file: any) => {
            formData.append('file', file);
        });
        this.validateForm.patchValue({
            operators: this.operatorsList
        });

        if (this.operatorsList.length == 0) {
            this.message.error('请选择人员');
            return false;
        }
        for (let i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
            this.validateForm.controls[i].updateValueAndValidity();
        }
        if (this.validateForm.invalid) {
            return false;
        }

        formData.append('json', JSON.stringify(this.validateForm.value));
        formData.append('id', this.eventId);
        this.workSer.update(formData).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isVisiable = false;
                    this.initForm();
                    this.done.emit();
                    this.message.success('修改事件成功');
                }
            }
        );
    }

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

    //选择处理人
    selectPerson() {
        this.smartSelectPerson.showModal('选择处理人', null);
    }

    deletePerson(i) {
        this.operatorsList.splice(i, 1);
    }

    getUser(e) {
        const arr = [];
        e.forEach(res => {
            const data = {
                username: res.name,
                userId: res.id
            };
            arr.push(data);
        });
        this.operatorsList = arr;
    }
}
