/*
 * Author: 黎永顺
 * name: 添加补差人员
 * Description:
 * Date: 2023/11/28
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaDialog, WeaInputNumber, WeaLocaleProvider, WeaSearchGroup, WeaTableEdit } from "ecCom";
import * as API from "../../../../apis/standingBook";
import { Button, message } from "antd";
import { addPersonConditions } from "../constant";
import { getSearchs, toDecimal_n } from "../../../../util";
import { convertData } from "./supplementarySlide";

const getLabel = WeaLocaleProvider.getLabel;

@inject("standingBookStore")
@observer
class AddCompensationPersonnelDialog extends Component {
  constructor(props) {
    super(props);
    this.state = {
      conditions: [], paymentList: [
        { title: getLabel(538967, "社保"), titleSign: "social", payment: [] },
        { title: getLabel(538969, "公积金"), titleSign: "fund", payment: [] },
        { title: getLabel(542518, "企业年金及其它福利"), titleSign: "other", payment: [] }
      ], loading: false
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      const { standingBookStore: { addCPForm } } = nextProps;
      this.setState({
        conditions: _.map(addPersonConditions, o => {
          return {
            ...o,
            items: _.map(o.items, g => ({
              ...g, label: getLabel(g.lanId, g.label)
            })),
            title: getLabel(111, "补差人员")
          };
        })
      }, () => addCPForm.initFormFields(this.state.conditions));
    }
    if (nextProps.visible !== this.props.visible && !nextProps.visible) nextProps.standingBookStore.initAddCPForm();
  }

  getBalancePaymentGroup = () => {
    const { standingBookStore: { addCPForm }, paymentOrganization } = this.props;
    const payload = { ...addCPForm.getFormParams(), paymentOrganization };
    API.getBalancePaymentGroup(payload).then(({ status, data }) => {
      if (status && !_.isEmpty(data)) {
        this.setState({
          paymentList: [
            {
              title: getLabel(538967, "社保"), titleSign: "social",
              payment: convertData(_.filter(data, it => it.titleSign === "social"))
            },
            {
              title: getLabel(538969, "公积金"), titleSign: "fund",
              payment: convertData(_.filter(data, it => it.titleSign === "fund"))
            },
            {
              title: getLabel(542518, "企业年金及其它福利"), titleSign: "other",
              payment: convertData(_.filter(data, it => it.titleSign === "other"))
            }
          ]
        });
      } else {
        message.error(getLabel(111, "数据不存在！"));
        this.setState({
          paymentList: [
            { title: getLabel(538967, "社保"), titleSign: "social", payment: [] },
            { title: getLabel(538969, "公积金"), titleSign: "fund", payment: [] },
            { title: getLabel(542518, "企业年金及其它福利"), titleSign: "other", payment: [] }
          ]
        });
      }
    });
  };
  renderColumns = () => {
    return [
      {
        title: getLabel(543262, "福利项"),
        dataIndex: "insuranceName",
        key: "insuranceName",
        com: [
          { label: "", type: "INPUT", viewAttr: 1, key: "insuranceName" }
        ],
        colSpan: 1,
        width: "33%"
      },
      {
        title: getLabel(543263, "个人缴纳金额"),
        dataIndex: "custom",
        key: "custom",
        com: [
          {
            type: "custom",
            key: "custom",
            render: (text, record, index, onEdit) => (
              <WeaInputNumber precision={parseFloat(record.perValidNum || 2)}
                              value={record[`${record.insuranceId}_per`]} disabled={record.perDisabled}
                              onChange={v => onEdit({
                                record: { ...record, [`${record.insuranceId}_per`]: v },
                                index, key: "per", value: v
                              })}
              />
            )
          }
        ],
        colSpan: 1,
        width: "33%"
      },
      {
        title: getLabel(543264, "单位缴纳金额"),
        dataIndex: "custom",
        key: "custom",
        com: [
          {
            type: "custom",
            key: "custom",
            render: (text, record, index, onEdit) => (
              <WeaInputNumber precision={parseFloat(record.comValidNum || 2)}
                              value={record[`${record.insuranceId}_com`]} disabled={record.comDisabled}
                              onChange={v => onEdit({
                                record: { ...record, [`${record.insuranceId}_com`]: v },
                                index, key: "com", value: v
                              })}
              />
            )
          }
        ],
        colSpan: 1,
        width: "33%"
      }
    ];
  };
  save = () => {
    const { standingBookStore: { addCPForm }, paymentOrganization, billMonth } = this.props;
    const { paymentList } = this.state;
    addCPForm.validateForm().then(f => {
      if (f.isValid) {
        const payload = {
          billMonth, paymentOrganization, ...addCPForm.getFormParams(),
          ...this.convertItemJSON(_.find(paymentList, i => i.titleSign === "social").payment, "social"),
          ...this.convertItemJSON(_.find(paymentList, i => i.titleSign === "fund").payment, "fund"),
          ...this.convertItemJSON(_.find(paymentList, i => i.titleSign === "other").payment, "other")
        };
        this.setState({ loading: true });
        API.addNewBalance(payload).then(({ status, errormsg }) => {
          this.setState({ loading: false });
          if (status) {
            message.success(getLabel(30700, "操作成功！"));
            this.props.onCancel(true);
          } else {
            message.error(errormsg);
          }
        }).catch(() => this.setState({ loading: false }));
      } else {
        f.showErrors();
      }
    });
  };
  convertItemJSON = (list, type) => {
    let perJson = {}, comJson = {};
    _.forEach(list, o => {
      if (!_.isNil(o.per)) {
        perJson = _.assign(perJson, { [o.insuranceId]: toDecimal_n(o.per, o.perValidNum || 2) });
      }
      if (!_.isNil(o.com)) {
        comJson = _.assign(comJson, { [o.insuranceId]: toDecimal_n(o.com, o.comValidNum ||2) });
      }
    });
    return { [`${type}PerJson`]: JSON.stringify(perJson), [`${type}ComJson`]: JSON.stringify(comJson) };
  };
  getRowSelection = (rowSelection) => {
    let sel = { ...rowSelection };
    sel.getCheckboxProps = (record) => {
      return { disabled: true };
    };
    return sel;
  };

  render() {
    const { conditions, paymentList, loading } = this.state;
    const { standingBookStore: { addCPForm } } = this.props;
    return (
      <WeaDialog {...this.props} scalable title={getLabel(111, "添加补差人员")} initLoadCss
                 className="add-comp-per-dialog"
                 buttons={[<Button type="primary" onClick={this.save}
                                   loading={loading}>{getLabel(826, "确定")}</Button>]}
                 style={{
                   width: 800, height: 600, minHeight: 200, minWidth: 380, maxHeight: "90%",
                   maxWidth: "90%", overflow: "hidden", transform: "translate(0px, 0px)"
                 }}
      >
        <div className="add-comp-per-content">
          <div className="form">{getSearchs(addCPForm, conditions, 1, false, this.getBalancePaymentGroup)}</div>
          {
            _.map(paymentList, item => (
              <WeaSearchGroup title={item.title} showGroup needTigger>
                <WeaTableEdit columns={this.renderColumns()} datas={item.payment} showTitle={false}
                              getRowSelection={this.getRowSelection}
                              onChange={payment => this.setState({
                                paymentList: _.map(paymentList, o => {
                                  if (o.titleSign === item.titleSign) {
                                    return { ...o, payment };
                                  }
                                  return { ...o };
                                })
                              })}
                />
              </WeaSearchGroup>
            ))
          }
        </div>
      </WeaDialog>
    );
  }
}

export default AddCompensationPersonnelDialog;
