/*
 * Author: 黎永顺
 * name: 薪资项目拓扑图-查看
 * Description:
 * Date: 2023/10/26
 */
import React, { Component } from "react";
import { WeaLocaleProvider } from "ecCom";
import SalaryItemDiagram from "../salaryItemDiagram";
import { getQueryString } from "../../util/url";
import { getSalaryItemTopology } from "../../apis/ledger";
import uuidV4 from "uuid/v4";

const getLabel = WeaLocaleProvider.getLabel;

class Index extends Component {
  componentDidMount() {
    window.addEventListener("message", this.handleReceive, false);
  }

  handleReceive = async ({ data }) => {
    const { type } = data;
    if (type === "initDiagram") this.postMessageToChild();
  };

  componentWillUnmount() {
    window.removeEventListener("message", this.handleReceive, false);
  }

  postMessageToChild = async () => {
    const i18n = { "薪资项目": getLabel(542362, "薪资项目"), "公式": getLabel(18125, "公式") };
    const { params: payload = {} } = this.props;
    const acctEmpId = getQueryString("acctEmpId"), type = getQueryString("type");
    let itemsTree = [];
    if (type === "ledger") {
      const { data } = await getSalaryItemTopology({ ...payload });
      itemsTree = this.convertToTreeDatas([data]);
    }
    const childFrameObj = document.getElementById("topologyDiagram");
    childFrameObj.contentWindow.postMessage(JSON.stringify({ ...payload, i18n, acctEmpId, itemsTree }), "*");
  };
  convertToTreeDatas = (datas, parentId = "0") => {
    return _.map(datas, item => {
      if (_.isEmpty(item.children)) {
        return { ...item, salaryItemId: item.salaryItemId ? item.salaryItemId.toString() : uuidV4(), parentId };
      } else {
        return {
          ...item, parentId, salaryItemId: item.salaryItemId.toString(),
          children: this.convertToTreeDatas(item.children, item.salaryItemId.toString())
        };
      }
    });
  };

  render() {
    const type = getQueryString("type");
    const pathname = type === "ledger" ? "ledgerSalaryItemDiagram" : "salaryItemDiagram";
    return (
      <div style={{ width: "100%", height: "100%" }}>
        <SalaryItemDiagram pathname={pathname}/>
      </div>
    );
  }
}

export default Index;
