import { ChangeDetectorRef, Component, Inject, Injector, OnInit, ViewChild } from '@angular/core';
import { FormSchemaService, GeneralHttpService, GeneralUtilsService, I18NService } from '@core';
import * as icConstant from '@core';
import { CacheService } from '@delon/cache';
import { SFComponent, SFSchema } from '@delon/form';
import { ALAIN_I18N_TOKEN, ModalHelper } from '@delon/theme';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { NzFormatEmitEvent, NzTreeComponent, NzTreeNode } from 'ng-zorro-antd/tree';
import { forkJoin } from 'rxjs';

import { PopupSelectPanelComponent } from '../../../../shared/component/popup-select/popup-select-panel';

@Component({
  selector: 'app-sys-rw-org-list',
  styleUrls: ['./list.component.less'],
  templateUrl: './list.component.html'
})
export class SysRwOrgListComponent implements OnInit {
  /* #region  变量定义 */
  constant = icConstant;
  @ViewChild('baseTree', { static: true }) baseTree!: NzTreeComponent;
  @ViewChild('baseFormSf', { static: true }) baseFormSf!: SFComponent;
  baseFormSchema: SFSchema = this.formSchema.organizationBaseFormSchema;
  baseFormData: NzSafeAny = {};
  configs: any;
  nodeCheck: NzSafeAny[] = [];
  nodes: NzSafeAny[] = [];
  originalNodes: NzSafeAny[] = [];
  formId = '-1';
  selectedKeys: NzSafeAny[] = [];
  selectedNode: any;
  checkedKeys: NzSafeAny[] = [];
  expandedKeys: NzSafeAny[] = [];
  uuids: NzSafeAny[] = [];
  editOrAddNodes: any[] = [];
  searchValue = '';
  userTableData: NzSafeAny[] = [];
  formConfig: any = { config: { listConfig: { base: { moduleTitle: '组织机构', moduleDescription: '' } } } };
  /* #endregion */

  /** 查询条件 */
  @ViewChild('searchSf', { static: false }) searchSf!: SFComponent;
  searchSchema: SFSchema = {
    properties: {
      username: {
        type: 'string',
        title: '姓名'
      },
      rolename: {
        type: 'string',
        title: '角色'
      }
    },
    ui: {
      spanLabelFixed: 100,
      grid: {
        xs: 24,
        sm: 12,
        md: 12,
        lg: 12,
        xl: 6,
        xxl: 6
      }
    }
  };

  /* #region  构造函数 */
  constructor(
    private http: GeneralHttpService,
    private cd: ChangeDetectorRef,
    private utils: GeneralUtilsService,
    private modal: ModalHelper,
    private notification: NzNotificationService,
    @Inject(ALAIN_I18N_TOKEN) public i18n: I18NService,
    private injector: Injector,
    public srv: CacheService
  ) {}

  private get formSchema(): FormSchemaService {
    return this.injector.get(FormSchemaService);
  }
  /* #endregion */

  ngOnInit() {
    this.getUUIDS();
    this.searchTreeData();
  }

  searchTreeData() {
    this.http.getOrganizationList({}).subscribe(res => {
      this.nodes = this.utils.composeTree(res.data, 'fullname');
      this.originalNodes = this.utils.composeTree(res.data, 'fullname');
    });
  }

  // 展开或收起全部节点
  expandAll(status: boolean) {
    const nodes = this.baseTree.getTreeNodes();
    this.utils.expandOrCollapseAllTreeNode(status, nodes);
  }

  /** 手动勾选和选中树节点 */
  treeChange(event: NzFormatEmitEvent): void {
    this.selectedNode = event.keys!.length > 0 ? event.node : null;
    /** 勾选 */
    if (event.eventName === 'check') {
      this.nodeCheck = [...event.checkedKeys!];
    }
    if (event.eventName === 'click') {
      /** 点击label */
      if (this.selectedNode && this.selectedNode.key !== '-1') {
        this.selectedNode.origin.createdate = new Date(this.selectedNode.origin.createdate) || new Date();
        this.selectedNode.origin.modifydate = new Date(this.selectedNode.origin.modifydate) || new Date();
        this.baseFormData = { ...this.selectedNode.origin };
        this.formId = this.selectedNode.key;
        this.getOrganizationUserByOrgId();
      } else {
        this.baseFormData = {};
        this.formId = '-1';
      }
    }
  }

  /** 清除所有树节点选中状态 */
  resetTreeStatus() {
    this.formId = '-1';
    this.selectedKeys = [];
    this.checkedKeys = [];
    this.baseFormData = {
      pid: this.formId
    };
  }

  getUUIDS() {
    this.http.getUUIDS(30).subscribe(res => {
      this.uuids = res.data;
    });
  }

  add() {
    const childId = this.uuids[0];
    this.uuids.splice(0, 1);
    if (this.uuids.length < 10) {
      this.getUUIDS();
    }
    this.baseFormData = this.utils.initTreeChild(this.selectedNode, childId, this.baseTree);
    this.baseFormData['enabled'] = 'y';
    this.baseFormData['orgtype'] = 'dept';
    const sysSerial = { modulecode: 'sys_organization_code', ruleTemplateStr: 'department@{serialNumber:#000}' };
    this.http.getSerialNumberCode(sysSerial).subscribe(res => {
      if (res.code !== this.constant.errorCode.saveError) {
        const codeSf = this.baseFormSf.getProperty('/code')!;
        codeSf.resetValue(res.data.code, false);
        this.cd.markForCheck();
      }
    });
    if (this.selectedNode) {
      this.cd.markForCheck();
      // 设置选中当前节点
      this.selectedKeys = [childId];
      this.formId = childId;
      this.selectedNode = this.baseTree.getTreeNodeByKey(childId);
    }
  }

  // 监听表单验证
  baseFormError(event: any) {}

  // 监听表单值改变
  baseFormChange(event: any) {}

  saveNode(saveOperation: string) {
    this.selectedNode = this.baseTree.getSelectedNodeList()[0];
    this.baseFormSf.setValue('/modifydate', new Date());
    this.selectedNode.origin = { ...this.baseFormSf.value };
    this.cd.markForCheck();
    this.selectedNode.title = this.selectedNode.origin.fullname;
    this.utils.initSaveTreeNode(this.selectedNode);
    this.http.saveOrganizationList([this.selectedNode.origin]).subscribe(res => {
      if (res.code !== this.constant.errorCode.saveError) {
        this.selectedNode.origin.editstatus = 'edited';
        // 保存并新增同级节点
        if (saveOperation === 'addSameLevel') {
          const parentNode = this.selectedNode.parentNode;
          this.selectedKeys = [parentNode.key];
          this.formId = parentNode.key;
          this.selectedNode = this.baseTree.getTreeNodeByKey(parentNode.key);
          this.add();
        }
        // 保存并新增子节点
        if (saveOperation === 'addChildLevel') {
          this.add();
        }
        const data = this.selectedNode.origin;
        const pData = this.selectedNode.parentNode.origin;
        const reqs = [];
        if (data.orgtype == '10') {
          const updateSql = `update ZHCX_SUBCONTRACTOR_MANAGE_UNIT
                             set WORKSHOP_NAME       = '${pData.fullname}/${data.fullname}',
                                 WORKSHOP_SHORT_NAME = '${data.shortname}',WORKSHOP_NAME_EN = '${data.remark}'
                             WHERE WORKSHOP_ID = '${data.id}'`;
          const updateRectifyDeptSql = `update ZHCX_PROJECT_RECTIFY_MACHINE
                             set DEPTNAME = '${data.shortname}'
                             WHERE DEPTID = '${data.id}'`;
          const updateRectifyDutyDeptSql = `update ZHCX_PROJECT_RECTIFY_MACHINE
                             set DUTYDEPTNAME = '${data.shortname}'
                             WHERE DUTYDEPTID = '${data.id}'`;
          reqs.push(this.http.getPostData(`inControlServer/sys/generalCRUD/getDataBySql`, { querySql: updateSql }));
          reqs.push(this.http.getPostData(`inControlServer/sys/generalCRUD/getDataBySql`, { querySql: updateRectifyDeptSql }));
          reqs.push(this.http.getPostData(`inControlServer/sys/generalCRUD/getDataBySql`, { querySql: updateRectifyDutyDeptSql }));
          // this.http.getPostData(`inControlServer/sys/generalCRUD/getDataBySql`, { querySql: updateSql }).subscribe(res => {
          //   console.log('同步分包商成功...');
          // });
        } else if (data.orgtype == '20') {
          const updateRectifyFirstDeptSql = `update ZHCX_PROJECT_RECTIFY_MACHINE
                             set FIRSTDEPTNAME = '${data.shortname}'
                             WHERE FIRSTDEPTID = '${data.id}'`;
          const updateRectifyFirstDutyDeptSql = `update ZHCX_PROJECT_RECTIFY_MACHINE
                             set FIRSTDUTYDEPTNAME = '${data.shortname}'
                             WHERE FIRSTDUTYDEPTID = '${data.id}'`;
          reqs.push(this.http.getPostData(`inControlServer/sys/generalCRUD/getDataBySql`, { querySql: updateRectifyFirstDeptSql }));
          reqs.push(this.http.getPostData(`inControlServer/sys/generalCRUD/getDataBySql`, { querySql: updateRectifyFirstDutyDeptSql }));
        }
        forkJoin(reqs).subscribe((res: any[]) => {
          res.forEach((v: NzSafeAny) => {
            console.log('同步分包商,整改清单成功...');
          });
        });
      }
    });
  }

  deleteRows() {
    const ids = this.nodeCheck.map((value: NzSafeAny) => {
      return value.key;
    });
    this.checkedKeys = [];
    this.http.deleteOrg(ids).subscribe(res => {
      this.resetTreeStatus();
      this.searchTreeData();
    });
  }

  // 新增用户
  addUsers() {
    const configItem = {
      configName: 'user_select',
      displayField: 'NAME',
      multipleSelect: true
    };
    this.modal.create(PopupSelectPanelComponent, { configItem }, { size: 800 }).subscribe(res => {
      if (res) {
        const orgUsers: NzSafeAny[] = [];
        res.forEach((v: NzSafeAny) => {
          const orgUser = {
            orgid: this.formId,
            userid: v.ID,
            username: v.NAME
          };
          orgUsers.push(orgUser);
        });
        this.http.addOrganizationUsers(orgUsers).subscribe(retRes => {
          this.getOrganizationUserByOrgId();
          this.notification.info(retRes.msg, '');
        });
      }
    });
  }

  deleteUsers(row: any) {
    const userOrgObj = {
      id: row.userOrgId,
      userid: row.userId,
      orgid: this.formId
    };
    this.http.deleteOrganizationUsers([userOrgObj]).subscribe(res => {
      this.getOrganizationUserByOrgId();
    });
  }

  getOrganizationUserByOrgId() {
    // 查询条件
    const searchvl = this.searchSf.value;
    searchvl['orgid'] = this.selectedNode.key;
    this.http.getOrganizationUserByOrgId(searchvl).subscribe(res => {
      this.userTableData = [];
      this.userTableData = res.data;
    });
  }

  /** 树形搜索 */
  startFilter() {
    const resultNodes: NzTreeNode[] = this.utils.searchTree(this.searchValue, this.originalNodes);
    this.nodes = resultNodes;
  }

  /**
   * 树表结构，搜索框enter时触发
   */
  searchValueChange(value: any) {
    if (value === '') {
      this.nodes = this.originalNodes;
    }
  }
}
