/*
 * Author: 黎永顺
 * name: 员工明细查看
 * Description:
 * Date: 2023/5/24
 */
import React, { Component } from "react";
import { WeaLocaleProvider, WeaSelect, WeaTop } from "ecCom";
import { WeaTableNew } from "comsMobx";
import { toJS } from "mobx";
import { Spin } from "antd";
import { inject, observer } from "mobx-react";
import { MonthRangePicker } from "../reportView/components/statisticalMicroSettingsSlide";
import { optionAddWhole } from "../../util/options";
import moment from "moment";
import "./index.less";

const WeaTableComx = WeaTableNew.WeaTable;
const { getLabel } = WeaLocaleProvider;

@inject("taxAgentStore", "payrollFilesStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      taxAgentId: "",
      countResult: {},
      salaryMonth: [moment().startOf("year").format("YYYY-MM"), moment().format("YYYY-MM")],
      dataSource: [],
      pageInfo: {
        current: 1,
        pageSize: 10,
        total: 0
      }
    };
  }

  componentWillMount() {
    const { taxAgentStore: { fetchTaxAgentOption } } = this.props;
    fetchTaxAgentOption();
  }

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

  handleReceive = ({ data }) => {
    const { type, payload: { id, params } = {} } = data;
    const { dataSource, pageInfo, countResult } = this.state;
    const { payrollFilesStore: { employeeTableStore } } = this.props;
    const columns = _.filter(toJS(employeeTableStore.columns), (item) => item.display === "true" && item.dataIndex !== "acctTimes");
    if (type === "init") {
      this.postMessageToChild({
        columns: _.map(columns, (it, idx) => ({
          ...it,
          width: (it.dataIndex === "taxAgent" || it.dataIndex === "salarySob") ? 176 : it.oldWidth,
          fixed: (idx === 1 || idx === 0 || idx === 2) ? "left" : "",
          ellipsis: true
        })), dataSource, countResult,
        showSum: true, pageInfo
      });
    } else if (type === "turn") {
      if (id === "PAGEINFO") {
        const { pageNum: current, size: pageSize } = params;
        this.setState({ pageInfo: { ...pageInfo, current, pageSize } }, () => this.statisticsEmployeeDetailList());
      }
    }
  };
  postMessageToChild = (payload) => {
    const childFrameObj = document.getElementById("atdTable");
    const { dataSource, columns, showSum, pageInfo, countResult } = payload;
    childFrameObj && childFrameObj.contentWindow.postMessage(JSON.stringify({
      dataSource, columns, showSum, pageInfo, countResult
    }), "*");
  };

  statisticsEmployeeDetailList = () => {
    const { params: { employeeId }, payrollFilesStore: { statisticsEmployeeDetailList } } = this.props;
    const { taxAgentId, salaryMonth, pageInfo } = this.state;
    const payload = {
      employeeId, taxAgentId,
      salaryMonth: salaryMonth.map(item => moment(item).format("YYYY-MM-DD")),
      ...pageInfo
    };
    this.setState({ loading: true });
    statisticsEmployeeDetailList(payload).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { countResult, pageInfo: { list, pageNum: current, pageSize, total } } = data;
        this.setState({
          countResult,
          dataSource: list || [],
          pageInfo: { ...pageInfo, current, pageSize, total }
        }, () => {
          // this.postMessageToChild({
          //   columns: this.state.columns,
          //   dataSource: this.state.dataSource,
          //   showSum: false, pageInfo: this.state.pageInfo
          // });
        });
      }
    }).catch(() => this.setState({ loading: false }));
  };

  getColumns = () => {
    const { dataSource, pageInfo, countResult } = this.state;
    const { payrollFilesStore: { employeeTableStore } } = this.props;
    const columns = _.filter(toJS(employeeTableStore.columns), (item) => item.display === "true" && item.dataIndex !== "acctTimes");
    this.postMessageToChild({
      columns: _.map(columns, (it, idx) => ({
        ...it,
        width: (it.dataIndex === "taxAgent" || it.dataIndex === "salarySob") ? 176 : it.oldWidth,
        fixed: (idx === 1 || idx === 0 || idx === 2) ? "left" : "",
        ellipsis: true
      })), dataSource, countResult,
      showSum: true, pageInfo
    });
  };

  render() {
    const {
      location,
      taxAgentStore: { showOperateBtn, taxAgentOption },
      payrollFilesStore: { employeeTableStore }
    } = this.props;
    const { salaryMonth, taxAgentId, loading } = this.state;
    const { query: { dept, name } } = location;
    const btns = [
      <MonthRangePicker viewAttr={2} dateRange={salaryMonth}
                        onChange={v => this.setState({ salaryMonth: v }, () => this.statisticsEmployeeDetailList())}/>,
      <WeaSelect options={optionAddWhole(taxAgentOption)} value={taxAgentId} style={{ width: 200 }}
                 onChange={v => this.setState({ taxAgentId: v }, () => this.statisticsEmployeeDetailList())}/>
    ];
    const dropMenuDatas = [
      {
        key: "BTN_COLUMN",
        icon: <i className="icon-coms-Custom"/>,
        content: "显示列定制",
        onClick: () => {
          employeeTableStore.setColSetVisible(true);
          employeeTableStore.tableColSet(true);
        }
      }
    ];
    return (
      <WeaTop
        title={<span><span style={{ marginRight: 8 }}>{name}</span><span>{dept}</span></span>}
        icon={<i className="icon-coms-fa"/>} buttons={showOperateBtn ? btns : []}
        iconBgcolor="#F14A2D" showDropIcon={true} dropMenuDatas={dropMenuDatas}
      >
        <div className="employeeDetailWrapper">
          <Spin spinning={loading}>
            <iframe
              style={{ border: 0, width: "100%", height: "100%" }}
              // src="http://localhost:7607/#/commonTable"
              src="/spa/hrmSalary/hrmSalaryCalculateDetail/index.html#/commonTable"
              id="atdTable"
            />
          </Spin>
        </div>
        <WeaTableComx
          style={{ display: "none" }}
          comsWeaTableStore={employeeTableStore}
          needScroll={true}
          columns={this.getColumns()}
        />
      </WeaTop>
    );
  }
}

export default Index;
