/*
 * Author: 黎永顺
 * name: 薪资档案页面重构-列表
 * Description:
 * Date: 2024/1/8
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaLoadingGlobal, WeaLocaleProvider } from "ecCom";
import { WeaTableNew } from "comsMobx";
import SalaryFilesEditSlide from "../salaryFilesEditSlide";
import { toJS } from "mobx";
import { message, Spin } from "antd";
import * as API from "../../../../apis/payrollFiles";

const WeaTableComx = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
const URLLIST = {
  pending: "/api/bs/hrmsalary/salaryArchive/pendingList",
  fixed: "/api/bs/hrmsalary/salaryArchive/fixedList",
  suspend: "/api/bs/hrmsalary/salaryArchive/suspendList",
  stop: "/api/bs/hrmsalary/salaryArchive/stopList",
  ext: "/api/bs/hrmsalary/salaryArchive/extList"
};
const APILIST = {
  addToSalarypayment: API.gotoFixed, //设为发薪员工
  delPenditngToDo: API.deletePendingTodo, //待定薪删除待办
  delSalaryFiles: API.deleteSalaryArchive, //删除薪资档案
  salarySuspension: API.gotoStop, //停薪
  delSuspendToDo: API.deleteSuspendTodo, //待停薪删除待办
  cancelSalarySuspension: API.cancelStop //取消停薪
};

@inject("payrollFilesStore", "taxAgentStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [], columns: [], loading: false, selectedRowKeys: [],
      pageInfo: { current: 1, pageSize: 10, total: 0 },
      salaryFilesEditSlide: { visible: false, salaryArchiveId: "" }
    };
    this.SFSlideRef = null;
  }

  componentDidMount() {
    this.getSalaryFileList(this.props, true);
    window.addEventListener("message", this.handleReceive, false);
    window.addEventListener("resize", this.handleResize, false);
  }

  handleResize = () => {
    this.forceUpdate();
  };

  componentWillReceiveProps(nextProps, nextContext) {
    if ((nextProps.selectedKey !== this.props.selectedKey) || (nextProps.isQuery !== this.props.isQuery)) {
      this.setState({
        pageInfo: { ...this.state.pageInfo, current: 1, pageSize: 10, total: 0 }
      }, () => this.getSalaryFileList(nextProps));
    }
    if ((nextProps.selectedKey !== this.props.selectedKey)) {
      this.setState({
        dataSource: [], columns: [], loading: false, selectedRowKeys: [],
        salaryFilesEditSlide: { ...this.state.salaryFilesEditSlide, visible: false }
      });
    }
  }

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

  handleReceive = async ({ data }) => {
    const { type, payload: { id, params } = {} } = data;
    if (type === "init") {
      this.getColumns();
    } else if (type === "turn") {
      switch (id) {
        case "PAGEINFO":
          this.setState({
            pageInfo: { ...this.state.pageInfo, ...params }
          }, () => this.getSalaryFileList(this.props));
          break;
        case "ROWSELECTION":
          const { selectedRowKeys } = params;
          this.setState({ selectedRowKeys });
          break;
        case "ADD-TO-SALARYPAYMENT":
        case "DEL-PENDITNG-TO-DO":
        case "DEL-SALARY-FILES":
        case "SALARY-SUSPENSION":
        case "DEL-SUSPEND-TO-DO":
        case "CANCEL-SALARY-SUSPENSION":
          const { interfaceParams } = params;
          this.handleSalaryOpts(_.camelCase(id), interfaceParams);
          break;
        case "CHANGE-SALARY":
        case "VIEW":
        case "EDIT":
          const { taxAgentStore: { showOperateBtn }, selectedKey: runStatuses } = this.props;
          const { record: { id: salaryArchiveId } } = params;
          this.setState({
            salaryFilesEditSlide: {
              ...this.state.salaryFilesEditSlide, visible: true, salaryArchiveId,
              runStatuses, showOperateBtn
            }
          });
          break;
        case "log":
          this.props.onFilterLog(id, params.record.id);
          break;
        default:
          break;
      }
    }
  };
  handleSalaryOpts = (type, payload) => {
    WeaLoadingGlobal.start();
    APILIST[type](payload).then(({ status, data = {}, errormsg }) => {
      WeaLoadingGlobal.destroy();
      if (status) {
        const { msg, type } = data;
        if (type === "fail" || type === "info") {
          message.error(msg);
        } else if (type === "success") {
          message.success(msg);
          this.getSalaryFileList(this.props);
          this.setState({ selectedRowKeys: [] });
        } else {
          message.success(getLabel(30700, "操作成功！"));
          this.getSalaryFileList(this.props);
          this.setState({ selectedRowKeys: [] });
        }
      } else {
        message.error(errormsg);
      }
    });
  };
  postMessageToChild = (payload = {}) => {
    const i18n = {
      "操作": getLabel(30585, "操作"), "调薪": getLabel(542686, "调薪"),
      "增员": getLabel(543180, "增员"), "删除档案": getLabel(23238, "删除档案"),
      "删除待办": getLabel(543181, "删除待办"), "查看": getLabel(33564, "查看"),
      "取消停薪": getLabel(543309, "取消停薪"), "共": getLabel(18609, "共"),
      "条": getLabel(18256, "条"), "设为发薪人员": getLabel(543308, "设为发薪人员"),
      "停薪": getLabel(542692, "停薪"), "编辑": getLabel(501169, "编辑"),
      "操作日志": getLabel(545781, "操作日志")
    };
    const childFrameObj = document.getElementById("atdTable");
    childFrameObj && childFrameObj.contentWindow.postMessage(JSON.stringify({ ...payload, i18n }), "*");
  };
  getSalaryFileList = (props, init = false) => {
    const { pageInfo } = this.state;
    const {
      payrollFilesStore: { salaryFileQueryForm, queryList }, selectedKey, onChangeTopTabCount
    } = props;
    this.setState({ loading: true });
    queryList(pageInfo, salaryFileQueryForm.getFormParams(), URLLIST[selectedKey]).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { pageInfo: result } = data;
        const { list: dataSource, total, pageNum: current, pageSize } = result;
        this.setState({
          pageInfo: { ...pageInfo, current, pageSize, total }, dataSource
        }, () => {
          onChangeTopTabCount(selectedKey, total, init);
        });
      }
    }).catch(() => this.setState({ loading: false }));
  };
  getColumns = () => {
    const { payrollFilesStore: { tableStore }, taxAgentStore: { showOperateBtn } } = this.props;
    const columns = _.map(_.filter(toJS(tableStore.columns), (item) => item.display === "true"), (it, idx) => ({
      dataIndex: it.dataIndex, title: it.title, align: "left",
      width: (it.dataIndex === "taxAgentName" || it.dataIndex === "operate") ? 185 : 150,
      fixed: it.dataIndex === "username" ? "left" : it.dataIndex === "operate" ? "right" : it.fixed ? it.fixed : false,
      ellipsis: true
    }));
    if (!_.isEmpty(columns)) {
      this.postMessageToChild({
        columns, showOperateBtn, selectedKey: this.props.selectedKey,
        showDelSalaryFileBtn: this.props.showDelSalaryFileBtn,
        dataSource: this.state.dataSource, selectedRowKeys: this.state.selectedRowKeys,
        showSum: false, pageInfo: this.state.pageInfo
      });
    }
  };

  render() {
    const { loading, dataSource, salaryFilesEditSlide } = this.state;
    const { payrollFilesStore: { tableStore } } = this.props;
    const dom = document.querySelector(".wea-new-top-req-content");
    let height = 280;
    if (dom && dataSource.length > 0) {
      height = (parseFloat(dom.style.height) > 620 && dataSource.length === 10) ? dataSource.length * 39 + 113 : dataSource.length < 10 ? dataSource.length * 39 + 113 : parseFloat(dom.style.height) - 16;
    }
    return (
      <div className="table-layout" style={{ height: height + "px" }}>
        <Spin spinning={loading}>
          <iframe
            style={{ border: 0, width: "100%", height: "100%" }}
            // src="http://localhost:7607/#/salaryFileTable"
            src="/spa/hrmSalary/hrmSalaryCalculateDetail/index.html#/salaryFileTable"
            id="atdTable"
          />
        </Spin>
        <WeaTableComx
          style={{ display: "none" }}
          comsWeaTableStore={tableStore}
          needScroll={true}
          columns={this.getColumns()}
        />
        {/* 编辑查看员工薪资档案*/}
        <SalaryFilesEditSlide {...salaryFilesEditSlide} ref={dom => this.SFSlideRef = dom}
                              onClose={(isFresh) => this.setState({
                                salaryFilesEditSlide: { ...salaryFilesEditSlide, visible: isFresh }
                              }, () => isFresh && this.getSalaryFileList(this.props))}
        />
      </div>
    );
  }
}

export default Index;
