/*
 * Author: 黎永顺
 * name:社保福利档案页面重构-列表
 * Description:
 * Date: 2023/10/31
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaLoadingGlobal, WeaLocaleProvider } from "ecCom";
import { message, Modal, Spin } from "antd";
import WelfareEditArchiveSlide from "../welfareEditArchiveSlide";
import * as API from "../../../../../apis/welfareArchive";
import { welfareTypeEnum } from "../../config";
import { getConditionDomkeys, getConditionFields } from "../../../../../util";

const getLabel = WeaLocaleProvider.getLabel;
const APILIST = {
  runStatuses: API.queryList,
  ext: API.getExtTable,
  delToDo: API.updateRunStatus, //删除待办
  delArchive: API.deleteArchive, //删除档案
  addToPay: API.stayAddToPay, //增员
  stayDelToStop: API.stayDelToStop, //减员
  delToDoStay: API.cancelStayDel, //待减员-删除待办
  cancelStop: API.cancelStopPayment //停缴员工-取消停缴
};

@inject("archivesStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [], columns: [], loading: false, selectedRowKeys: [],
      pageInfo: { current: 1, pageSize: 10, total: 0 },
      welfareEditSlide: { visible: false, employeeId: "", welfareTypeEnum: "", paymentOrganization: "" }
    };
  }

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

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

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

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

  handleReceive = async ({ data }) => {
    const { type, payload: { id, params } = {} } = data;
    if (type === "init") {
      this.getWelfareList(this.props, true);
    } else if (type === "turn") {
      const { record: { baseInfo, employeeId, paymentOrganization } = {}, interfaceParams = {} } = params;
      const { runStatuses, showOperateBtn } = this.props;
      switch (id) {
        case "PAGEINFO":
          this.setState({
            pageInfo: { ...this.state.pageInfo, ...params }
          }, () => this.getWelfareList(this.props));
          break;
        case "CHECKBOX":
          const { selectedRowKeys } = params;
          this.setState({ selectedRowKeys });
          break;
        case "EDIT":
        case "VIEW":
          const payload = { employeeId, paymentOrganization };
          const [socialItems, fundItems, othersItems] = await Promise.all([
            this.getProfileTypeForm({ ...payload, welfareTypeEnum: welfareTypeEnum["social"] }),
            this.getProfileTypeForm({ ...payload, welfareTypeEnum: welfareTypeEnum["fund"] }),
            this.getProfileTypeForm({ ...payload, welfareTypeEnum: welfareTypeEnum["other"] })
          ]);
          this.setState({
            welfareEditSlide: {
              ...this.state.welfareEditSlide, employeeId, paymentOrganization, runStatuses,
              socialItems: socialItems.data.items[0].items,
              socialBaseData: {
                SOCIAL_SECURITY: { ...socialItems.data.data, socialUnderTake: socialItems.data.data.underTake }
              },
              fundItems: fundItems.data.items[0].items,
              fundBaseData: {
                ACCUMULATION_FUND: { ...fundItems.data.data, fundUnderTake: fundItems.data.data.underTake }
              },
              othersItems: othersItems.data.items[0].items,
              othersBaseData: { OTHER: { ...othersItems.data.data, otherUnderTake: othersItems.data.data.underTake } }
            }
          }, async () => {
            const { socialBaseData, fundBaseData, othersBaseData } = this.state.welfareEditSlide;
            const { SOCIAL_SECURITY: { socialSchemeId } } = socialBaseData,
              { ACCUMULATION_FUND: { fundSchemeId } } = fundBaseData,
              { OTHER: { otherSchemeId } } = othersBaseData;
            const [socialBase, fundBase, otherBase] = await Promise.all([
              this.getPaymentForm({ ...payload, welfareTypeEnum: welfareTypeEnum["social"], schemeId: socialSchemeId }),
              this.getPaymentForm({ ...payload, welfareTypeEnum: welfareTypeEnum["fund"], schemeId: fundSchemeId }),
              this.getPaymentForm({ ...payload, welfareTypeEnum: welfareTypeEnum["other"], schemeId: otherSchemeId })
            ]);
            this.setState({
              welfareEditSlide: {
                ...this.state.welfareEditSlide, visible: true, showOperateBtn,
                socialBase: socialBase.data, fundBase: fundBase.data, otherBase: otherBase.data
              }
            });
          });
          break;
        case "ADD-TO-PAY":
        case "STAY-DEL-TO-STOP":
        case "CANCEL-STOP":
        case "DEL-TO-DO":
        case "DEL-TO-DO-STAY":
          const module = (id === "ADD-TO-PAY" || id === "STAY-DEL-TO-STOP" || id === "CANCEL-STOP") ?
            [baseInfo] : { ids: [baseInfo], ...interfaceParams };
          this.handleWelfareOpts(_.camelCase(id), module);
          break;
        case "DEL-ARCHIVE":
          Modal.confirm({
            title: getLabel(131329, "信息确认"),
            content: getLabel(388758, "确认要删除吗？"),
            onOk: () => this.handleWelfareOpts(_.camelCase(id), [baseInfo])
          });
          break;
        case "log":
          this.props.onFilterLog(id, baseInfo);
          break;
        default:
          break;
      }
    }
  };
  getProfileTypeForm = async (props) => {
    const { employeeId, paymentOrganization, welfareTypeEnum } = props;
    const payload = { employeeId, paymentOrganization, welfareTypeEnum };
    return API.getBaseForm(payload);
  };
  getPaymentForm = async (props) => {
    return API.getPaymentForm({ ...props });
  };
  getWelfareList = (props, init = false) => {
    const { pageInfo } = this.state;
    const { archivesStore: { welfareForm }, runStatuses, onChangeTopTabCount, showOperateBtn } = props;
    const params = { ...pageInfo, ...welfareForm.getFormParams() };
    const payload = runStatuses === "ext" ? { ...params, extWelArchiveList: true } : {
      ...params,
      runStatuses: runStatuses.split(",")
    };
    this.setState({ loading: true });
    APILIST[runStatuses === "ext" ? "ext" : "runStatuses"](payload).then(({ status, data }) => {
      this.setState({ loading: false });
      if (status) {
        const { columns, datas: dataSource, pageInfo: { pageNum: current, pageSize, total } } = data;
        this.setState({
          pageInfo: { ...pageInfo, current, pageSize, total }, dataSource,
          columns: _.map(columns, o => {
            const { column: dataIndex, text: title, width, fixed } = o;
            if (dataIndex === "employeeName") {
              return {
                dataIndex, title, width, fixed: "left", ellipsis: true
              };
            }
            return {
              dataIndex, title, width, ellipsis: true, fixed: fixed || false
            };
          })
        }, () => {
          const { pageInfo, selectedRowKeys, columns, dataSource } = this.state;
          onChangeTopTabCount(runStatuses, total, init);
          this.postMessageToChild({
            dataSource, pageInfo, selectedRowKeys, runStatuses,
            columns, showOperateBtn
          });
        });
      }
    }).catch(() => this.setState({ loading: false }));
  };
  /*
   * Author: 黎永顺
   * Description:批量操作
   * Params:
   * Date: 2023/11/3
   */
  handleBatchOpt = (type, payload) => {
    const { selectedRowKeys } = this.state;
    if (_.isEmpty(selectedRowKeys)) {
      message.warning(getLabel(543303, "请选择表格数据"));
      return;
    }
    const params = _.isNil(payload) ? selectedRowKeys : { ids: selectedRowKeys, ...payload };
    this.handleWelfareOpts(type, params);
  };
  handleWelfareOpts = (type, payload) => {
    WeaLoadingGlobal.start();
    APILIST[type](payload).then(({ status, data = {}, errormsg }) => {
      WeaLoadingGlobal.destroy();
      if (status) {
        const { msg, type } = data;
        if (type === "fail") {
          message.error(msg);
        } else if (type === "success") {
          message.success(msg);
          this.getWelfareList(this.props);
          this.setState({ selectedRowKeys: [] });
        } else {
          message.success(getLabel(30700, "操作成功！"));
          this.getWelfareList(this.props);
          this.setState({ selectedRowKeys: [] });
        }
      } else {
        message.error(errormsg);
      }
    });
  };
  postMessageToChild = (payload = {}) => {
    const i18n = {
      "操作": getLabel(30585, "操作"), "编辑": getLabel(501169, "编辑"),
      "增员": getLabel(543180, "增员"), "删除档案": getLabel(23238, "删除档案"),
      "删除待办": getLabel(543181, "删除待办"), "减员": getLabel(543182, "减员"),
      "查看": getLabel(33564, "查看"), "取消停缴": getLabel(543183, "取消停缴"),
      "共": getLabel(18609, "共"), "条": getLabel(18256, "条"),
      "操作日志": getLabel(545781, "操作日志")
    };
    const childFrameObj = document.getElementById("atdTable");
    childFrameObj && childFrameObj.contentWindow.postMessage(JSON.stringify({ ...payload, i18n }), "*");
  };
  handleChangeProgramme = (type, schemeId, payload) => {
    this.getPaymentForm({ ...payload, welfareTypeEnum: welfareTypeEnum[type], schemeId })
      .then(({ status, data }) => {
        if (status) {
          const { data: defVal, items, comData, comItems } = data;
          this.setState({
            welfareEditSlide: { ...this.state.welfareEditSlide, [`${type}Base`]: data }
          }, () => {
            const perData = _.reduce(getConditionDomkeys(items), (pre, cur) => {
              const minNum = !_.isNil(getConditionFields(items)[cur].min) ? Number(getConditionFields(items)[cur].min) : undefined,
                maxNum = !_.isNil(getConditionFields(items)[cur].max) ? Number(getConditionFields(items)[cur].max) : undefined;
              const val = !_.isNil(defVal) ? Number(defVal[cur]) : 0;
              return {
                ...pre,
                [cur]: (val < minNum && !!minNum) ? minNum : (val > maxNum && !!maxNum) ? maxNum : val
              };
            }, {});
            if (!_.isNil(comItems)) {
              const comDataTmpv = _.reduce(getConditionDomkeys(comItems), (pre, cur) => {
                const minNum = !_.isNil(getConditionFields(comItems)[cur].min) ? Number(getConditionFields(comItems)[cur].min) : undefined,
                  maxNum = !_.isNil(getConditionFields(comItems)[cur].max) ? Number(getConditionFields(comItems)[cur].max) : undefined;
                const val = !_.isNil(comData) ? Number(comData[cur]) : 0;
                return {
                  ...pre,
                  [`${cur}_com`]: (val < minNum && !!minNum) ? minNum : (val > maxNum && !!maxNum) ? maxNum : val
                };
              }, {});
              this.archiveSlideRef.wrappedInstance.updateFormData({ ...perData, ...comDataTmpv });
              return;
            }
            this.archiveSlideRef.wrappedInstance.updateFormData({ ...perData });
          });
        }
      });
  };

  render() {
    const { loading, dataSource, welfareEditSlide } = this.state;
    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) - 170;
    }
    return (
      <div className="table-layout" style={{ height: height + "px" }}>
        <Spin spinning={loading}>
          <iframe
            style={{ border: 0, width: "100%", height: "100%" }}
            // src="http://localhost:7607/#/welfareArchiveTable"
            src="/spa/hrmSalary/hrmSalaryCalculateDetail/index.html#/welfareArchiveTable"
            id="atdTable"
          />
        </Spin>
        {/* 编辑查看员工福利档案*/}
        <WelfareEditArchiveSlide {...welfareEditSlide} ref={dom => this.archiveSlideRef = dom}
                                 onClose={(isFresh) => this.setState({
                                   welfareEditSlide: { ...welfareEditSlide, visible: false }
                                 }, () => isFresh && this.getWelfareList(this.props))}
                                 onChangeProgramme={this.handleChangeProgramme}
        />
      </div>
    );
  }
}

export default Index;
