import {Component, OnInit} from '@angular/core';

import {PlatformLocation} from '@angular/common';
import {HttpClient} from '@angular/common/http';
import {NzFormatEmitEvent, NzMessageService, NzModalService} from 'ng-zorro-antd';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NavigationExtras, Router} from '@angular/router';

// import {DictionaryService} from '../../../services/dictionary/dictionary.service';
import {environment} from '../../../../environments/environment';
import {ADMIN_INFO_OBJECT} from '../../../services/local-storage.namespace';
import {LocalStorageService} from '../../../services/local-storage.service';
import {CommonsService} from '../../../services/commons.service';
declare var $: any;
@Component({
  selector: 'app-system-role',
  templateUrl: './system-role.component.html',
  styleUrls: ['./system-role.component.less']
})
export class SystemRoleComponent implements OnInit {
  WEB_SERVE_URL = environment.baseUrl;
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  requestData = [];
  loading = true;
  isLoadingSearch = false;
  isLoadingDelete = false;
  isVisible = false;
  isVisibleEdit = false;
  isOkLoading = false;
  validateForm: FormGroup;
  validateFormEdit: FormGroup;
  title = '';
  role: any = {
    companyId: '',
    roleType: '',
    roleName: '',
    roleDesc: '',
    enableStatus: '',
    sId: '',
    createTime: '',
    updateTime: '',
    templetType : 0,
    primaryRole: ''
  };
  isMultiCheck = false;
  templetType;
  companyId;
  // tslint:disable-next-line:variable-name
  BTN_systemrole_add;
  // tslint:disable-next-line:variable-name
  BTN_systemrole_allot;
  // tslint:disable-next-line:variable-name
  BTN_systemrole_edit;
  // tslint:disable-next-line:variable-name
  BTN_systemrole_delete;
  // tslint:disable-next-line:variable-name
  BTN_systemrole_addmodel = 0;    // 增加模板按钮
  /** add type */
  requestType = 'default';    // 'role'->角色，'roleModel'->角色模板
  roleTypeArray = [];

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

  ngOnInit() {
    this.commonsService.getDictionary('ROLE_TYPE', data => {
      this.roleTypeArray = data['return_data'];
    });
    if (this.store.get(ADMIN_INFO_OBJECT)['secRole'].roleType === 0) {
      this.templetType = 1;
      this.companyId = '';
    } else {
      this.templetType = 0;
      this.companyId = this.store.get(ADMIN_INFO_OBJECT)['bsCompany'].id;
    }
    // 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_systemrole_add' ) {
        this.BTN_systemrole_add = 1;
      }
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_systemrole_allot' ) {
        this.BTN_systemrole_allot = 1;
      }
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_systemrole_edit' ) {
        this.BTN_systemrole_edit = 1;
      }
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_systemrole_delete' ) {
        this.BTN_systemrole_delete = 1;
      }
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_systemrole_addmodel' ) {
        this.BTN_systemrole_addmodel = 1;
      }
    }
    // 判断表单
    this.validateForm = this.fb.group({
      role_name: [null, [Validators.required]],
      roleType: [null, [Validators.required]],
      enableStatus: [null],
      role_desc: [null],
    });
    this.validateFormEdit = this.fb.group({
      role_name: [null, [Validators.required]],
      roleType: [null, [Validators.required]],
      enableStatus: [null],
      role_desc: [null],
    });
    // 调用请求方法
    this.goRequest();
  }


  // 查询
  goRequest(reset: boolean = false) {
    this.loading = false;
    if (reset) {
      this.pageIndex = 1;
    }
    this.http.get(this.WEB_SERVE_URL + '/secRole/getRoleList?pageNum=' + this.pageIndex + '&pageSize=' + this.pageSize + '&roleName=' + this.title + '&companyId=' + this.companyId + '&templetType=' + this.templetType).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.requestData = data['return_data'].list;
        this.total = data['return_data'].total;
        this.isLoadingSearch = false;
      } else {
        this.message.create('error', data['return_msg']);

      }
    });
  }

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

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

  // 确定添加按钮
  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 (value.role_name == null) {
      this.message.create('warning', `请输入名称！`);
      return;
    } else if (this.requestType === 'roleModel' && value.roleType == null) {
      this.message.create('warning', `请选择角色类型！`);
      return;
    }

    const params = {
      roleName: value.role_name,
      roleType: null,
      enableStatus: 0,
      roleDesc: value.role_desc,
      templetType: 0,
      companyId: null,
      primaryRole: 0
    };
    if (value.enableStatus === true) {
      params.enableStatus = 1;
    }
    if (this.requestType === 'role') {
      params.roleType = this.store.get(ADMIN_INFO_OBJECT)['secRole'].roleType;
      params.templetType = 0;
      params.companyId = this.store.get(ADMIN_INFO_OBJECT)['bsCompany'].id;
    } else if (this.requestType === 'roleModel') {
      params.roleType = value.roleType;
      params.templetType = 1;
      params.companyId = null;
    } else {
      return;
    }

    this.isOkLoading = true;
    this.http.post(this.WEB_SERVE_URL + '/secRole/addRole', params).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.message.create('success', `新增成功！`);
        this.title = '';
        this.goRequest();
        this.isVisible = false;
      } else {
        this.message.create('warning', data['return_msg']);
      }
      setTimeout(() => {
        this.isOkLoading = false;
      }, 1000);
    }, error => {
      this.isOkLoading = false;
      this.message.create('error', `未知错误！`);
    });
  }

  // 取消按钮
  handleCancel(): void {
    this.goRequest();
    this.isVisible = false;
    this.validateForm.reset();
  }
  /** 添加 end */

  /** 修改 start */
  // 查询详情
  goDetails(data) {
    this.role = data;
    this.role['roleType'] = String(data['roleType']);
    if (this.role.templetType === 1) {
      this.requestType = 'roleModel';
    } else {
      this.requestType = 'role';
    }

    this.isVisibleEdit = true;
  }
  // 修改确定按钮
  handleOkEdit(value: any) {
    // tslint:disable-next-line:forin
    for (const i in this.validateFormEdit.controls) {
      this.validateFormEdit.controls[i].markAsDirty();
      this.validateFormEdit.controls[i].updateValueAndValidity();
    }

    if (this.role.roleName == null || this.role.roleName === '') {
      this.message.create('warning', `请输入名称！`);
      return;
    }

    if (this.role.enableStatus == true) {
      this.role.enableStatus = 1;
    } else {
      this.role.enableStatus = 0;
    }

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

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

  goAllocation(data) {
    this.role = data;
    const navigationExtras: NavigationExtras = {
      queryParams: this.role,
    };
    this.router.navigate(['/admin/system/systemrole-show'], navigationExtras);
    // this.goTree(this.role.sid);
  }



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

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

  /** 角色模板 start */
  goAddModel() {
    this.requestType = 'roleModel';
    this.isVisible = true;
  }
  /** 角色模板 end */
}
