import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {ProjectModalComponent} from '../../../project-manager/modal/project-modal/project-modal.component';
import {CompanyModalComponent} from '../../../project-manager/modal/company-modal/company-modal.component';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {NzMessageService, UploadFile} from 'ng-zorro-antd';
import {SystemService} from '../../../system/system.service';
import {SystemChangeService} from '../../system-change.service';
import {SelectPersonComponent} from '../../../modal/select-person/select-person.component';
import {change_level} from '../../system-change.constants';
import {TrackInfoComponent} from '../../../project-manager/modal/track-info/track-info.component';
import {LocalStorageService} from 'ngx-webstorage';
import {WorkService} from '../../../work/work.service';

@Component({
    selector: 'smart-change-create',
    templateUrl: './change-create.component.html',
    styles: []
})
export class ChangeCreateComponent implements OnInit {
    @ViewChild('smartProjectModal') smartProjectModal: ProjectModalComponent;
    @ViewChild('smartCompanyModal') smartCompanyModal: CompanyModalComponent;
    @ViewChild('smartTrackInfo') smartTrackInfo: TrackInfoComponent;
    @ViewChild('smartSelectPerson') smartSelectPerson: SelectPersonComponent;

    @Output() done = new EventEmitter<any>();
    tabNum = 0;    //tabs面板的序列号

    title;
    isVisible = false;
    isOkLoading = false;
    validateForm: FormGroup;
    fileList: UploadFile[] = [];
    fileId = [];
    change_level = change_level;
    typeList = [];

    cID;
    userInfo;  //用户信息

    constructor(private fb: FormBuilder, private systemSer: SystemService,
                private sysChangeSer: SystemChangeService,
                private localStorage: LocalStorageService,
                private workSer: WorkService,
                private message: NzMessageService, private systemChangeSer: SystemChangeService) {
    }

    ngOnInit(): void {
        this.userInfo = this.localStorage.retrieve('userInfo');
        console.log(this.userInfo);
        this.initForm();
        this.getType();
    }

    //初始化
    initForm() {
        this.validateForm = this.fb.group({
            manageUserId: [this.userInfo.userId],
            manageUserName: [this.userInfo.userName],
            organizationId: [this.userInfo.organizationId],
            organizationName: [this.userInfo.organizationName],
            type: ['1', [Validators.required]],
            classifyId: [null, [Validators.required]],
            status: ['1'],
            title: ['变更'],
            changeTime: [null],
            projectId: [null],
            projectName: [null],
            verifyUserId: [null],
            verifyUserName: [null],
            description: [null],
        });
    }

    //变更分类
    getType() {
        this.systemChangeSer.findByType('sys_change_type').subscribe(
            (res) => {
                if (res.data) {
                    this.typeList = res.data;
                } else {
                    this.message.warning('暂无变更类型');
                }
            }
        );
    }

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

    showEditModal(data, title) {
        this.isVisible = true;
        this.title = title;
        this.cID = data.id;
        this.getDetail();
    }

    //查询变更详情
    getDetail() {
        this.sysChangeSer.find(this.cID).subscribe(
            (res) => {
                res.data.type += '';
                res.data.status += '';
                this.validateForm.patchValue(res.data);
            }
        );
    }

    handleCancel() {
        this.isVisible = 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.validateForm.patchValue({
            status: status
        });
        this.isOkLoading = true;
        this.validateForm.patchValue({
            changeTime: new Date(this.validateForm.value.changeTime).getTime()
        });
        if (this.title.includes('新增')) this.create();
        if (this.title.includes('提交审核')) this.update();
    }

    create() {
        this.validateForm.addControl('fileId', new FormControl(this.fileId.join(',')));
        this.systemChangeSer.sysChangeSave(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.systemChangeSer.sysChangeUpdate(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();
    }

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

    //选择公司
    showCompany() {
        this.smartCompanyModal.showModal();
    }

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

    //选择团队负责人
    showPeoplemodal() {
        this.smartSelectPerson.showModal('选择审批人', null);
    }

    setPeolpe(e) {
        console.log(e);
        const d = {
            verifyUserName: e[0].name,
            verifyUserId: e[0].id
        };
        this.validateForm.patchValue(d);
    }

}
