import { Component, OnInit, ViewChild, AfterViewInit } from "@angular/core";
import { NzFormatEmitEvent, NzTreeNodeOptions, NzTreeComponent, NzMessageService } from 'ng-zorro-antd';
import { ToolService } from 'src/app/services/tool.service';
import { MainService } from 'src/app/services/main.service';
import uniqBy from 'lodash-es/uniqBy'
import cloneDeep from 'lodash-es/cloneDeep'
import { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';
import { Router, ActivatedRoute } from '@angular/router';
import { Subject, forkJoin } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: "app-inspection-plan-config",
  templateUrl: "./inspection-plan-config.component.html",
  styleUrls: ["./inspection-plan-config.component.less"],
})
export class InspectionPlanConfigComponent implements OnInit, AfterViewInit {
  constructor(
    private tool: ToolService,
    private mainService: MainService,
    private message: NzMessageService,
    private router: Router,
    private route: ActivatedRoute,
  ){}
  @ViewChild('nzTreeComponent', { static: false }) nzTreeComponent: NzTreeComponent;
  @ViewChild('nzTreeComponentCopy', { static: false }) nzTreeComponentCopy: NzTreeComponent;
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;
  defaultCheckedKeys = [];
  defaultSelectedKeys = [];
  defaultExpandedKeys = [];
  nodes: NzTreeNodeOptions[] = [];
  currentHospital; //当前院区

  changeInpSubject = new Subject(); //防抖

  ngOnInit(): void {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[0] === 'user'){
        this.getUsers(v[1]);
      } else if(v[0] === 'group'){
        this.getGroups(v[1]);
      }
    });
    this.currentHospital = this.tool.getCurrentHospital();
    this.getUsers();
    this.getGroups();
    this.getInfo();
  }

  getInfo(){
    let getPlanDetail$ = this.getPlanDetail();
    let getAddressList$ = this.getAddressList();
    let getTagList$ = this.getTagList();
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    forkJoin(getPlanDetail$, getAddressList$, getTagList$).subscribe((res:any) => {
      this.message.remove(this.maskFlag);
      this.maskFlag = false;
      // getPlanDetail
      {
        this.planDetail = res[0].data || {};
        let nodeList = res[0].data ? (res[0].data.nodeList || []) : [];
        this.generateTree(nodeList);
      }
      // getAddressList
      {
        if (res[1].status == 200) {
          let addressList = res[1].list || [];
          let buildingAndAddressList = this.generateList(addressList);
          this.buildingAndAddressList = this.tool.tranListToTreeData(buildingAndAddressList, undefined, "parentId", "key");
          console.log(this.buildingAndAddressList);
        }else{
          this.message.error(res[1].msg || "请求数据失败");
        }
      }
      // getTagList
      {
        if (res[2].status == 200) {
          this.tagList = res[2].list || [];
        }
      }
    });
  }

  // 表格数据
  isLoading = false;
  buildingAndAddressList: NzTreeNodeOptions[] = [];
  buildingAndAddressListCopy: NzTreeNodeOptions[] = [];
  getAddressList() {
    let data = {
      idx: 0,
      sum: 9999,
      inspectionNode: {
        hosId: this.currentHospital.id,
      },
    };

    return this.mainService.getFetchDataList("simple/data", "inspectionNode", data)
  }

  nzCheck(event: NzFormatEmitEvent): void {
    console.log(event);
    console.log(event.node);
    console.log(event.node.parentNode);
    let buildingAndAddressListCopy = cloneDeep(this.buildingAndAddressListCopy);
    if(event.eventName === 'check'){
      if(event.node.isChecked){
        // 选中
        if(event.node.isLeaf){
          // 叶子节点
          let parent = buildingAndAddressListCopy.find(v => v.key === event.node.parentNode.key);
          if(parent){
            parent.children.push({ ...event.node.origin, selectable: true, checked: false });
          }else{
            let parent = cloneDeep({ ...event.node.parentNode.origin, selectable: true, checked: false });
            parent.children = [{ ...event.node.origin, selectable: true, checked: false }];
            buildingAndAddressListCopy.push(parent);
          }
          console.log("选中叶子节点");
        }else{
          // 非叶子节点
          buildingAndAddressListCopy = buildingAndAddressListCopy.filter(v => v.key !== event.node.key);
          event.node.origin.children.forEach( v => {
            v.selectable = true;
            v.checked = false;
          })
          buildingAndAddressListCopy.push({ ...event.node.origin, selectable: true, checked: false });
          console.log("选中非叶子节点");
        }
      } else {
        // 未选中
        if(event.node.isLeaf){
          // 叶子节点
          let parent = buildingAndAddressListCopy.find(v => v.key === event.node.parentNode.key);
          parent.children = parent.children.filter(v => v.key !== event.node.key);
          if(!parent.children.length){
            buildingAndAddressListCopy = [];
          }
          console.log("未选中叶子节点");
        }else{
          // 非叶子节点
          buildingAndAddressListCopy = buildingAndAddressListCopy.filter(v => v.key !== event.node.key);
          console.log("未选中非叶子节点");
        }
      }
    }
    this.buildingAndAddressListCopy = buildingAndAddressListCopy;
    console.log('buildingAndAddressListCopy', this.buildingAndAddressListCopy);
  }

  // 边输边搜节流阀
  changeInp(model, e) {
    this.isLoading = true;
    this.changeInpSubject.next([model, e]);
  }

  // 修改处理人
  changeUser(userId){
    this.activeAddress.origin.userId = userId;
  }

  // 修改处理组
  changeGroup(groupId){
    this.activeAddress.origin.groupId = groupId;
  }

  searchDto:any = {};
  // 搜索
  // 获取所有科室
  userList: any = []; //所有所属科室(搜索)
  getUsers(keyword = '') {
    let postData = {
      user: {
        hospital: { id: this.currentHospital.id },
        name: keyword,
        simpleQuery: true,
        menuId: 414,
        roleCodes: 'inspectman',
        engineer: 1,
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("data", "user", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.userList = data.list || [];
      });
  }

  // 获取组
  groupList: any = []; //所有所属科室(搜索)
  getGroups(keyword = '') {
    let postData = {
      group2: {
        groupName: keyword,
        hospitals: this.currentHospital.id,
        type: 3,
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("data", "group2", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.groupList = data.list || [];
      });
  }

  // 选择单个巡检点
  activeAddress:any;
  activeAddressId:any;
  nzClick(event: NzFormatEmitEvent): void {
    console.log(event);
    this.activeAddress = event.node;
    this.activeAddressId = event.selectedKeys[0];
    this.activeAddress.origin.radioValue = event.node.origin.userId ? 1 : (event.node.origin.groupId ? 2 : undefined);
    if(event.node.origin.userId){
      let flag = this.userList.find(v => v.id === event.node.origin.userId);
      if(!flag){
        this.userList.unshift({ id: event.node.origin.userId, name: event.node.origin.userName })
      }
    }

    if(event.node.origin.groupId){
      let flag = this.groupList.find(v => v.id === event.node.origin.groupId);
      if(!flag){
        this.groupList.unshift({ id: event.node.origin.groupId, groupName: event.node.origin.groupName })
      }
    }
  }

  // 计划详情
  planDetail:any = {};
  getPlanDetail(){
    return this.mainService.getFetchData("simple/data", "inspection", +this.route.snapshot.paramMap.get('id'));
  }

  // 标签
  tagList:any = [];
  getTagList(){
    let postData = {
      idx: 0,
      sum: 99,
      tag: {
        hosId: this.currentHospital.id,
        onlyBind: 1,
        modelType: { value: 'inspection' },
      }
    }
    return this.mainService.getFetchDataList("simple/data", "tag", postData)
  }

  // 点击标签
  currentTagId;
  clickTag(tag){
    this.currentTagId = tag.id;
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let postData = {
      inspectionNode: {
        hosId: this.currentHospital.id,
        tagIds: tag.id.toString(),
      },
      idx: 0,
      sum: 9999,
    };
    this.mainService
      .getFetchDataList("simple/data", "inspectionNode", postData)
      .subscribe((result) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        let addressList = result.list || [];
        let buildingAndAddressListCopy = this.generateList(addressList, true);
        console.log(buildingAndAddressListCopy);
        this.defaultCheckedKeys = buildingAndAddressListCopy.map(v => v.key).filter(v => !(/b-/.test(v)));
        this.buildingAndAddressListCopy = this.tool.tranListToTreeData(buildingAndAddressListCopy, undefined, "parentId", "key");
        console.log(this.buildingAndAddressListCopy);
      });
  }

  // 回显树形结构
  generateTree(nodeList){
    console.log('nodeList:', nodeList);
    let buildingAndAddressList = nodeList.map(v => ({
      title: v.nodeId ? v.inspectionNodeDTO.name : v.buildingDTO.buildingName,
      key: v.nodeId ? `${v.nodeId}` : `b-${v.buildId}`,
      parentId: v.nodeId ? `b-${v.buildId}` : undefined,
      hosId: v.hosId,
      children: [],
      selectable: false,
      isLeaf: Boolean(v.nodeId),
      checked: false,
    }));
    this.defaultCheckedKeys = buildingAndAddressList.map(v => v.key).filter(v => !(/b-/.test(v)));
    let buildingAndAddressListCopy = nodeList.map(v => ({
      title: v.nodeId ? v.inspectionNodeDTO.name : v.buildingDTO.buildingName,
      key: v.nodeId ? `${v.nodeId}` : `b-${v.buildId}`,
      parentId: v.nodeId ? `b-${v.buildId}` : undefined,
      userId: v.userId,
      userName: v.userDTO ? v.userDTO.name : undefined,
      groupId: v.groupId,
      groupName: v.groupDTO ? v.groupDTO.name : undefined,
      hosId: v.hosId,
      children: [],
      selectable: true,
      isLeaf: Boolean(v.nodeId),
      checked: false,
    }));
    console.log('buildingAndAddressList:', buildingAndAddressList);
    this.buildingAndAddressListCopy = this.tool.tranListToTreeData(buildingAndAddressListCopy, undefined, "parentId", "key");
    console.log('this.buildingAndAddressListCopy', this.buildingAndAddressListCopy);
  }

  // 处理巡检点数据
  generateList(addressList, selectableFlag = false){
    // 楼栋
    let buildingList = addressList.map((item) => {
      return {
        title: item.buildingDTO.buildingName,
        key: 'b-' + item.buildingDTO.id,
        children: [],
        selectable: selectableFlag,
        hosId: this.currentHospital.id,
      }
    })
    buildingList = uniqBy(buildingList, "key");
    // 巡检点
    addressList = addressList.map((item) => {
      return {
        title: item.name,
        key: item.id.toString(),
        parentId: 'b-' + item.buildingDTO.id,
        isLeaf: true,
        selectable: selectableFlag,
        hosId: this.currentHospital.id,
      }
    })
    let buildingAndAddressList = buildingList.concat(addressList);
    console.log(buildingAndAddressList);
    return buildingAndAddressList;
  }

  // 填写模板名称-确定
  templateLoading = false;
  templateFlag = false;
  submitFormHand(name){
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let nodeList = this.tool.tranTreeToListData(this.buildingAndAddressListCopy).map(v => ({
      nodeId: v.parentId ? Number(v.key) : undefined,
      userId: v.userId,
      groupId: v.groupId,
      hosId: v.hosId,
      buildId: v.parentId ? Number(v.parentId.replace(/b-/, '')): Number(v.key.replace(/b-/, '')),
    }));
    console.log(name);
    console.log(nodeList);
    console.log('保存并存为模板');
    let postData = {
      inspection: {
        ...this.planDetail,
        nodeList,
      },
      template: {
        hosId: this.currentHospital.id,
        name,
      },
    };
    console.log(postData);
    this.mainService
      .inspectionPost("templateToInspection", postData)
      .subscribe((result) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        if (result.status == 200) {
          this.message.success("保存成功");
          this.router.navigateByUrl("/main/inspectionPlan");
        } else {
          this.message.error(result.msg || '保存失败');
        }
      });
  }

  // 填写模板名称-取消
  cancelFlagHand(e) {
    this.templateFlag = false;
  }

  // 返回
  goBack(){
    this.router.navigateByUrl("/main/inspectionPlan");
  }

  // 保存并存为模板
  maskFlag: any = false;
  saveToTemplate(){
    let nodeList = this.tool.tranTreeToListData(this.buildingAndAddressListCopy);
    console.log(nodeList);
    if(!nodeList.length){
      this.message.warning('请选择至少一个巡检点');
      return;
    }
    this.templateFlag = true;
  }

  // 保存
  save(){
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let nodeList = this.tool.tranTreeToListData(this.buildingAndAddressListCopy).map(v => ({
      nodeId: v.parentId ? Number(v.key) : undefined,
      userId: v.userId,
      groupId: v.groupId,
      hosId: v.hosId,
      buildId: v.parentId ? Number(v.parentId.replace(/b-/, '')): Number(v.key.replace(/b-/, '')),
    }));
    console.log(nodeList);
    console.log('保存');
    let postData = {
      ...this.planDetail,
      nodeList,
      saveButton: '启动',
    };
    console.log(postData);
    this.mainService
      .simplePost("addData", "inspection", postData)
      .subscribe((result) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        if (result.status == 200) {
          this.message.success("保存成功");
          this.router.navigateByUrl("/main/inspectionPlan");
        } else {
          this.message.error(result.msg || '保存失败');
        }
      });
  }

  // 引入模板
  inspectionTemplatePromptModalShow = false;
  showInspectionTemplate() {
    this.inspectionTemplatePromptModalShow = true;
  }
  // 关闭弹窗
  closeModelInspectionTemplate(e) {
    this.inspectionTemplatePromptModalShow = JSON.parse(e).show;
  }
  // 确认弹窗
  confirmModelInspectionTemplate(tempId) {
    this.inspectionTemplatePromptModalShow = false;
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let postData = {
      idx: 0,
      sum: 9999,
      inspectionTempNodes: {
        tempId,
      }
    }
    this.mainService.getFetchDataList("simple/data", "inspectionTempNodes", postData).subscribe((result:any) => {
      this.message.remove(this.maskFlag);
      this.maskFlag = false;
      let nodeList = result.list || [];
      this.generateTree(nodeList);
    })
  }

  ngAfterViewInit(): void {
    // get node by key: '10011'
    console.log(this.nzTreeComponent.getTreeNodeByKey('10011'));
    // use tree methods
    console.log(
      this.nzTreeComponent.getTreeNodes(),
      this.nzTreeComponent.getCheckedNodeList(),
      this.nzTreeComponent.getSelectedNodeList(),
      this.nzTreeComponent.getExpandedNodeList()
    );
  }
}
