import { Component, OnInit, TemplateRef, ViewContainerRef } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzFormatEmitEvent, NzTreeComponent, NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { NzModalService } from 'ng-zorro-antd/modal';
import { AdduserComponent } from './adduser/adduser.component';
import { NzMessageService } from 'ng-zorro-antd/message';
import { HttpClient } from '@angular/common/http';
import { EdituserComponent } from './edituser/edituser.component';
import { TreeService } from 'src/app/service/tree.service';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss']
})
export class UserComponent implements OnInit {
  validateForm!: FormGroup;
  constructor(private fb: FormBuilder, private modal: NzModalService, private viewContainerRef: ViewContainerRef, private message: NzMessageService, private http: HttpClient, private toTree: TreeService) { }

  level
  getAllUrl
  addUrl
  editUrl
  deleteUrl
  CountsByOrganizations
  ngOnInit(): void {
    this.validateForm = this.fb.group({
      search: [null]
    });
    this.level = JSON.parse(sessionStorage.getItem("userdata")).organization.level
    if (this.level == 1) {
      this.getAllUrl = '/api/services/app/User/GetAll'
      this.addUrl = '/api/services/app/User/Create'
      this.editUrl = '/api/services/app/User/Update'
      this.deleteUrl = '/api/services/app/User/Delete'
      this.CountsByOrganizations = '/api/services/app/User/GetCountsByOrganizations'
    } else {
      this.getAllUrl = '/api/services/app/EdittingUser/GetAll'
      this.addUrl = '/api/services/app/EdittingUser/Create'
      this.editUrl = '/api/services/app/EdittingUser/Update'
      this.deleteUrl = '/api/services/app/EdittingUser/Delete'
      this.CountsByOrganizations = '/api/services/app/EdittingUser/GetCountsByOrganizations'
    }
    this.getAllOrganization()
    this.getAllRoles()
  }
  nzSelectedKeys: any[] = []
  defaultExpandedKeys = [];
  IsContainsChildren = true
  searchValue = '';
  totalCount: string
  //获取所有用户
  usersLIst: any = []
  usersNum: string
  OrganizationUnitId
  loading: boolean;
  organizationsList = []
  getAllUsers() {
    this.loading = true
    let params = {
      Keyword: this.validateForm.value.search ? this.validateForm.value.search : '',
      SkipCount: String(this.SkipCount),
      MaxResultCount: String(this.MaxResultCount),
      OrganizationUnitId: this.OrganizationUnitId,
      IsContainsChildren: String(this.IsContainsChildren)
    }
    this.http.get(this.getAllUrl, {
      params: params
    }).subscribe((data: any) => {
      this.usersLIst = data.result.items
      this.usersNum = data.result.totalCount
      console.log('所有用户', this.usersLIst)
      this.loading = false
    })
  }
  SkipCount: number = 0  //0 16 32 48 
  MaxResultCount: number = 16
  pageChange($event) {
    this.SkipCount = ($event - 1) * this.MaxResultCount
    this.getAllUsers()
  }

  listOfData: any = []
  //获取角色列表
  async getAllRoles() {
    let params = {
      SkipCount: '0',
      MaxResultCount: '999',
      ContainsBuiltins: 'true'
    }
    await new Promise<void>((resolve, reject) => {
      this.http.get('/api/services/app/Role/GetAll', {
        params: params
      }).subscribe((data: any) => {
        resolve(data)
        this.listOfData = data.result.items
      })
    })
  }
  //获取所有组织机构
  nodes: any = []
  async getAllOrganization() {
    let OrganizationUnitId = sessionStorage.getItem('isGasStation') == 'true' ? JSON.parse(sessionStorage.getItem('userdataOfgasstation')).organization.id : JSON.parse(sessionStorage.getItem('userdata')).organization.id
    let params = {
      OrganizationUnitId: OrganizationUnitId,
      IsContainsChildren: "true"
    }
    await new Promise<void>((resolve, reject) => {
      this.http.get('/api/services/app/Organization/GetAll', {
        params: params
      }).subscribe(async (data: any) => {
        await this.getuser(data.result.items)
        resolve(data)
        this.getAllUsers()
      })
    })
  }
  async getuser(e) {
    let OrganizationUnitId = sessionStorage.getItem('isGasStation') == 'true' ? JSON.parse(sessionStorage.getItem('userdataOfgasstation')).organization.id : JSON.parse(sessionStorage.getItem('userdata')).organization.id
    let params = {
      OrganizationUnitId: OrganizationUnitId,
      IsContainsChildren: String(this.IsContainsChildren)
    }
    await new Promise<void>((resolve, reject) => {
      this.http.get(this.CountsByOrganizations, {
        params: params
      }).subscribe((data: any) => {
        resolve(data)
        this.organizationsList = data.result
        const arrs = e.map(item => {
          const data = this.organizationsList.find(i => item.id == i.organizationId)
          return {
            ...item,
            products: data ? data : false
          }
        })

        for (let index = 0; index < arrs.length; index++) {
          arrs[index].title = arrs[index].displayName
          arrs[index].key = arrs[index].id
        }

        this.nodes = [...this.toTree.toTree(arrs)]
        this.defaultExpandedKeys = [this.nodes[0].id]
        this.nzSelectedKeys = [this.nodes[0].id]
        this.OrganizationUnitId = [this.nodes[0].id]
        console.log(this.nodes, 9000);
      })
    })
  }
  xxx(node){
    console.log(node)
  }
  //搜索框提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    this.getAllUsers()
  }
  nzClick(event: NzFormatEmitEvent) {
    console.log(event);
    this.nzSelectedKeys[0] = event.node.origin.id
    this.nzSelectedKeys = [...this.nzSelectedKeys]
    this.OrganizationUnitId = event.node.origin.id
    this.getAllUsers()
  }
  //新增用户
  addUser(): void {
    const modal = this.modal.create({
      nzTitle: '新增用户',
      nzContent: AdduserComponent,
      nzViewContainerRef: this.viewContainerRef,
      nzWidth: 450,
      nzMaskClosable: false,
      nzComponentParams: {
        title: '',
        subtitle: ''
      },
      nzOnOk: async () => {
        if (instance.validateForm.valid) {
          await new Promise(resolve => {
            let body = {
              userName: instance.validateForm.value.account,
              name: instance.validateForm.value.name,
              organizationUnitId: Number(instance.validateForm.value.organization),
              roleNames: instance.validateForm.value.role,
              phoneNumber: instance.validateForm.value.phonenum,
              isActive: true
            }
            this.http.post(this.addUrl, body).subscribe(data => {
              resolve(data)
              this.message.create('success', '创建成功!');
              this.SkipCount = 0
              this.getAllUsers()
              return true
            }, err => {
              resolve(err)
              this.message.create('warning', err.error.error.message);
              return false
            })
          })
        } else {
          this.message.create('warning', '请填写完整!');
          return false
        }
      }
    });
    const instance = modal.getContentComponent();
    modal.afterOpen.subscribe(() => console.log('[afterOpen] emitted!'));
    modal.afterClose.subscribe(result => console.log('[afterClose] The result is:', result));
  }

  //编辑用户
  editUser(data): void {
    console.log(data)
    const modal = this.modal.create({
      nzTitle: '编辑用户',
      nzContent: EdituserComponent,
      nzViewContainerRef: this.viewContainerRef,
      nzWidth: 450,
      nzMaskClosable: false,
      nzComponentParams: {
        data: data,
        listOfData: this.listOfData,
        nodes: this.nodes
      },
      nzOnOk: async () => {
        if (instance.validateForm.valid) {
          await new Promise(resolve => {
            let body = {
              id: data.id,
              userName: instance.validateForm.value.account,
              name: instance.validateForm.value.name,
              organizationUnitId: instance.validateForm.value.organization,
              roleNames: instance.validateForm.value.role,
              phoneNumber: instance.validateForm.value.phonenum,
              isActive: true
            }
            this.http.put(this.editUrl, body).subscribe(data => {
              resolve(data)
              this.message.create('success', '编辑成功!');
              this.getAllUsers()
              return true
            }, err => {
              resolve(err)
              this.message.create('warning', '编辑失败');
              return false
            })
          })
        } else {
          this.message.create('warning', '请填写完整!');
          return false
        }
      }
    });
    const instance = modal.getContentComponent();
  }

  //重置密码
  resetPassword(item) {
    console.log(item)
    this.modal.confirm({
      nzTitle: `确定要重置${item.userName}这个账户的密码吗?`,
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOnOk: () => {
        let body = {
          userId: item.id
        }
        this.http.post('/api/services/app/User/ResetPassword', body).subscribe(data => {
          this.message.create('success', '重置成功!');
        })
      },
      nzCancelText: '取消',
      nzOnCancel: () => {

      }
    });
  }

  //提交审核
  audit(data, type) {
    if (type && data.auditStatus == 5) {//提交审核
      this.message.create('warning', '审核完成的不能重复提交,请编辑后提交');
      return
    }
    let url
    type ? url = '/api/services/app/EdittingUser/Commit' : url = '/api/services/app/EdittingUser/Uncommit'
    this.http.post(url, '', {
      params: {
        id: data.id
      }
    }).subscribe(data => {
      this.message.create('success', type ? '提交审核成功' : '撤销审核成功');
      this.getAllUsers()
    }, err => {
      this.message.create('error', type ? '提交审核失败' : '撤销审核失败');
    })
  }

  //停用启用
  cancel(data, type) {
    let url
    if (this.level == 1) {
      type ? url = '/api/services/app/User/Activate' : url = '/api/services/app/User/DeActivate'

    } else {
      type ? url = '/api/services/app/EdittingUser/Activate' : url = '/api/services/app/EdittingUser/DeActivate'
    }
    let body = {
      id: data.id
    }
    this.http.post(url, body).subscribe(data => {
      this.message.create('success', type ? '启用成功' : '停用成功');
      this.getAllUsers()
    }, err => {
      this.message.create('error', type ? '启用失败' : '停用失败');
    })
  }


  //删除
  delete(item) {
    this.modal.confirm({
      nzTitle: `确定要注销${item.userName}这个账户吗?`,
      nzOkText: '确定',
      nzOkType: 'danger',
      nzOnOk: () => {
        this.http.delete(this.deleteUrl, {
          params: {
            Id: item.id
          }
        }).subscribe(data => {
          this.message.create('success', '注销成功!');
          this.getAllUsers()
        })
      },
      nzCancelText: '取消',
      nzOnCancel: () => {

      }
    });
  }
}