import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaDialog, WeaLocaleProvider, WeaTools } from "ecCom";
import { Button, message } from "antd";
import { getSearchs } from "../../../../util";
import { salaryItemsConditions } from "../../conditions";
import * as API from "../../../../apis/variableSalary";

const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;

@inject("baseTableStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      conditions: [], loading: false
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) this.initForm(nextProps);
    if (nextProps.visible !== this.props.visible && !nextProps.visible) this.props.baseTableStore.initVSSalaryItemForm();
  }

  initForm = (props) => {
    const { baseTableStore: { VSSalaryItemForm } } = props;
    this.setState({
      conditions: _.map(salaryItemsConditions, item => ({
        ...item,
        items: _.map(item.items, o => {
          if (getKey(o) === "dataType") {
            return { ...o, options: _.map(o.options, g => ({ ...g, showname: getLabel(g.lanId, g.showname) })) };
          }
          return { ...o, label: getLabel(o.lanId, o.label) };
        })
      }))
    }, () => VSSalaryItemForm.initFormFields(this.state.conditions));
  };
  save = () => {
    const { baseTableStore: { VSSalaryItemForm }, onSearch, id } = this.props;
    VSSalaryItemForm.validateForm().then(f => {
      if (f.isValid) {
        const payload = VSSalaryItemForm.getFormParams();
        this.setState({ loading: true });
        API.saveVariableSalaryItem({ ...payload, id })
          .then(({ status, errormsg }) => {
            this.setState({ loading: false });
            if (status) {
              message.success(getLabel(30700, "操作成功"));
              this.props.onCancel(onSearch());
            } else {
              message.error(errormsg);
            }
          }).catch(() => this.setState({ loading: false }));
      } else {
        f.showErrors();
      }
    });
  };

  render() {
    const { conditions, loading } = this.state;
    const { baseTableStore: { VSSalaryItemForm } } = this.props;
    return (
      <WeaDialog
        {...this.props} style={{ width: 480, height: 127 }} initLoadCss
        buttons={[
          <Button onClick={() => this.props.onCancel()}>{getLabel(111, "取消")}</Button>,
          <Button type="primary" onClick={this.save} loading={loading}>{getLabel(111, "保存")}</Button>
        ]}
      >
        <div className="form-dialog-layout">{getSearchs(VSSalaryItemForm, conditions, 1, false)}</div>
      </WeaDialog>
    );
  }
}

export default Index;
