/*
 * Author: 黎永顺
 * name: 新增调薪计薪规
 * Description:
 * Date: 2022/12/12
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaDialog, WeaFormItem, WeaHelpfulTip, WeaLocaleProvider, WeaSelect, WeaTools } from "ecCom";
import FormInfo from "../../../components/FormInfo";
import { WeaSwitch } from "comsMobx";
import { Button } from "antd";
import { listSalarySobItem } from "../../../apis/ledger";
import { monthDays, ruleConditions } from "../config";
import "./index.less";

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

@inject("ledgerStore")
@observer
class LedgerAdjustRuleAddModal extends Component {
  constructor(props) {
    super(props);
    this.state = { conditions: [] };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) this.listSalarySobItem(nextProps.salarySobId);
    if (nextProps.visible !== this.props.visible && !nextProps.visible) this.props.ledgerStore.initRuleForm();
  }

  listSalarySobItem = (salarySobId) => {
    const { salaryRuleItemsList } = this.props;
    const payload = {
      excludeSalaryItemIds: _.map(salaryRuleItemsList, item => item.salaryItemId), salarySobId
    };
    listSalarySobItem(payload).then(({ status, data }) => {
      if (status) {
        this.setState({
          conditions: _.map(ruleConditions, item => ({
            ...item, items: _.map(item.items, o => {
              o = { ...o, label: getLabel(o.lanId, o.label) };
              if (getKey(o) === "salaryItemId") {
                return {
                  ...o, options: _.map(data, it => ({ key: it.salaryItemId.toString(), showname: it.salaryItemName }))
                };
              } else if (getKey(o) === "dayOfMonth") {
                return { ...o, options: monthDays };
              } else if (getKey(o) === "beforeAdjustmentType" || getKey(o) === "afterAdjustmentType") {
                return {
                  ...o,
                  options: _.map(o.options, k => ({
                    ...k,
                    showname: !k.helpfultip ? getLabel(k.lanId, k.showname) : <span>
                      <span style={{ marginRight: 4 }}>{getLabel(k.lanId, k.showname)}</span>
                      <WeaHelpfulTip title={`=${getLabel(k.helpfultiplanId, k.helpfultip)}`}/>
                    </span>
                  }))
                };
              }
              return o;
            })
          }))
        }, () => this.props.ledgerStore.ruleForm.initFormFields(this.state.conditions));
      }
    });
  };
  handleSave = () => {
    const { salaryRuleItemsList, onSave, ledgerStore: { ruleForm } } = this.props;
    ruleForm.validateForm().then(f => {
      if (f.isValid) {
        const { salaryItemId } = ruleForm.getFormParams(), { fieldMap } = ruleForm;
        const fields = _.map(salaryItemId.split(","), o => ({
          ...ruleForm.getFormParams(),
          salaryItemId: o,
          salaryItemName: _.find(fieldMap["salaryItemId"]["options"], k => k.key === o).showname
        }));
        this.props.onCancel(onSave([...salaryRuleItemsList, ...fields]));
      } else {
        f.showErrors();
      }
    });
  };


  render() {
    const { ledgerStore: { ruleForm } } = this.props, { conditions } = this.state;
    const buttons = [<Button type="primary" onClick={this.handleSave}>{getLabel(111, "保存")}</Button>];
    const itemRender = {
      salaryItemId: (field, textAreaProps, form, formParams) => {
        return (<WeaSwitch fieldConfig={{ ...field, ...textAreaProps }} form={form} formParams={formParams}/>);
      },
      dayOfMonth: () => null,
      beforeAdjustmentType: () => null,
      afterAdjustmentType: () => null
    };
    const childrenComponents = {
      salaryItemId: () => {
        const { dayOfMonth, beforeAdjustmentType, afterAdjustmentType } = ruleForm.getFormParams();
        const coms = [], { fieldMap } = ruleForm;
        coms.push(
          <WeaFormItem label={<span>
            <span className="title">{getLabel(111, "计薪规则")}</span>
            <WeaHelpfulTip
              title={getLabel(111, "该规则适用于一个薪资核算周期内只调整一次薪资或个税扣缴义务人的情况，其他情况默认按照分段计薪规则核算")}/>
          </span>} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
            <div className="cust">
              <div className="child">
                <div className="lbl">{fieldMap["dayOfMonth"].label}</div>
                <WeaSelect value={dayOfMonth} options={monthDays} style={{ width: 100 }}
                           onChange={v => ruleForm.updateFields({ dayOfMonth: { value: v } })}/>
                <div className="rbl">{getLabel(111, "（含）之前")}</div>
              </div>
              <div className="child">
                <div className="lbl">{fieldMap["beforeAdjustmentType"].label}</div>
                <WeaSelect value={beforeAdjustmentType} detailtype={fieldMap["beforeAdjustmentType"]["detailtype"]}
                           options={fieldMap["beforeAdjustmentType"]["options"]} style={{ flex: 1 }}
                           onChange={v => ruleForm.updateFields({ beforeAdjustmentType: { value: v } })}/>
              </div>
              <div className="child">
                <div className="lbl">{getLabel(111, "否则：调薪生效日期在10号之后")}</div>
              </div>
              <div className="child">
                <div className="lbl">{fieldMap["afterAdjustmentType"].label}</div>
                <WeaSelect value={afterAdjustmentType} detailtype={fieldMap["afterAdjustmentType"]["detailtype"]}
                           options={fieldMap["afterAdjustmentType"]["options"]} style={{ flex: 1 }}
                           onChange={v => ruleForm.updateFields({ afterAdjustmentType: { value: v } })}/>
              </div>
            </div>
          </WeaFormItem>
        );
        return [{ com: <div className="calcRules">{coms}</div>, col: 1 }];
      }
    };
    return (
      <WeaDialog {...this.props} initLoadCss style={{ width: 750, height: 236 }} buttons={buttons}
                 className="adjustRuleModalWrapper">
        <FormInfo className="form-dialog-layout" center={false} itemRender={itemRender}
                  childrenComponents={childrenComponents} form={ruleForm} formFields={conditions}/>
      </WeaDialog>
    );
  }
}

export default LedgerAdjustRuleAddModal;

