/*
 * Author: 黎永顺
 * name: 报表内容区
 * Description:
 * Date: 2023/4/21
 */
import React, { Component } from "react";
import { message, Spin } from "antd";
import { WeaEchart, WeaLocaleProvider } from "ecCom";
import RightOptions from "./rightOptions";
import ChartsRangeSettingsModal from "./chartsRangeSettingsModal";
import { mapBarOptions, mapLineOptions, mapPieOptions } from "./condition";
import { queryRangeSetting, reportStatisticsReportGetData } from "../../../apis/statistics";
import PovitpivotChartModal from "./povitpivotChartModal";
import { getSalaryMonthValue } from "./statisticalMicroSettingsSlide";
import "../index.less";

const getLabel = WeaLocaleProvider.getLabel;

class ReportContent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [],
      dataSource: [],
      countResult: {},
      loading: false,
      viewType: "dataView",
      chartsType: "0",
      chartsInfo: {},
      povitView: {
        visible: false, id: "", isShare: false, dimensionId: "", dimensionValue: "", salaryStartMonth: "",
        salaryEndMonth: ""
      },
      rangSet: {
        visible: false, reportId: "",
        rangeVal: {}
      },
      pageInfo: { current: 1, pageSize: 10, total: 0 }
    };
  }

  componentDidMount() {
    window.addEventListener("message", this.handleReceive, false);
    if (this.refs.chart) this.refs.chart.paint();
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.report !== this.props.report && nextProps.report.dimensionId) {
      this.reportStatisticsReportGetData(nextProps.report);
      this.setState({ viewType: "dataView", chartsInfo: {} });
    }
  }

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

  handleReceive = ({ data }) => {
    const { type, payload: { id, params } = {} } = data;
    if (type === "init") {
      const { columns, countResult, dataSource, pageInfo } = this.state;
      this.postMessageToChild({
        columns, countResult, dataSource, pageInfo,
        showSum: !_.isEmpty(countResult)
      });
    } else if (type === "turn") {
      //数据透视弹框
      if (id === "PIVOTCHART") {
        const { record } = params;
        const { dimension: dimensionValue } = record;
        const {
          id: pivotId, dimensionId, isShare, timeType, salaryEndMonth: end, salaryStartMonth: start
        } = this.props.report;
        const [salaryStartMonth, salaryEndMonth] = getSalaryMonthValue(timeType);

        this.setState({
          povitView: {
            visible: true, id: pivotId, dimensionId, dimensionValue, isShare,
            salaryStartMonth: (salaryStartMonth || start) + "-01", salaryEndMonth: (salaryEndMonth || end) + "-01"
          }
        });
      } else if (id === "PAGEINFO_REPORT") {
        this.setState({ pageInfo: { ...this.state.pageInfo, ...params } }, () => this.reportStatisticsReportGetData(this.props.report));
      }
    }
  };
  postMessageToChild = (payload) => {
    const i18n = {
      "共": getLabel(18609, "共"), "条": getLabel(18256, "条"),
      "总计": getLabel(523, "总计")
    };
    const childFrameObj = document.getElementById("atdTable");
    const { dataSource, columns, showSum, countResult, pageInfo } = payload;
    childFrameObj && childFrameObj.contentWindow.postMessage(JSON.stringify({
      dataSource, columns, showSum, countResult, i18n, pageInfo
    }), "*");
  };
  reportStatisticsReportGetData = (params) => {
    const { pageInfo } = this.state;
    const { id, dimension, dimensionId, isShare, timeType, salaryEndMonth: end, salaryStartMonth: start } = params;
    const [salaryStartMonth, salaryEndMonth] = getSalaryMonthValue(timeType);
    const payload = {
      id, dimensionId, isShare, ...pageInfo,
      salaryStartMonth: (salaryStartMonth || start) + "-01", salaryEndMonth: (salaryEndMonth || end) + "-01"
    };
    this.setState({ loading: true });
    reportStatisticsReportGetData(payload).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status && id.toString() === data.reportId.toString()) {
        const { countResult, columns, pageInfo: { list, pageNum, pageSize, total } } = data;
        this.setState({
          countResult, dataSource: list || [],
          pageInfo: dimension === getLabel(111, "人员") ? { ...pageInfo, current: pageNum, pageSize, total } : null,
          columns: _.map(columns, it => ({
            ...it,
            dataIndex: it.column, width: it.width ? it.width + "px" : 150,
            title: it.text, align: "center",
            children: !_.isNil(it.children) ? _.map(it.children, child => ({
              ...child,
              dataIndex: child.column, width: child.width ? child.width + "px" : 150,
              title: child.text, align: "center"
            })) : []
          }))
        }, () => {
          this.postMessageToChild({
            columns: this.state.columns, countResult: this.state.countResult,
            dataSource: this.state.dataSource, pageInfo: this.state.pageInfo,
            showSum: !_.isEmpty(this.state.countResult)
          });
        });
      }
    }).catch(() => this.setState({ loading: false }));
  };
  queryRangeSetting = (payload, isTab) => {
    const { dataSource, columns } = this.state;
    this.setState({ loading: true });
    queryRangeSetting(payload).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { rangSet, viewType } = this.state;
        const { itemValues, itemColValue, id } = data;
        this.setState({
          rangSet: {
            ...rangSet,
            rangeVal: data
          }
        });
        if (id) {
          if (!isTab) return;
          switch (viewType) {
            case "bar":
              this.setState({
                chartsInfo: {
                  name: _.find(_.reduce(_.filter(columns, col => !_.isNil(col.children)), (pre, cur) => ([...pre, ...cur.children]), []), it => it.column === itemColValue).text,
                  xAxis: _.reduce(itemValues, (pre, cur) => ([...pre, _.find(columns, item => item.column === cur).text]), []),
                  data: _.map(dataSource, item => {
                    return {
                      name: item.dimension,
                      data: _.map(itemValues, child => {
                        const key = child + itemColValue.slice(_.indexOf(itemColValue, "_"));
                        return item[key] || "0";
                      })
                    };
                  })
                }
              });
              break;
            case "line":
              this.setState({
                chartsInfo: {
                  xAxis: _.map(dataSource, it => it.dimension),
                  data: _.map(itemValues, item => {
                    return {
                      name: `${_.find(_.reduce(_.filter(columns, col => !_.isNil(col.children)), (pre, cur) => ([...pre, ...cur.children]), []), it => it.column === itemColValue).text}(${_.find(columns, it => it.column === item).text})`,
                      data: _.map(dataSource, child => {
                        const key = item + itemColValue.slice(_.indexOf(itemColValue, "_"));
                        return child[key] || "0";
                      })
                    };
                  })
                }
              });
              break;
            case "pie":
              this.setState({
                chartsInfo: {
                  data: _.map(itemValues, item => {
                    return {
                      name: _.find(_.reduce(_.filter(columns, col => !_.isNil(col.children)), (pre, cur) => ([...pre, ...cur.children]), []), it => it.column === itemColValue).text,
                      data: _.map(dataSource, child => {
                        return {
                          name: child["dimension"],
                          value: child[itemColValue]
                        };
                      })
                    };
                  })
                }
              });
              break;
            default:
              break;
          }
          if (this.refs.chart) this.refs.chart.paint();
        } else {
          this.setState({ chartsInfo: {} });
        }
      }
    }).catch(() => this.setState({ loading: false }));
  };
  handleChangeChartOpts = (chartsType, viewType) => {
    const { loading } = this.state;
    if (loading) {
      message.info(getLabel(111, "列表正在加载中，请稍后"));
      return;
    }
    this.setState({ chartsInfo: {} });
    if (this.refs.chart && viewType !== "setting" && viewType !== "dataView" && !this.state.rangSet.visible) this.refs.chart.clear();
    const { report: { id: reportId } } = this.props;
    const { rangSet } = this.state;
    viewType !== "setting" && this.setState({ chartsType, viewType }, () => {
      const { viewType, chartsType } = this.state;
      viewType !== "dataView" ?
        this.queryRangeSetting({ reportId, chartsType }, true) :
        this.reportStatisticsReportGetData(this.props.report);
    });
    viewType === "setting" && this.setState({ rangSet: { ...rangSet, visible: true, reportId } }, () => {
      this.queryRangeSetting({ reportId, chartsType });
    });
  };
  handleCancel = () => {
    this.setState({
      rangSet: {
        visible: false, reportId: "",
        rangeVal: {}
      }
    });
  };
  handleGetData = () => {
    const { report } = this.props;
    this.setState({ viewType: "dataView" }, () => this.reportStatisticsReportGetData(report));
  };
  renderCharts = () => {
    const { chartsInfo, viewType } = this.state;
    return _.isEmpty(chartsInfo) ?
      <ChartEmptyComp/> : (viewType === "bar" || viewType === "line" || viewType === "pie") ?
        <WeaEchart
          ref="chart" useDefault={false} className="chart"
          option={viewType === "bar" ? mapBarOptions(chartsInfo) : viewType === "line" ? mapLineOptions(chartsInfo) : mapPieOptions(chartsInfo)}
        /> :
        <div>123</div>;
  };

  render() {
    const { loading, viewType, rangSet, columns, povitView } = this.state;
    const { report } = this.props;
    const { isShare } = report;
    return (
      <div className="layoutContent">
        <div className="layoutBox">
          <Spin spinning={loading}>
            {
              viewType === "dataView" ?
                <iframe
                  style={{ border: 0, width: "100%", height: "100%" }}
                  // src="http://localhost:7607/#/reportTable"
                  src="/spa/hrmSalary/hrmSalaryCalculateDetail/index.html#/reportTable"
                  id="atdTable"
                /> : this.renderCharts()
            }
          </Spin>
        </div>
        {/*侧边栏*/}
        <RightOptions isShare={isShare} onChange={this.handleChangeChartOpts}/>
        {/* 图表范围数据设置框 */}
        <ChartsRangeSettingsModal
          {...rangSet}
          columns={columns}
          onCancel={this.handleCancel}
          onChange={this.queryRangeSetting}
          onGetData={this.handleGetData}
        />
        {/* 数据透视弹框*/}
        <PovitpivotChartModal
          {...povitView}
          onCancel={() => this.setState({
            povitView: {
              visible: false, id: "", dimensionId: "", dimensionValue: "",
              isShare: false, salaryStartMonth: "", salaryEndMonth: ""
            }
          })}
        />
      </div>
    );
  }
}

export default ReportContent;

const ChartEmptyComp = () => {
  return <div className="chartsEmptyWrapper">
    <span>
      <img src={require("../../../common/Icon-empty-file.svg")} alt=""/>
    </span>
    <span>暂无数据</span>
    <span>您还没有设置报表统计项，请先设置一下哦~</span>
  </div>;
};
