import React from "react";
import { inject, observer } from "mobx-react";
import { message } from "antd";
import { toJS } from "mobx";
import { WeaSearchGroup } from "ecCom";
import {
  ConsistentWelfare,
  SocialDatePicker,
  SocialEditInput,
  SocialInputNumber,
  SocialSelect,
  SocialTitle
} from "./socialSecurityForm";
import "./index.less";

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

  componentWillMount() {
    const { archivesStore: { getBaseForm, getPaymentForm } } = this.props;
    getBaseForm(this.props.employeeId, "ACCUMULATION_FUND", this.props.record.paymentOrganization);
    getPaymentForm(this.props.employeeId, "ACCUMULATION_FUND", this.props.record.fundSchemeId, this.props.record.paymentOrganization);
  }

  handleFormChange = ({ key, value }) => {
    const params = { [key]: value };
    const { archivesStore: { accumulationFundForm, setAccumulationFundForm }, onChangeRecordFundSchemeId } = this.props;
    const { data } = accumulationFundForm;
    let request = { ...data, ...params };
    let form = { ...accumulationFundForm };
    form.data = request;
    setAccumulationFundForm(form);
    key === "fundSchemeId" && this.setState({ Welfare: "" });
    key === "fundSchemeId" && this.handleFetchPaymentForm(value);
    key === "fundSchemeId" && onChangeRecordFundSchemeId(value);
  };

  // 获取基数表单
  handleFetchPaymentForm = (fundName) => {
    const { archivesStore: { getPaymentForm } } = this.props;
    getPaymentForm(this.props.employeeId, "ACCUMULATION_FUND", fundName, this.props.record.paymentOrganization, true);
  };
  handlePaymentChange = ({ key, value }) => {
    const params = { [key]: !_.isNil(value) ? value.toString() : "" };
    const { archivesStore: { accumulationFundPaymentForm, setAccumulationFundPaymentForm } } = this.props;
    const { data } = accumulationFundPaymentForm;
    let request = { ...data, ...params };
    let form = { ...accumulationFundPaymentForm };
    form.data = request;
    setAccumulationFundPaymentForm(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: { accumulationFundPaymentForm, setAccumulationFundPaymentForm } } = this.props;
    const { data } = accumulationFundPaymentForm;
    let request = { ...data, ...params };
    let form = { ...accumulationFundPaymentForm };
    form.data = request;
    setAccumulationFundPaymentForm(form);
  };
  handleChangeWelfare = (val) => {
    const { archivesStore: { accumulationFundPaymentForm, setAccumulationFundPaymentForm } } = this.props;
    let paymentData = toJS(accumulationFundPaymentForm.data);
    const [paymentFormItems] = toJS(accumulationFundPaymentForm.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]]: "" };
      });
    }
    setAccumulationFundPaymentForm({ ...accumulationFundPaymentForm, data: { ...paymentData } });
  };

  render() {
    const { Welfare } = this.state;
    const { archivesStore: { accumulationFundForm, accumulationFundPaymentForm } } = this.props;
    const { items, data: foundData } = accumulationFundForm;
    const paymentData = accumulationFundPaymentForm.data;
    const paymentItems = accumulationFundPaymentForm.items;
    const {
      nonPayment = "", fundAccount = "", supplementFundAccount = "", fundStartTime = "", fundEndTime = "",
      fundSchemeId = ""
    } = foundData || {};
    const foundItems = !_.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(foundData[item["domkey"][0]]) ? foundData[item["domkey"][0]].toString() : "",
            options: item.options,
            onChange: this.handleFormChange
          })
        })),
      {
        com: SocialDatePicker({
          key: "fundStartTime",
          label: "公积金起始缴纳月",
          viewAttr: fundSchemeId ? 3 : 2,
          value: fundStartTime,
          disabledDate: (current) => {
            return current && fundEndTime && current.getTime() > new Date(fundEndTime).getTime();
          },
          onChange: this.handleFormChange
        })
      },
      {
        com: SocialEditInput({
          key: "fundAccount",
          label: "公积金账号",
          value: fundAccount,
          onChange: this.handleFormChange
        })
      },
      {
        com: SocialDatePicker({
          key: "fundEndTime",
          label: "公积金最后缴纳月",
          value: fundEndTime,
          disabledDate: (current) => {
            return current && fundStartTime && current.getTime() < new Date(fundStartTime).getTime();
          },
          onChange: this.handleFormChange
        })
      },
      {
        com: SocialEditInput({
          key: "supplementFundAccount",
          label: "补充公积金账号",
          value: supplementFundAccount,
          onChange: this.handleFormChange
        })
      }
    ] : [];
    return (
      <div className="socialFormWrapper">
        <WeaSearchGroup
          title="公积金基础信息"
          customComponent={<SocialTitle keyname="nonPayment" value={!_.isNil(nonPayment) ? nonPayment.toString() : "0"}
                                        onChange={this.handleFormChange}/>}
          items={foundItems} col={2} showGroup needTigger={false}/>
        {
          fundSchemeId && !_.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>
    );
  }
}
