import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {SystemService} from '../../system/system.service';

@Component({
    selector: 'smart-select-role',
    templateUrl: './select-role.component.html',
    styles: []
})
export class SelectRoleComponent implements OnInit {
    @Output() done = new EventEmitter<any>();

    dataSet: any = [];
    title;
    selectList = [];
    isVisible = false;
    isOkLoading = false;
    allChecked = false;
    checkedNumber = 0;
    disabledButton = true;
    indeterminate = false;
    userId;
    userRoleList = [];
    constructor(private systemSer: SystemService) {
    }

    checkAll(value: boolean): void {
        this.dataSet.forEach(data => data.checked = value);
        this.refreshStatus();
    }

    currentPageDataChange($event: Array<{ key1: string; key2: number; key3: string; key4: string; checked: boolean }>): void {
        this.dataSet = $event;
    }

    refreshStatus(): void {
        const allChecked = this.dataSet.every(value => value.checked === true);
        const allUnChecked = this.dataSet.every(value => !value.checked);
        this.allChecked = allChecked;
        this.indeterminate = (!allChecked) && (!allUnChecked);
        this.disabledButton = !this.dataSet.some(value => value.checked);
        this.checkedNumber = this.dataSet.filter(value => value.checked).length;
    }

    ngOnInit() {
    }

    initForm(){
        this.allChecked = false;
    }

    showModal(title,id) {
        this.title = title;
        this.isVisible = true;
        this.userId = id;
        this.systemSer.getRoleByUserId(this.userId).subscribe(
            (res)=>{
                this.userRoleList = res.data;
                this.getRole();
            }
        )
    }

    getRole() {
        this.systemSer.role().subscribe(
            (res) => {
                this.dataSet = res.data;
                this.dataSet.forEach(e=>{
                    if(this.userRoleList.indexOf(e.id) > -1){
                        e.checked = true;
                    }
                })
            }
        );
    }

    handleEditCancel(){
        this.isVisible = false;
        this.isOkLoading = false;
    }

    handEditleOk(){
        let arr = [];
        this.dataSet.forEach(e => {
            if (e.checked) {
                arr.push(e);
            }
        });
        this.done.emit(arr);
        this.allChecked = false;
        this.isVisible = false;
    }

}
