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;
    allChecked = false;
    checkedNumber = 0;
    disabledButton = true;
    indeterminate = false;
    userId;
    userRoleList = [];
    displayData: Array<{ key1: string; key2: number; key3: string; key4: string; checked: boolean }> = [];
    constructor(private systemSer: SystemService) {
    }

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

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

    selectItem(event,item){
        if(event){
            this.selectList.push(item);
        }else{
            this.selectList.forEach((value,index)=>{
                if(value.id == item.id){
                    this.selectList.splice(index,1)
                }
            })
        }
        this.refreshStatus()
    }

    refreshStatus(): void {
        const allChecked = this.displayData.every(value => value.checked === true);
        const allUnChecked = this.displayData.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() {
    }

    showModal(title,id) {
        this.title = title;
        this.isVisible = true;
        this.userId = id;
        const data = {
            userId:this.userId
        }
        this.systemSer.getRoleByUserId(data).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;
    }

    handEditleOk(){
        this.done.emit(this.selectList);
        this.isVisible = false;
    }

}
