import {Component, OnInit} from '@angular/core';
import {environment} from "../../../../environments/environment";
import {DatePipe, NgForOf, NgIf, PlatformLocation} from "@angular/common";
import {HttpClient} from "@angular/common/http";
import {NzMessageService} from "ng-zorro-antd/message";
import {FormsModule, ReactiveFormsModule, UntypedFormBuilder} from "@angular/forms";
import {NzModalModule, NzModalService} from "ng-zorro-antd/modal";
import {ActivatedRoute, RouterLink} from "@angular/router";
import {ADMIN_INFO_OBJECT} from "../../../services/local-storage.namespace";
import {SalesmanStatusPipe} from "../../../pipes/salesman-status.pipe";
import {BreadcrumbComponent} from "../../common/breadcrumb/breadcrumb.component";
import {NzFormDirective, 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 {NzSiderComponent} from "ng-zorro-antd/layout";
import {NzSwitchComponent} from "ng-zorro-antd/switch";
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";
declare var $: any;

@Component({
  selector: 'app-system-role-show',
  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,
    NzModalModule,
    NzTableModule,
    NzFormModule,
    NzSpinModule,
    NzRadioGroupComponent,
    NzRadioComponent,
    NzDatePickerModule
  ],
  templateUrl: './system-role-show.component.html',
  styleUrls: ['./system-role-show.component.less','../../../../assets/css/bootstrap-treeview.min.css']
})
export class SystemRoleShowComponent implements OnInit {
  WEB_SERVE_URL = environment.baseUrl;
  role: any = {
    companyId: '',
    roleType: '',
    roleName: '',
    roleDesc: '',
    enableStatus: '',
    sId: '',
    createTime: '',
    updateTime: '',
    templetType : 0
  };
  rolePermission: any = {
    roleId: '',
    pmsIds: new Array()
  };
  test = [];
  dataTree;
  private locationUrl: any;
  constructor(
    private location: PlatformLocation, // 路径
    private http: HttpClient, // http请求
    private message: NzMessageService, // 信息提示
    private fb: UntypedFormBuilder, // 表单
    private modalService: NzModalService, // 对话框
    private store: BrowserStorageService ,
    private activatedRoute: ActivatedRoute,
  ) {
  }


  ngOnInit() {

    // 查询详情
    this.activatedRoute.queryParams.subscribe(queryParams => {
      this.role = queryParams;

      let roleId = this.store.get(ADMIN_INFO_OBJECT)['secRole'].id;
      let roleType = this.store.get(ADMIN_INFO_OBJECT)['secRole'].roleType;
      const allotRoleId = this.role.id;
      if (this.role.templetType === 1) {
        // 如果是模板
        roleId = '';
        roleType = 0;
      }

      this.http.get(this.WEB_SERVE_URL + '/secMenu/findMenuTree?roleId=' + roleId + '&roleType=' + roleType + '&allotRoleId=' + allotRoleId).subscribe( data => {
        this.goInformation(data['return_data']);
        this.goTree(data['return_data'] );
      });

    });
  }

  // 循环树数据
  goInformation(data: any) {
    this.dataTree = data;
    // 请求查询留言
    this.goTree(data);
  }
  goTree(res) {
    const that = this;
    $('#tree').treeview({
      showCheckbox: true,
      levels: 0,
      data: res,
      onNodeChecked: function getArray(event, data) {
        if (data.parentId != null) {
          const parentNode = $('#tree').treeview('getNode', data.parentId);
          $('#tree').treeview('checkNode', parentNode.nodeId);
          if (parentNode.parentId != null) {
            getArray(parentNode, parentNode);
          }
        }
        that.test = $('#tree').treeview('getChecked');
      },
      onNodeUnchecked: function getArray(event, data) {
        if (data.nodes != null) {
          // tslint:disable-next-line:prefer-for-of
          for (let i = 0; i < data.nodes.length; i++) {
            // @ts-ignore
            $('#tree').treeview('uncheckNode', [data.nodes[i].nodeId, {silent: true}]);
            getArray(data.nodes[i], data.nodes[i]);
          }
        }
        that.test = $('#tree').treeview('getChecked');
      }
    });
  }

  // 保存分配
  savePermission() {
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0 ; i < this.test.length ; i++) {
      this.rolePermission.pmsIds.push(this.test[i].id);
    }

    let requestUrl = null;
    if (this.role.templetType === '1') {
      requestUrl = '/secPermission/allotTemplatePermission';
    } else if (this.role.templetType === '0') {
      requestUrl = '/secPermission/allotPermission';
    } else {
      this.message.create('warning', '角色信息错误');
      return;
    }

    this.rolePermission.roleId = this.role.id;
    this.http.post(this.WEB_SERVE_URL + requestUrl, this.rolePermission).subscribe(data => {
      if (data['return_code'] === '000000') {
        history.back();
        this.message.create('success', '提交成功');
      } else {
        this.message.create('warning', data['return_msg']);
      }
    });
  }

  // 返回
  getBack() {
    history.back();
  }

}
