// 袁野
// 2019-05-11
import {Component, OnInit} from '@angular/core';
import {PlatformLocation} from '@angular/common';
import {HttpClient} from '@angular/common/http';
import {NzMessageService, NzModalService, NzUploadFile} from 'ng-zorro-antd';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {Observable, Observer} from 'rxjs';
import {ValidatorsService} from '../../../services/validators.service';
import {LocalStorageService} from '../../../services/local-storage.service';
import {environment} from '../../../../environments/environment';
import { ADMIN_INFO_OBJECT } from '../../../services/local-storage.namespace';
import {CommonsService} from "../../../services/commons.service";

@Component({
  selector: 'app-system-user',
  templateUrl: './system-user.component.html',
  styleUrls: ['./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: FormGroup;
  WEB_SERVE_URL = environment.baseUrl;
  title: any = '';
  isSpinning = false;
  id = '';
  selectedValueSearch = '';
  manager = false;
  isAnonymity = false;
  optionList: string[] = [];
  companyList: string[] = [];
  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;

  userLabelArray = [];

  constructor(
    private location: PlatformLocation, // 路径
    private http: HttpClient, // http请求
    private commonsService: CommonsService,
    private message: NzMessageService, // 信息提示
    private fb: FormBuilder, // 表单
    private modalService: NzModalService, // 对话框
    private getData: LocalStorageService, // 请求数据字典查询
    private store: LocalStorageService,
  ) {
  }

  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],
      label: [null],
      roleId: [null, [Validators.required]],
    });


    // 调用请求方法
    this.goRequest();
    // 调用请求政策下拉列表
    this.goRequestpoducetList();
    this.goRequestCompanyList();

    this.getUserLabel();
  }


  confirmationValidator = (control: FormControl): { [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']);
      }
    });
  }

  // 查询用户标签
  getUserLabel() {
    this.commonsService.getDictionary('USER_LABEL', data => {
        this.userLabelArray = data['return_data'];
    });
  }

  // 获取部门列表
  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,
      labelIdArray: value.label
    };
    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.secUser.labelIdArray = value.label;

    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.validateForm.reset();
    this.isVisibleEdit = false;
  }

  // 删除提示
  showDeleteConfirm(id): void {
    this.modalService.confirm({
      nzTitle: '您确定要删除吗?',
      nzOkText: '是',
      nzOkType: 'danger',
      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'];
        const labelIdArray = [];
        for (const labelId of this.secUser['labelIdArray']) {
          labelIdArray.push(String(labelId));
        }
        this.validateForm.patchValue({ label: labelIdArray});
        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;
    }
  }

}
