import {Component, OnInit} from '@angular/core';
import {environment} from "../../../../environments/environment";
import {
  FormsModule,
  ReactiveFormsModule,
  UntypedFormBuilder,
  UntypedFormControl,
  UntypedFormGroup,
  Validators
} from '@angular/forms';
import {HttpClient} from "@angular/common/http";
import {NzMessageService} from "ng-zorro-antd/message";
import {NzModalComponent, NzModalModule, NzModalService} from "ng-zorro-antd/modal";
import {ADMIN_INFO_OBJECT} from "../../../services/local-storage.namespace";
import {ValidatorsService} from "../../../services/validators.service";
import {NzUploadComponent, NzUploadFile} from "ng-zorro-antd/upload";
import {Observable, Observer} from "rxjs";
import {RouterLink} from "@angular/router";
import {SalesmanStatusPipe} from "../../../pipes/salesman-status.pipe";
import {DatePipe, NgForOf, NgIf} from "@angular/common";
import {BreadcrumbComponent} from "../../common/breadcrumb/breadcrumb.component";
import {NzFormDirective, NzFormLabelComponent, NzFormModule} from "ng-zorro-antd/form";
import {NzColDirective, NzRowDirective} from "ng-zorro-antd/grid";
import {NzOptionComponent, NzSelectComponent} from "ng-zorro-antd/select";
import {NzInputDirective} from "ng-zorro-antd/input";
import {NzButtonComponent} from "ng-zorro-antd/button";
import {NzIconDirective} from "ng-zorro-antd/icon";
import {NzCellFixedDirective, NzTableComponent, NzTableModule, NzThMeasureDirective} from "ng-zorro-antd/table";
import {AgentStatusPipe} from "../../../pipes/agent-status.pipe";
import {NzBreadCrumbComponent, NzBreadCrumbItemComponent} from "ng-zorro-antd/breadcrumb";
import {NzContentComponent, NzLayoutComponent, NzSiderComponent} from "ng-zorro-antd/layout";
import {NzSwitchComponent} from "ng-zorro-antd/switch";
import {NzDividerComponent} from "ng-zorro-antd/divider";
import {NzTooltipDirective} from "ng-zorro-antd/tooltip";
import {BrowserStorageService} from "../../../utils/localStorage.service";
import {NzSpinModule} from "ng-zorro-antd/spin";
import {NzRadioComponent, NzRadioGroupComponent} from "ng-zorro-antd/radio";
import {NzDatePickerModule} from "ng-zorro-antd/date-picker";

@Component({
  selector: 'app-system-user',
  standalone: true,
  imports: [
    RouterLink,
    SalesmanStatusPipe,
    DatePipe,
    BreadcrumbComponent,
    NzFormDirective,
    NzRowDirective,
    NzColDirective,
    NzSelectComponent,
    NzOptionComponent,
    ReactiveFormsModule,
    NgIf,
    NzInputDirective,
    NzButtonComponent,
    NzIconDirective,
    NzTableComponent,
    NzThMeasureDirective,
    NzCellFixedDirective,
    NgForOf,
    AgentStatusPipe,
    NzBreadCrumbItemComponent,
    NzBreadCrumbComponent,
    NzSiderComponent,
    NzSwitchComponent,
    FormsModule,
    NzLayoutComponent,
    NzContentComponent,
    NzModalComponent,
    NzUploadComponent,
    NzFormLabelComponent,
    NzDividerComponent,
    NzTooltipDirective,
    NzModalModule,
    NzTableModule,
    NzFormModule,
    NzSpinModule,
    NzRadioGroupComponent,
    NzRadioComponent,
    NzDatePickerModule
  ],
  templateUrl: './system-user.component.html',
  styleUrl: './system-user.component.less'
})
export class SystemUserComponent implements OnInit {
  FILE_URL = environment.imageUrl;
  avatarImg = '';
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  requestData = [];
  loading = true;
  isLoadingSearch = false;
  isLoadingDelete = false;
  isVisible = false;
  isVisibleEdit = false;
  isOkLoading = false;
  validateForm: UntypedFormGroup;
  WEB_SERVE_URL = environment.baseUrl;
  title: any = '';
  isSpinning = false;
  id = '';
  selectedValueSearch = '';
  manager = false;
  isAnonymity = false;
  optionList: any[] = [];
  companyList: any[] = [];
  isLoading = false;
  isCompanyoading = false;
  date = null;
  secUser: any = {};
  checkPassword;

  // tslint:disable-next-line:variable-name
  BTN_systemuser_add;
  // tslint:disable-next-line:variable-name
  BTN_systemuser_edit;
  // tslint:disable-next-line:variable-name
  BTN_systemuser_delete;

  constructor(
    private http: HttpClient, // http请求
    private message: NzMessageService, // 信息提示
    private fb: UntypedFormBuilder, // 表单
    private modalService: NzModalService, // 对话框
    private getData: BrowserStorageService, // 请求数据字典查询
    private store: BrowserStorageService,
  ) {
  }

  ngOnInit() {
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < this.store.get(ADMIN_INFO_OBJECT)['buttonList'].length; i++) {
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_systemuser_add') {
        this.BTN_systemuser_add = 1;
      }
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_systemuser_edit') {
        this.BTN_systemuser_edit = 1;
      }
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_systemuser_delete') {
        this.BTN_systemuser_delete = 1;
      }
    }

    // 判断表单
    this.validateForm = this.fb.group({
      organizationId: [null, [Validators.required]],
      checked: [null],
      userName: [null, [Validators.required, ValidatorsService.maxLength(20)]],
      loginName: [null, [Validators.required, ValidatorsService.minLength(3), ValidatorsService.maxLength(20)]],
      password: [null, [Validators.required, ValidatorsService.minLength(6), ValidatorsService.maxLength(40)]],
      telephone: [null],
      roleId: [null, [Validators.required]],
    });
    // 调用请求方法
    this.goRequest();
    // 调用请求政策下拉列表
    this.goRequestpoducetList();
    this.goRequestCompanyList();
  }


  confirmationValidator = (control: UntypedFormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return {required: true};
    } else if (control.value !== this.validateForm.controls['password'].value) {
      return {confirm: true, error: true};
    }
    return {};
  }

  // 角色
  goRequestpoducetList() {
    // tslint:disable-next-line:max-line-length
    this.http.get(this.WEB_SERVE_URL + '/secRole/getAllRole?companyId=' + this.store.get(ADMIN_INFO_OBJECT)['bsCompany'].id + '&primaryRole=0&templetType=0').subscribe(data => {
      if (data['return_code'] === '000000') {
        this.optionList = data['return_data'];
        this.isLoading = false;
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  // 获取部门列表
  goRequestCompanyList() {
    this.http.get(this.WEB_SERVE_URL + '/bsOrganization/getOrganizationList?companyId=' + this.store.get(ADMIN_INFO_OBJECT)['bsCompany'].id).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.companyList = data['return_data'];
        this.isCompanyoading = false;
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  // 查询
  goRequest(reset: boolean = false) {
    this.loading = false;
    if (reset) {
      this.pageIndex = 1;
    }
    if (this.selectedValueSearch == null) {
      this.selectedValueSearch = '';
    }
    this.http.get(this.WEB_SERVE_URL + '/secUser/getUserList?pageNum=' + this.pageIndex + '&pageSize=' + this.pageSize + '&userName=' + this.title + '&organizationId=' + this.selectedValueSearch + '&companyId=' + this.store.get(ADMIN_INFO_OBJECT)['bsCompany'].id).subscribe(data => {
      this.isLoadingSearch = false;
      if (data['return_code'] === '000000') {
        console.log(data);
        this.requestData = data['return_data'].list;
        this.total = data['return_data'].total;
      } else {
        this.message.create('error', data['return_msg']);

      }
    });
  }

  // 搜索
  goSearch() {
    this.isLoadingSearch = true;
    this.goRequest();
  }

  // 弹出添加弹框
  goAddShow() {
    this.avatarImg = '';
    this.validateForm.reset();
    this.isVisible = true;
  }

  // 确定添加政策按钮
  handleOk(value: any): void {
    // tslint:disable-next-line:forin
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (this.validateForm.status == null || this.validateForm.status !== 'VALID') {
      this.modalService.info({
        nzTitle: '提示',
        nzContent: '有未填写的必填项',
      });
      return;
    }
    if (value.checked == null) {
      value.checked = false;
    }
    // 定义请求数据
    const params = {
      companyId: this.store.get(ADMIN_INFO_OBJECT)['bsCompany'].id,
      organizationId: value.organizationId,
      manager: value.checked,
      avatar: this.avatarImg,
      userName: value.userName,
      loginName: value.loginName,
      password: value.password,
      telephone: value.telephone,
      roleId: value.roleId,
    };
    this.isOkLoading = true;
    this.http.post(this.WEB_SERVE_URL + '/secUser/addUser', params).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.message.create('success', `新增成功！`);
        this.goRequest();
        this.isVisible = false;
      } else {
        this.message.create('warning', data['return_msg']);
      }
    }, error => {
      this.isOkLoading = false;
      this.message.create('error', `未知错误！`);
    });
  }

  // 清空
  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    // tslint:disable-next-line:forin
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }

  // 取消按钮
  handleCancel(): void {
    this.isVisible = false;
  }

  // 修改确定按钮
  handleOkEdit(value: any) {
    // tslint:disable-next-line:forin
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.status == null || this.validateForm.status !== 'VALID') {
      this.modalService.info({
        nzTitle: '提示',
        nzContent: '有未填写的必填项',
      });
      return;
    }
    this.isOkLoading = true;
    this.secUser.organizationId = value.organizationId;
    this.secUser.avatar = this.avatarImg;
    this.secUser.userName = value.userName;
    this.secUser.password = value.password;
    this.secUser.telephone = value.telephone;
    this.secUser.roleId = value.roleId;

    this.http.post(this.WEB_SERVE_URL + '/secUser/editUser', this.secUser).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.message.create('success', `修改成功！`);
        this.goRequest();
      } else {
        this.message.create('warning', data['return_msg']);
      }
    }, error => {
      this.isOkLoading = false;
      this.message.create('error', `未知错误！`);
    });
  }

  // 修改取消按钮
  handleCancelEdit(): void {
    this.isVisibleEdit = false;
  }

  // 删除提示
  showDeleteConfirm(id): void {
    this.modalService.confirm({
      nzTitle: '您确定要删除吗?',
      nzOkText: '是',
      nzOnOk: () => this.goDelete(id),
      nzCancelText: '否',
    });
  }

  // 查询详情
  goDetails(userId) {
    this.id = userId;
    this.isVisibleEdit = true;
    this.http.get(this.WEB_SERVE_URL + '/secUser/getUserView?userId=' + userId).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.secUser = data['return_data'];
        this.avatarImg = data['return_data']['avatar'];

      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  // 删除
  goDelete(id) {
    this.isLoadingDelete = true;
    this.http.get(this.WEB_SERVE_URL + '/secUser/deleteUser?userId=' + id).subscribe(data => {
      this.isLoadingDelete = false;
      if (data['return_code'] === '000000') {
        this.message.create('success', '删除成功');
        // 调用请求方法
        this.goRequest();
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  /**
   * 图片上传前的校验
   * @param file
   * @param fileList
   */
  beforeUpload = (file: NzUploadFile, fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.message.error('图片格式错误! 请上传jpg、png格式的图片');
        observer.complete();
        return;
      }
      const isLt2M = file.size! / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.message.error('图片必须小于2MB!');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  };

  /**
   * 上传机构LOGO回调
   * @param info
   */
  avatarHandleChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        break;
      case 'done':
        this.avatarImg = info.file.response.return_data[0];
        break;
      case 'error':
        this.message.error('上传失败');
        break;
    }
  }

}
