/*
  * 汇通建设二开
  * 社保福利台账报表
  * @Author:    黎永顺
  * @Date:      2024/11/22
  * @Wechat:
  * @Email:     971387674@qq.com
  * @description:
*/
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaDatePicker, WeaLoadingGlobal, WeaLocaleProvider, WeaTop } from "ecCom";
import { Button, Spin } from "antd";
import * as API from "../../../../apis/custom-apis/huitong";
import AdvanceSearchPannel from "./advanceSearchPannel";
import cs from "classnames";
import moment from "moment";

const getLabel = WeaLocaleProvider.getLabel;

@inject("HTStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pageInfo: { current: 1, pageSize: 10, total: 0 }, loading: false, showSearchAd: false,
      dataSource: [], columns: [], conditions: [], payload: {}, sumDataSource: {},
      query: { billMonth: moment(new Date()).format("YYYY-MM") }
    };
  }

  componentDidMount() {
    window.addEventListener("message", this.handleReceive, false);
  }

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

  handleReceive = ({ data }) => {
    const { pageInfo } = this.state;
    const { type, payload: { id, params } = {} } = data;
    if (type === "init") {
      this.getHTCommonListReport();
    } else if (type === "turn") {
      switch (id) {
        case "PAGEINFO":
          this.setState({ pageInfo: { ...pageInfo, ...params } }, () => this.getHTCommonListReport(false));
          break;
        default:
          break;
      }
    }
  };
  postMessageToChild = (payload = {}) => {
    const i18n = {
      "共": getLabel(18609, "共"), "条": getLabel(18256, "条"),
      "总计": getLabel(523, "总计")
    };
    const childFrameObj = document.getElementById("unitTable");
    childFrameObj && childFrameObj.contentWindow.postMessage(JSON.stringify({ ...payload, i18n }), "*");
  };
  getHTCommonListReport = (updateSum = true) => {
    const { HTStore: { queryForm } } = this.props, { pageInfo, query } = this.state;
    const advanceSearch = _.reduce(_.keys(queryForm.getFormParams()), (pre, cur) => {
      return {
        ...pre, [cur]: !_.isEmpty(queryForm.getFormParams()[cur]) ? queryForm.getFormParams()[cur].split(",") : []
      };
    }, {});
    const payload = { ...pageInfo, ...query, ...advanceSearch };
    this.setState({ loading: true });
    API.getHTCommonListReport(payload).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { columns, pageInfo: result } = data;
        const { list: dataSource, pageNum: current, pageSize, total } = result;
        this.setState({
          pageInfo: { ...pageInfo, current, pageSize, total }, dataSource, payload,
          columns: _.map(columns, o => ({
            title: o.text, dataIndex: o.column, width: o.width, ellipsis: true, fixed: o.fixed || false
          }))
        }, () => {
          const result = {
            scrollHeight: 152, dataSource: this.state.dataSource, columns: this.state.columns,
            pageInfo: this.state.pageInfo, unitTableType: "999", showRowSelection: false,
            showTotalCell: true, sumDataSource: this.state.sumDataSource
          };
          this.postMessageToChild(result);
          if (updateSum) this.getHTCommonListReportSum(payload, result);
        });
      }
    }).catch(() => this.setState({ loading: false }));
  };
  getHTCommonListReportSum = (payload, result) => {
    WeaLoadingGlobal.start();
    API.getHTCommonListReportSum(payload).then(({ status, data }) => {
      WeaLoadingGlobal.end();
      WeaLoadingGlobal.destroy();
      if (status) this.setState({ sumDataSource: data.sumRow }, () => this.postMessageToChild({
        ...result, sumDataSource: data.sumRow
      }));
    });
  };
  handleExport = () => {
    WeaLoadingGlobal.start();
    const promise = API.exportHtCommonList(this.state.payload);
  };

  render() {
    const { showSearchAd, pageInfo, loading, dataSource, query } = this.state;
    const dom = document.querySelector(".wea-new-top-content");
    let height = 330;
    if (dataSource.length > 0 && dom) {
      const tableHeight = dataSource.length * 46 + 162;
      const containerHeight = parseFloat(dom.style.height) - 8;
      height = containerHeight > tableHeight ? tableHeight : containerHeight;
    }
    return (<WeaTop title={getLabel(111, "社保福利台账报表")} className="custom_data_huitong"
                    icon={<i className="icon-coms-fa"/>} showDropIcon={false} iconBgcolor="#F14A2D"
                    buttons={[
                      <Button type="primary" onClick={this.handleExport}>{getLabel(111, "导出")}</Button>,
                      <WeaDatePicker format="YYYY-MM" value={query.billMonth} onChange={v => this.setState({
                        query: { ...query, billMonth: v }, pageInfo: { ...pageInfo, current: 1 }
                      }, () => this.getHTCommonListReport())}/>,
                      <Button type="ghost"
                              onClick={() => this.setState({ showSearchAd: true })}>{getLabel(111, "高级搜索")}</Button>
                    ]}>
      <div className="huitong-body">
        <div className={cs("searchAdvanced-condition-container", { "searchAdvanced-condition-hide": !showSearchAd })}>
          <AdvanceSearchPannel onCancel={() => this.setState({ showSearchAd: false })}
                               onAdSearch={() => this.setState({
                                 pageInfo: { ...pageInfo, current: 1 }, showSearchAd: false
                               }, () => this.getHTCommonListReport())}/>
        </div>
        <div className="custom_huitong_list" style={{ height }}>
          <Spin spinning={loading}>
            <iframe
              style={{ border: 0, width: "100%", height: "100%" }}
              // src="http://localhost:7607/#/unitTable"
              src="/spa/hrmSalary/hrmSalaryCalculateDetail/index.html#/unitTable"
              id="unitTable"
            />
          </Spin>
        </div>
      </div>
    </WeaTop>);
  }
}

export default Index;
