import {Component, OnInit, ViewChild} from '@angular/core';
import {NzMessageService, NzModalService, NzTreeNode, NzTreeNodeOptions} from 'ng-zorro-antd';
import {SystemService} from '../system.service';
import {UserComponent} from '../modal/user/user.component';
import {GroupModalComponent} from '../modal/group-modal/group-modal.component';
import {SelectRoleComponent} from '../../modal/select-role/select-role.component';
import {CommonService} from '../../shared/common/common.service';
import {pageSize, SERVER_API_URL_COMS} from '../../app.constants';
import 'rxjs/Rx' ;
import {UploadComponent} from '../../work/modal/upload/upload.component';

@Component({
    selector: 'jhi-group',
    templateUrl: './group.component.html',
    styles: []
})
export class GroupComponent implements OnInit {
    @ViewChild('smartSelectRole') smartSelectRole: SelectRoleComponent;
    @ViewChild('power') power;
    @ViewChild('smartUser') smartUser: UserComponent;
    @ViewChild('smartGroupModal') smartGroupModal: GroupModalComponent;
    @ViewChild("smartUpload") smartUpload:UploadComponent;

    dataSet: any[];
    groupList: any[];
    allChecked = false;
    disabledButton = true;
    indeterminate = false;
    checkedNumber = 0;
    nodes: any[];
    isVisible = true;
    userId;
    setType;
    selectList = [];
    name = null;  //搜索文字

    organizationId = null;  //组织ID

    pageNum = 1;
    pageSize = pageSize;
    totalNum;

    constructor(private systemSer: SystemService, private message: NzMessageService,
                private modalSer: NzModalService, private commonSer: CommonService) {
    }

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

    currentPageDataChange($event: Array<{ checked: boolean }>): void {
        this.dataSet = $event;
    }

    selectItem(item, e) {
        if (e) {
            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.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;
    }

    mouseAction(name: string, e: any): void {
        console.log(name, e);
    }

    ngOnInit() {
        this.getUser();
        this.getGroup();
    }

    getUser() {
        const data = {
            'search': this.name = this.name == '' ? null : this.name,
            'organizationId': this.organizationId = this.organizationId == '' ? null : this.organizationId,
            'pageNum': this.pageNum,
            'pageSize': this.pageSize
        };
        this.systemSer.user(data).subscribe(
            (res) => {
                this.dataSet = res.data.data;
                this.totalNum = res.data.totalCount;
            }
        );
    }

    changePage(e) {
        this.pageNum = e;
        this.getUser();
    }

    getOrg(e) {
        console.log(e);
        this.organizationId = e.key;
        this.getUser();
    }

    //组织信息
    getGroup() {
        this.systemSer.organization().subscribe(
            (res) => {
                this.groupList = res.data;
                this.groupList.forEach(
                    res => {
                        res.title = res.name;
                        res.key = res.id;
                    }
                );
                this.nodeTree();
            }
        );
    }

    nodeTree() {
        const tree = this.commonSer.listToTree('id', 'parentId', this.groupList,);
        const list = tree.map(res => {
            return new NzTreeNode(res);
        });
        this.nodes = list;
    }

    showModal(): void {
        this.isVisible = true;
    }

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

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

    //新增用户
    showUserModal() {
        this.smartUser.showAddModal(this.groupList, '新增用户');
    }

    //编辑用户
    showEditModal(item) {
        this.smartUser.showEditModal(this.groupList, '编辑用户', item.id);
    }

    //删除用户--单个
    deleteUser(item) {
        this.modalSer.confirm({
            nzTitle: '删除',
            nzContent: '<b style="color: red">确定删除该用户吗</b>',
            nzOkText: '确定',
            nzCancelText: '取消',
            nzOnOk: () => {
                const data = {
                    id: item.id
                };
                this.systemSer.deleteUser(data).subscribe(
                    (res) => {
                        if (res.data == 1) {
                            this.getUser();
                        }
                    }
                );
            },
            nzOnCancel: () => {
            }
        });
    }

    //删除用户-- 批量
    batchDelete() {
        let bool = false;
        this.dataSet.forEach(e => {
            if (e.checked) {
                bool = true;
            }
        });
        if (!bool) {
            this.message.warning('请选择需要删除的用户');
            return false;
        }
        let arr = [];
        this.dataSet.forEach(e => {
            if (e.checked) {
                arr.push(e.user.id);
            }
        });
        this.commonSer.confirmThing('删除', '确定删除选择的用户', () => {
            this.systemSer.batchDeleteUser(arr).subscribe(
                (res) => {
                    if (res.errCode == 10000) {
                        this.getUser();
                    }
                }
            );
        });
    }

    //新增部门
    showGroupModal() {
        this.smartGroupModal.showAddModal(this.groupList,"新增部门");
    }

    //编辑部门
    showEditGroupModal(item) {
        this.smartGroupModal.showEditModal(this.groupList,"编辑部门",item.key);
    }

    //删除部门
    deleteGroup(item) {
        this.commonSer.confirmThing("删除","确认删除该组织",()=>{
            this.systemSer.deleteOrg(item.key).subscribe(
                (res)=>{
                    if(res.errCode == 10000){
                        this.message.success("删除成功");
                        this.getGroup();
                    }else{
                        this.message.error(res.errMsg);
                    }
                }
            )
        })
    }

    //授予角色
    grantRole(data) {
        this.setType = '单个';
        this.userId = data.id;
        this.smartSelectRole.showModal('选择角色', this.userId);
    }

    //设置用户角色
    setRole(event) {
        if (this.setType == '批量') {
            const data = {
                userId: this.selectList.map(
                    e => {
                        return e.id;
                    }
                ),
                roles: event.map(e => {
                    return e.id;
                }),
            };
            this.systemSer.batchUserToAuth(data).subscribe(
                (res) => {
                    if (res.errCode == 10000) {
                        this.getUser();
                        this.message.success('授予角色成功');
                    } else {
                        this.message.error(res.errMsg);
                    }
                }
            );
        }
        if (this.setType == '单个') {
            const data = {
                userId: this.userId,
                roles: event.map(e => {
                    return e.id;
                }),
            };
            this.systemSer.aloneUserToAuth(data).subscribe(
                (res) => {
                    if (res.errCode == 10000) {
                        this.getUser();
                        this.message.success('授予角色成功');
                    } else {
                        this.message.error(res.errMsg);
                    }
                }
            );
        }
    }

    //选择角色
    selectRoleModal() {
        this.setType = '批量';
        this.smartSelectRole.showModal('选择角色', null);
    }

    //下载模版
    downLoad(){
      this.systemSer.downloadTemplate("",SERVER_API_URL_COMS + "/user/downloadTemplate/").subscribe(
          data=>{
              this.commonSer.downloadFile("模版",data)
          }
      );
    }

    //导入用户
    showUploadModalUser(){
        this.smartUpload.showModal("上传用户文件");
    }

    //导入组织
    showUploadModalOrg(){
        this.smartUpload.showModal("上传组织文件");
    }

}
