import {Component, OnInit} from '@angular/core';
import {environment} from "../../../../environments/environment";
import {FormsModule, ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup, Validators} from "@angular/forms";
import {HttpClient} from "@angular/common/http";
import {NzMessageService} from "ng-zorro-antd/message";
import {ActivatedRoute, RouterLink} from "@angular/router";
import {DatePipe, NgForOf, NgIf, PlatformLocation} from "@angular/common";
import {NzModalComponent, NzModalModule, NzModalService} from "ng-zorro-antd/modal";
import {ADMIN_INFO_OBJECT} from "../../../services/local-storage.namespace";
import {NzFormatEmitEvent, NzTreeComponent} from "ng-zorro-antd/tree";
import {SalesmanStatusPipe} from "../../../pipes/salesman-status.pipe";
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, NzInputGroupComponent, NzInputGroupWhitSuffixOrPrefixDirective} 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 {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-organization',
  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,
    NzTreeComponent,
    NzModalComponent,
    NzInputGroupWhitSuffixOrPrefixDirective,
    FormsModule,
    NzInputGroupComponent,
    NzFormLabelComponent,
    NzModalModule,
    NzTableModule,
    NzFormModule,
    NzSpinModule,
    NzRadioGroupComponent,
    NzRadioComponent,
    NzDatePickerModule
  ],
  templateUrl: './system-organization.component.html',
  styleUrl: './system-organization.component.less'
})
export class SystemOrganizationComponent implements OnInit {
  FILE_URL = environment.imageUrl;
  WEB_SERVE_URL = environment.baseUrl;
  searchValue = '';
  nodes = [];
  orgLogo = [];
  organizationArr: any = {};
  remark;
  isVisible = false;
  validateForm: UntypedFormGroup;
  isOkLoading = false;
  isOkEditLoading = false;
  province;
  regionId;
  isLoadingDelete = false;
  id;
  isVisibleEdit = false;
  UserList;
  upload = '1';

  isAgencyVisibleButton = false;
  isAgencyVisibleDivider = false;
  isAgencyVisible = false;
  industryArray;
  organizationAgencyObject: any = {};
  organizationAgencyRegion = ['', '', ''];
  organizationAgencyRegionName = ['', '', ''];
  listOfTagOptions = [];
  orgId;

  agencyImgList = [];
  agencyImgString = '';
  agencyImgShow: string | undefined = '';
  agencyImgVisibleShow = false;

  licenseImgList = [];
  licenseImgString = '';
  licenseImgShow: string | undefined = '';
  licenseImgVisibleShow = false;

  organizationAgencyForm: UntypedFormGroup;


  showUploadList = {
    showPreviewIcon: true,
    showRemoveIcon: true,
    hidePreviewIconInNonImage: true
  };
  imgUrl = '';

  // tslint:disable-next-line:variable-name
  BTN_systemorganization_add;
  // tslint:disable-next-line:variable-name
  BTN_systemorganization_edit;
  // tslint:disable-next-line:variable-name
  BTN_systemorganization_delete;
  nzOptions;
  ORG_REGION_WARRANT;
  regionType = 0;
  companyIdType;
  visible = false;
  label = null;
  config: any = {
    initialFrameHeight: 400
  };
  USER_INFO;
  orgDetail = {};
  constructor(
    private http: HttpClient,
    private message: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private location: PlatformLocation,
    private store: BrowserStorageService ,
    private fb: UntypedFormBuilder, // 表单
    private modalService: NzModalService, // 对话框
  ) {
  }

  ngOnInit() {
    this.USER_INFO = this.store.get(ADMIN_INFO_OBJECT);
    this.companyIdType = this.USER_INFO['secUser']['companyId'];
    this.http.get(this.WEB_SERVE_URL + '/secUser/getUserList?companyId=' + this.USER_INFO['bsCompany'].id + '&pageNum=1&pageSize=10000').subscribe( data => {
      if (data['return_code'] === '000000') {
        this.UserList = data['return_data'].list;
      } else {
        this.message.create('warning', data['return_msg']);
      }
    });
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < this.USER_INFO['buttonList'].length; i++) {
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_systemorganization_add' ) {
        this.BTN_systemorganization_add = 1;
      }
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_systemorganization_edit' ) {
        this.BTN_systemorganization_edit = 1;
      }
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_systemorganization_delete' ) {
        this.BTN_systemorganization_delete = 1;
      }
    }

    /*    this.store.provinceData(data => {
          if (data['return_code'] === '000000') {
            this.nzOptions = data['return_data'];
            this.generateCommentCiyt(this.nzOptions);
          }
        });*/

    // 判断表单
    this.validateForm = this.fb.group({
      // regionAbbreviate: [null, [Validators.required, ValidatorsService.maxLength(10)]],
      name: [null, [Validators.required]],
      // address: [null, [Validators.required]],
      phone: [null, [Validators.required]],
      siteUrl: [null],
      email: [null],
      managerId: [null],
      managerName: [null],
      managerPhone: [null],
      remark: [null],
    });

    // 机构详细表单校验
    this.organizationAgencyForm = this.fb.group({
      id: [null],
      orgId: [null],
      agencyName: [null, [Validators.required]],
      postalCoding: [null, [Validators.required]],
      agencyChargePerson: [null, [Validators.required]],
      contactNumber: [null, [Validators.required]],
      organizationAgencyRegion: [null, [Validators.required]],
      address: [null, [Validators.required]],
      listOfTagOptions: [null, [Validators.required]],
      introduction: [null, [Validators.required]],
    });

    this.goRequest();
  }

  goRequest() {
    this.http.get(this.WEB_SERVE_URL + '/bsOrganization/getOrganizationTree?companyId=' + this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['id']).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.nodes = [data['return_data']];
        this.generateComment(this.nodes);
      } else {
        this.message.create('warning', data['return_msg']);
      }
    });
  }
  generateComment(data) {
    for (const i in data) {
      if (data[i].nodes == null) {
        const item  = {
          isLeaf: true,
          title: data[i].text,
          key: data[i].id,
          children: data[i].nodes,
        };
        data[i] = item;
      } else {
        const item  = {
          isLeaf: false,
          title: data[i].text,
          key: data[i].id,
          children: data[i].nodes,
        };
        data[i] = item;
        this.generateComment(data[i].children);
      }
    }
    this.nodes = data;
  }

  goManagerName(userId) {
    if (userId == null || userId === 'null' || userId.length === 0) {
      return;
    }

    this.http.get(this.WEB_SERVE_URL + '/secUser/getUserView?userId=' + userId).subscribe( data => {
      if (data['return_code'] === '000000') {
        this.organizationArr.managerPhone = data['return_data'].telephone;
      } else {
        this.message.create('warning', data['return_msg']);
      }
    });
  }

  nzEvent(event: NzFormatEmitEvent): void {
    if (event.event == null) {
      return;
    }
    if (event['node']['parentNode'] == null) {
      this.upload = null;
    } else {
      this.upload = '1';
    }
    this.id = event['keys'][0];
    if (event['keys'][0] == null) {
      return;
    }

    // 校验公司类型是否是 法律局
    if (this.USER_INFO['bsCompany'].companyType === 2) {
      this.isAgencyVisibleButton = true;
      this.isAgencyVisibleDivider = true;
    }

    this.isAgencyVisible = false;
    this.orgId = event['keys'][0];
    this.goOrganization(this.orgId);
  }

  goOrganization(id) {
    if (id == null) {
      return;
    }
    this.orgLogo = [];
    this.http.get(this.WEB_SERVE_URL + '/bsOrganization/getOrganization?organizationId=' + id).subscribe( data => {
      if (data['return_code'] === '000000') {
        this.organizationArr = data['return_data'];
        this.regionId = data['return_data']['regionId'];

        if (data['return_data']['logo'] != null && data['return_data']['logo'] != '') {
          const logo = String(data['return_data']['logo']);
          const logoArray = [];
          logoArray.push(
            {
              uid: 1,
              name: logo,
              status: 'done',
              url: this.FILE_URL + logo
            });
          this.orgLogo = logoArray;
        }
        this.organizationArr.managerId = String(this.organizationArr.managerId);
      } else {
        this.message.create('warning', data['return_msg']);
      }
    });

  }

  goAddShow() {
    if (this.orgId === 0 ) {
      this.message.create('error', `请选择上级部门！`);
      return;
    }
    this.orgLogo = [];
    this.regionId = null;
    this.validateForm.reset();
    this.isVisible = true;
  }

  selectManager(data) {
    console.log(data);
  }
  // 确定添加按钮
  handleOk(value: any): void {
    if (this.orgId == null || this.orgId === '') {
      this.message.error('请选择上级部门');
      return;
    }
    // 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;
    }
    let orgLogoStr = '';
    // 处理logo地址
    if (this.orgLogo.length > 0){
      for (let i in this.orgLogo) {
        if (this.orgLogo[i]['response'] != null) {
          orgLogoStr += this.orgLogo[i]['response']['return_data'][0];
        } else {
          orgLogoStr += this.orgLogo[i]['name'];
        }
      }
    }
    // 定义请求数据
    const params = {
      parentId: this.orgId,
      companyId: this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['id'],
      regionId: this.regionId,
      regionAbbreviate: value.regionAbbreviate,
      name: value.name,
      address: value.address,
      phone: value.phone,
      logo: orgLogoStr,
      siteUrl: value.siteUrl,
      email: value.email,
      remark: value.remark
    };
    this.isOkLoading = true;
    this.http.post(this.WEB_SERVE_URL + '/bsOrganization/addOrganization', 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']);
      }
      setTimeout(() => {
        this.isOkLoading = false;
      }, 1000);
    }, error => {
      this.isOkLoading = false;
      this.message.create('error', `未知错误！`);
    });
  }

  /**
   * 选择区域回调
   * @param regionId
   */
  regionChange(regionId) {
    this.regionId = regionId;
  }

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

  resetForm(e: MouseEvent): void {
    this.validateForm.reset();
  }

  // 查询详情
  goDetails() {
    if (this.orgId == null || this.orgId == '') {
      this.message.create('error', `请选择上级部门！`);
      return;
    }
    this.goOrganization(this.orgId);
    this.isVisibleEdit = true;
  }
// 修改确定按钮
  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;
    }

    let orgLogoStr = '';
    // 处理logo地址
    if (this.orgLogo.length > 0){
      for (let i in this.orgLogo) {
        if (this.orgLogo[i]['response'] != null) {
          orgLogoStr += this.orgLogo[i]['response']['return_data'][0];
        } else {
          orgLogoStr += this.orgLogo[i]['name'];
        }
      }
    }

    // 定义请求数据
    const params = {
      id: this.organizationArr['id'],
      parentId: this.organizationArr['parentId'],
      companyId: this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['id'],
      regionId: this.regionId,
      regionAbbreviate: value.regionAbbreviate,
      name: value.name,
      managerId: value.managerId,
      address: value.address,
      phone: value.phone,
      logo: orgLogoStr,
      siteUrl: value.siteUrl,
      email: value.email,
      remark: value.remark
    };
    this.isOkLoading = true;
    this.http.post(this.WEB_SERVE_URL + '/bsOrganization/updateOrganization', params).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.message.create('success', `修改成功！`);
        this.goOrganization(this.id);
        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.isVisibleEdit = false;
  }

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

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