import React from "react";
import { WeaCheckbox, WeaDatePicker, WeaFormItem, WeaInput, WeaInputNumber, WeaSearchGroup, WeaSelect } from "ecCom";
import { message } from "antd";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import "./index.less";

@inject("archivesStore")
@observer
export default class SocialSecurityForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      Welfare: ""
    };
  }

  componentWillMount() {
    const { archivesStore } = this.props;
    const { getBaseForm, getPaymentForm } = archivesStore;
    const siSchemeId = this.props.record.siSchemeId;
    getBaseForm(this.props.employeeId, "SOCIAL_SECURITY", this.props.record.paymentOrganization);
    getPaymentForm(this.props.employeeId, "SOCIAL_SECURITY", siSchemeId, this.props.record.paymentOrganization);
  }

  handleFormChange = ({ key, value }) => {
    const params = { [key]: value };
    const {
      archivesStore: { socialSecurityForm, setSocialSecurityForm },
      onChangeRecordSchemeId
    } = this.props;
    const { data } = socialSecurityForm;
    let request = { ...data, ...params };
    let form = { ...socialSecurityForm };
    form.data = request;
    setSocialSecurityForm(form);
    key === "socialSchemeId" && this.setState({ Welfare: "" });
    key === "socialSchemeId" && this.handleFetchPaymentForm(value);
    key === "socialSchemeId" && onChangeRecordSchemeId(value);
  };

  handleFetchPaymentForm = (value) => {
    const { archivesStore: { getPaymentForm }, employeeId, record } = this.props;
    const { paymentOrganization } = record;
    getPaymentForm(employeeId, "SOCIAL_SECURITY", value, paymentOrganization, true);
  };

  handlePaymentChange = ({ key, value }) => {
    const params = { [key]: !_.isNil(value) ? value.toString() : "" };
    const { archivesStore: { socialSecurityPaymentForm, setSocialSecurityPaymentForm } } = this.props;
    const { data } = socialSecurityPaymentForm;
    let request = { ...data, ...params };
    let form = { ...socialSecurityPaymentForm };
    form.data = request;
    setSocialSecurityPaymentForm(form);
  };
  handleBlurChange = ({ key, value, minNum, maxNum }) => {
    const params = {
      [key]: _.isNil(value) ? "" : (Number(value) > maxNum && maxNum !== 0) ? maxNum :
        (Number(value) < minNum && minNum !== 0) ? minNum : value.toString()
    };
    const { archivesStore: { socialSecurityPaymentForm, setSocialSecurityPaymentForm } } = this.props;
    const { data } = socialSecurityPaymentForm;
    let request = { ...data, ...params };
    let form = { ...socialSecurityPaymentForm };
    form.data = request;
    setSocialSecurityPaymentForm(form);
  };
  handleChangeWelfare = (val) => {
    const { archivesStore: { socialSecurityPaymentForm, setSocialSecurityPaymentForm } } = this.props;
    let paymentData = toJS(socialSecurityPaymentForm.data);
    const [paymentFormItems] = toJS(socialSecurityPaymentForm.items);
    const { items } = paymentFormItems;
    if (val) {
      _.forEach(items, (it) => {
        const { min, max, domkey } = it;
        const minNum = !_.isNil(min) ? Number(min) : 0, maxNum = !_.isNil(max) ? Number(max) : 0;
        if ((val < minNum || val > maxNum) && !_.isNil(min) && !_.isNil(max) && (!!maxNum || !!minNum)) {
          message.warning("超出所选缴纳方案设置的基数上下限范围，将自动按基数上下限填充。");
          paymentData = {
            ...paymentData,
            [domkey[0]]: (val < minNum && !!minNum) ? minNum : (val > maxNum && !!maxNum) ? maxNum : val
          };
        } else {
          paymentData = { ...paymentData, [domkey[0]]: val };
        }
      });
    } else {
      _.forEach(items, (it) => {
        const { domkey } = it;
        paymentData = { ...paymentData, [domkey[0]]: "" };
      });
    }
    setSocialSecurityPaymentForm({ ...socialSecurityPaymentForm, data: { ...paymentData } });
  };

  render() {
    const { Welfare } = this.state;
    const { archivesStore: { socialSecurityForm, socialSecurityPaymentForm } } = this.props;
    const { items, data: socialData } = socialSecurityForm;
    const paymentData = toJS(socialSecurityPaymentForm.data);
    const paymentItems = socialSecurityPaymentForm.items;
    const {
      nonPayment = "", schemeAccount = "", socialStartTime = "", socialEndTime = "",
      socialSchemeId = ""
    } = socialData || {};
    const socialItems = !_.isNil(toJS(items)) ? [
      ..._.map(_.filter(toJS(items)[0].items, it => it.domkey[0] !== "paymentOrganization"),
        item => ({
          com: SocialSelect({
            key: item["domkey"][0],
            label: item.label,
            value: !_.isNil(socialData[item["domkey"][0]]) ? socialData[item["domkey"][0]].toString() : "",
            options: item.options,
            onChange: this.handleFormChange
          })
        })),
      {
        com: SocialDatePicker({
          key: "socialStartTime",
          label: "社保起始缴纳月",
          viewAttr: socialSchemeId ? 3 : 2,
          value: socialStartTime,
          disabledDate: (current) => {
            return current && socialEndTime && current.getTime() > new Date(socialEndTime).getTime();
          },
          onChange: this.handleFormChange
        })
      },
      {
        com: SocialEditInput({
          key: "schemeAccount",
          label: "社保账号",
          value: schemeAccount,
          onChange: this.handleFormChange
        })
      },
      {
        com: SocialDatePicker({
          key: "socialEndTime",
          label: "社保最后缴纳月",
          value: socialEndTime,
          disabledDate: (current) => {
            return current && socialStartTime && current.getTime() < new Date(socialStartTime).getTime();
          },
          onChange: this.handleFormChange
        })
      }
    ] : [];
    return (
      <div className="socialFormWrapper">
        <WeaSearchGroup
          title="社保基础信息"
          customComponent={<SocialTitle keyname="nonPayment" value={!_.isNil(nonPayment) ? nonPayment.toString() : "0"}
                                        onChange={this.handleFormChange}/>}
          items={socialItems} col={2} showGroup needTigger={false}/>
        {
          socialSchemeId && !_.isEmpty(toJS(paymentItems)) && _.map(toJS(paymentItems), item => {
            const { title, items } = item;
            return <WeaSearchGroup
              items={_.map(items, child => ({
                com: SocialInputNumber({
                  key: child["domkey"][0],
                  label: child.label,
                  value: !_.isNil(paymentData[child["domkey"][0]]) ? paymentData[child["domkey"][0]].toString() : "",
                  onChange: this.handlePaymentChange,
                  onBlurChange: this.handleBlurChange,
                  min: child.min,
                  max: child.max
                })
              }))}
              customComponent={<ConsistentWelfare value={Welfare} onChange={(Welfare) => this.setState({ Welfare })}
                                                  onBlurChange={this.handleChangeWelfare}/>}
              title={title} col={2} showGroup
            />;
          })
        }
      </div>
    );
  }
}
export const ConsistentWelfare = (props) => {
  const { onChange, onBlurChange, value } = props;
  return <div className="welfareBaseWrapper">
    <span className="title">各项福利基数一致：</span>
    <WeaInputNumber
      style={{ width: 100 }}
      onBlur={onBlurChange}
      value={value}
      onChange={onChange}
      precision={2}
    />
  </div>;
};
export const SocialTitle = (props) => {
  const { value, onChange, keyname: key } = props;
  return <WeaCheckbox value={value} content="暂不缴纳" onChange={(val) => onChange({ key, value: val })}/>;
};
export const SocialSelect = (props) => {
  const { key, value, onChange, options, label, labelColSpan = 12, wrapperColSpan = 12 } = props;
  return <WeaFormItem label={label} labelCol={{ span: labelColSpan }} wrapperCol={{ span: wrapperColSpan }}>
    <WeaSelect value={value} options={options} onChange={(val) => onChange({ key, value: val })}/>
  </WeaFormItem>;
};
export const SocialEditInput = (props) => {
  const { key, value, onChange, label, labelColSpan = 12, wrapperColSpan = 12 } = props;
  return (
    <WeaFormItem label={label} labelCol={{ span: labelColSpan }} wrapperCol={{ span: wrapperColSpan }}>
      <WeaInput value={value} onChange={(val) => onChange({ key, value: val })}/>
    </WeaFormItem>
  );
};
export const SocialInputNumber = (props) => {
  const { key, value, onChange, onBlurChange, label, min, max, labelColSpan = 12, wrapperColSpan = 12 } = props;
  const minNum = !_.isNil(min) ? Number(min) : 0, maxNum = !_.isNil(max) ? Number(max) : 0;
  return (
    <WeaFormItem label={label} labelCol={{ span: labelColSpan }} wrapperCol={{ span: wrapperColSpan }}>
      <WeaInputNumber
        value={value} onChange={(val) => onChange({ key, value: val })} precision={2}
        onBlur={(val) => onBlurChange({ key, value: val, minNum, maxNum })}
        // min={minNum > 0 ? minNum : -999999999999999}
        // max={maxNum > 0 ? maxNum : 999999999999999}
      />
    </WeaFormItem>
  );
};
export const SocialDatePicker = (props) => {
  const {
    key,
    value,
    onChange,
    label,
    format = "YYYY-MM",
    viewAttr = 2,
    labelColSpan = 12,
    wrapperColSpan = 12,
    disabledDate = false
  } = props;
  return (
    <WeaFormItem label={label} labelCol={{ span: labelColSpan }} wrapperCol={{ span: wrapperColSpan }}>
      <WeaDatePicker value={value} viewAttr={viewAttr} format={format}
                     onChange={(val) => onChange({ key, value: val })}
                     disabledDate={disabledDate}
      />
    </WeaFormItem>
  );
};


