/*
 * Author: 黎永顺
 * name: 智能算薪-添加提醒对象
 * Description:
 * Date: 2023/8/29
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaDialog, WeaLocaleProvider } from "ecCom";
import { Button, message } from "antd";
import { getSearchs } from "../../../util";
import { remindObjConditions } from "./constants";
import { apiflowWarnReceiverGetForm, apiflowWarnReceiverSave } from "../../../apis/intelligentCalculateSalarySettings";

const getLabel = WeaLocaleProvider.getLabel;

@inject("intelligentStore")
@observer
class EditBeRemindObjDialog extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    const { intelligentStore: { remindObjform }, id } = nextProps;
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      remindObjform.initFormFields(remindObjConditions);
      id && this.apiflowWarnReceiverGetForm(nextProps);
    }
    if (nextProps.visible !== this.props.visible && !nextProps.visible) {
      remindObjform.resetForm();
    }
  }

  apiflowWarnReceiverGetForm = (props) => {
    const { intelligentStore: { remindObjform } } = this.props;
    const { id } = props;
    apiflowWarnReceiverGetForm({ id }).then(({ status, data }) => {
      if (status) {
        const { employee } = data;
        remindObjform.updateFields({
          "employeeId": {
            value: employee[0].id,
            valueSpan: employee[0].content,
            valueObj: [{ id: employee[0].id, name: employee[0].content }]
          }
        });
      }
    });
  };

  save = () => {
    const { intelligentStore: { remindObjform }, warnConfigId, id } = this.props;
    remindObjform.validateForm().then(f => {
      const { employeeId } = remindObjform.getFormParams();
      if (f.isValid) {
        this.setState({ loading: true });
        apiflowWarnReceiverSave({ employeeId, warnConfigId, id }).then(({ status, errormsg }) => {
          this.setState({ loading: false });
          if (status) {
            message.success(getLabel(22619, "保存成功！"));
            this.props.updateWarnList();
            this.props.onCancel();
          } else {
            message.error(errormsg);
          }
        }).catch(() => this.setState({ loading: false }));
      } else {
        f.showErrors();
      }
    });
  };

  render() {
    const { intelligentStore: { remindObjform } } = this.props;
    return (
      <WeaDialog
        {...this.props} className="paymentDialog" initLoadCss
        style={{ width: 550 }}
        buttons={[<Button type="primary" onClick={this.save}
                          loading={this.state.loading}>{getLabel(537558, "保存")}</Button>]}
      >
        <div className="paymentDialogContent">
          {getSearchs(remindObjform, remindObjConditions, 1)}
        </div>
      </WeaDialog>
    );
  }
}

export default EditBeRemindObjDialog;
