import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {
    AbstractControl,
    FormBuilder,
    FormControl,
    FormGroup,
    Validators
} from '@angular/forms';
import {SystemService} from '../../system.service';
import {NzMessageService, NzTreeNode} from 'ng-zorro-antd';
import {LayoutService} from '../../../layouts/layout.service';
import {CommonService} from '../../../shared/common/common.service';
import {OverAllService} from '../../../overAll/overAll.service';

@Component({
    selector: 'smart-role',
    templateUrl: './role.component.html',
    styles: [
            `
            .tree-div p {
                margin: 0;
            }`
    ]
})
export class RoleComponent implements OnInit {
    @Output() add = new EventEmitter<any>();

    title;
    isVisible = false;
    validateForm: FormGroup;
    menuList;

    nodes;
    nodeList;
    roleId;
    groupList = [];
    moduleList = [];   //菜单权限
    resourceList = [];   //主机分组权限

    constructor(private fb: FormBuilder, private message: NzMessageService, private overAllSer: OverAllService,
                private systemSer: SystemService, private layoutSer: LayoutService, private commonSer: CommonService) {
    }

    ngOnInit() {
        this.ininForm();
        this.getMenu();
        this.getGroup();
    }

    ininForm() {
        this.validateForm = this.fb.group({
            name: [null, [Validators.required]],
            status: [null, [Validators.required]],
            comment: [null, [Validators.required]],
        });
    }

    //获取菜单栏
    getMenu() {
        this.systemSer.getMenuBySeparation().subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.menuList = this.commonSer.listToTree('id', 'parentId', res.data);
                    this.menuList.forEach(res => {
                        res.title = res.name;
                        res.key = res.id;
                        res.children.forEach((child) => {
                            child.title = child.name;
                            child.key = child.id;
                            child.isLeaf = true;
                        });
                    });
                    this.toNode(this.menuList);
                }
            }
        );
    }

    //获取分组
    getGroup() {
        this.groupList = [];
        this.overAllSer.findGroup().subscribe(
            (res) => {
                this.groupList = res.data;
                this.groupList.forEach(e => {
                    e.checked = false;
                });
            }
        );
    }

    toNode(data) {
        this.nodes = data.map(res => {
            return new NzTreeNode(res);
        });
    }

    //获取所有分组

    showAddModal(): void {
        this.title = '新增角色';
        this.isVisible = true;
    }

    showEditModal(id) {
        this.title = '编辑角色';
        this.isVisible = true;
        this.roleId = id;
        this.systemSer.getRole(id).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    const data = res.data.role;
                    data.status += '';
                    this.validateForm.patchValue(data);
                }
            }
        );
    }

    handleCancel(): void {
        this.isVisible = false;
    }

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

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

        let resourceArr = [];
        this.resourceList.forEach(e=>{
            if(e.checked){
                resourceArr.push(e.id);
            }
        })

        if (this.title == '新增角色') {
            this.create(resourceArr);
        }
        if (this.title == '编辑角色') {
            this.update(resourceArr);
        }
    }

    //新增
    create(resourceArr) {
        const data = {
            role: {
                name: this.validateForm.value.name,
                status: this.validateForm.value.status,
                comment: this.validateForm.value.comment,
            },
            modules: this.moduleList,
            resources: resourceArr
        };
        this.systemSer.addRole(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isVisible = false;
                    this.add.emit();
                    this.ininForm();
                    this.message.success('新增成功');
                } else {
                    this.message.error(res.errMsg);
                }
            }
        );
    }

    //编辑
    update(resourceArr) {
        const data = {
            role: {
                id: this.roleId,
                name: this.validateForm.value.name,
                status: this.validateForm.value.status,
                comment: this.validateForm.value.comment,
            },
            modules: this.moduleList,
            resources: resourceArr
        };
        this.systemSer.editRole(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isVisible = false;
                    this.add.emit();
                    this.ininForm();
                    this.message.success('修改成功');
                } else {
                    this.message.error(res.errMsg);
                }
            }
        );
    }

    selectCheckTree(e) {
        if (e.node.isChecked) {
            this.moduleList.push(e.node.key);
        } else {
            const index = this.moduleList.indexOf(e.node.key);
            this.moduleList.splice(index, 1);
        }
    }
}
