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;
    initGroupList = [];  //分组权限
    viewGroupList = [];  //分组权限

    initTempGroupList = [];   //模版权限
    viewTempGroupList = [];

    initModuleList = [];   //菜单权限
    dataModuleList = [];   //菜单数据

    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();
        this.getTempGroup();
    }

    ininForm() {
        this.viewGroupList = [];
        this.viewTempGroupList = [];
        this.validateForm = this.fb.group({
            name: [null, [Validators.required, Validators.maxLength(20)]],
            comment: [null, [Validators.required, Validators.maxLength(30)]],
        });
    }

    //获取菜单栏
    getMenu() {
        this.systemSer.getMenuBySeparation().subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.initModuleList = res.data;
                    this.addInit();
                }
            }
        );
    }

    //获取资源分组
    getGroup() {
        this.overAllSer.getEditGroups(0).subscribe(
            (res) => {
                this.initGroupList = res.data;
                this.viewGroupList = res.data;
                this.viewGroupList.forEach(e => {
                    e.checked = false;
                });
            }
        );
    }

    //获取模版分组
    getTempGroup() {
        this.overAllSer.getEditGroups(1).subscribe(
            (res) => {
                this.initTempGroupList = res.data;
                this.viewTempGroupList = res.data;
                this.viewTempGroupList.forEach(e => {
                    e.checked = false;
                });
            }
        );
    }

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

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

    //新增初始化
    addInit() {
        let list = this.commonSer.listToTree('id', 'parentId', this.initModuleList);
        list.forEach(res => {
            res.title = res.name;
            res.key = res.id;
            if (res.children && res.children.length > 0) {
                res.children.forEach((child) => {
                    child.title = child.name;
                    child.key = child.id;
                    child.isLeaf = true;
                });
            }
        });
        this.toNode(list);
    }

    //编辑
    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);
                    this.editInit(res.data);
                }
            }
        );
    }

    //编辑初始化
    editInit(data) {

        if (data.resources.length > 0) {
            const modulrArr = data.resources.map(res => {
                return res.groupId;
            });
            //分组回显
            this.viewGroupList = this.initGroupList.map(e => {
                const data = {
                    groupid: e.groupid,
                    name: e.name,
                    checked: false,
                };

                if (modulrArr.indexOf(e.groupid) > -1) {
                    data.checked = true;
                }
                return data;
            });

            //模版分组回显
            this.viewTempGroupList = this.initTempGroupList.map(e => {
                const data = {
                    groupid: e.groupid,
                    name: e.name,
                    checked: false,
                };

                if (modulrArr.indexOf(e.groupid) > -1) {
                    data.checked = true;
                }
                return data;
            });
        } else {
            this.viewGroupList = this.initGroupList;
            this.viewTempGroupList = this.initTempGroupList;
        }

        this.dataModuleList = data.modules;
        //菜单回显
        this.systemSer.getMenuBySeparation().subscribe(
            (res) => {
                let list = res.data;
                list.forEach(e => {
                    e.title = e.name;
                    e.key = e.id;
                    e.isChecked = false;
                    if (e.url) {
                        e.isLeaf = true;
                    }
                    if (data.modules.length > 0 && data.modules.indexOf(e.id) > -1) {
                        e.isChecked = true;
                    }
                });
                list = this.commonSer.listToTree('id', 'parentId', list);
                this.toNode(list);
            }
        );

    }

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

    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.viewGroupList.forEach(e => {
            if (e.checked) {
                const data = {
                    groupId: e.groupid,
                    groupName: e.name
                };
                resourceArr.push(data);
            }
        });
        this.viewTempGroupList.forEach(e => {
            if (e.checked) {
                const data = {
                    groupId: e.groupid,
                    groupName: e.name
                };
                resourceArr.push(data);
            }
        });

        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.dataModuleList,
            resources: resourceArr
        };
        this.systemSer.addRole(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isVisible = false;
                    this.add.emit();
                    this.ininForm();
                    this.message.success('新增成功');
                }
            }
        );
    }

    //编辑
    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.dataModuleList,
            resources: resourceArr
        };
        this.systemSer.editRole(data).subscribe(
            (res) => {
                if (res.errCode == 10000) {
                    this.isVisible = false;
                    this.add.emit();
                    this.ininForm();
                    this.message.success('修改成功');
                }
            }
        );
    }

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