import React from "react";
import { inject, observer } from "mobx-react";
import { WeaFormItem, WeaHelpfulTip, WeaLocaleProvider, WeaSearchGroup, WeaSlideModal, WeaTools } from "ecCom";
import { WeaSwitch } from "comsMobx";
import FormalFormModal from "./formalFormModal";
import { salaryItemConditions } from "./columns";
import { commonEnumList } from "../../apis/archive";
import { getItemForm } from "../../apis/item";
import { getTaxAgentSelectList } from "../../apis/taxAgent";


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

@inject("salaryItemStore")
@observer
export default class CustomSalaryItemSlide extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      conditions: [], visible: false
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      document.querySelector(".custom_salaryItemSlide").classList.add("zIndex0-weaslide-title");
      this.initForm(nextProps);
    } else if (nextProps.visible !== this.props.visible && !nextProps.visible) {
      document.querySelector(".custom_salaryItemSlide").classList.remove("zIndex0-weaslide-title");
      this.props.salaryItemStore.initItemsForm();
    }
  }

  handleChange = (data) => {
    const { salaryItemStore: { itemsForm: form } } = this.props;
    form.updateFields({ formulaContent: { value: data["formula"] }, formulaId: { value: data["id"] } });
  };
  initForm = async (props) => {
    const { data: salaryItemForm } = props.id ?
      await getItemForm({ id: props.id }) :
      {
        data: { sharedType: "0", useDefault: "0", hideDefault: "0", pattern: 2, dataType: "number", valueType: "1" }
      };
    const [{ data: sharedTypeList }, { data: taxAgentList }] = await Promise.all([
      commonEnumList({ enumClass: "com.engine.salary.enums.sicategory.SharedTypeEnum" }),
      getTaxAgentSelectList()
    ]);
    this.setState({
      conditions: _.map(salaryItemConditions, c => {
        return {
          ...c, items: _.map(c.items, fields => {
            fields = {
              ...fields, viewAttr: props.showOperateBtn ? fields.viewAttr : 1,
              label: getLabel(fields.lanId, fields.label),
              value: !_.isNil(salaryItemForm[getKey(fields)]) ? String(salaryItemForm[getKey(fields)]) : fields.value
            };
            switch (getKey(fields)) {
              case "sharedType":
                fields = {
                  ...fields, options: _.map(sharedTypeList, o => ({ key: o.value, showname: o.defaultLabel }))
                };
                break;
              case "taxAgentIds":
                fields = {
                  ...fields, options: _.map(taxAgentList, o => ({ key: o.id, showname: o.content })),
                  hide: String(salaryItemForm["sharedType"]) === "0" || _.isNil(salaryItemForm["sharedType"])
                };
                break;
              case "dataType":
              case "valueType":
                fields = {
                  ...fields, options: _.map(fields.options, o => ({ ...o, showname: getLabel(o.lanId, o.showname) }))
                };
                break;
              case "roundingMode":
                fields = {
                  ...fields, options: _.map(fields.options, o => ({ ...o, showname: getLabel(o.lanId, o.showname) })),
                  hide: String(salaryItemForm["dataType"]) === "string"
                };
                break;
              case "pattern":
                fields = {
                  ...fields, hide: String(salaryItemForm["dataType"]) === "string"
                };
                break;
              case "defaultValue":
                const otherParams = String(salaryItemForm["dataType"]) === "number" ? { precision: Number(salaryItemForm["pattern"]) } : {};
                fields = {
                  ...fields, otherParams,
                  conditionType: String(salaryItemForm["dataType"]) === "string" ? "INPUT" : "INPUTNUMBER",
                  hide: String(salaryItemForm["valueType"]) !== "1"
                };
                break;
              case "formulaContent":
                fields = {
                  ...fields, hide: String(salaryItemForm["valueType"]) === "1",
                  label: String(salaryItemForm["valueType"]) === "2" ? getLabel(111, "公式") : getLabel(111, "SQL")
                };
                break;
              default:
                break;
            }
            return fields;
          })
        };
      })
    }, () => {
      props.salaryItemStore.itemsForm.initFormFields(this.state.conditions);
    });
  };
  handleChangeFormItem = (res) => {
    const { salaryItemStore: { itemsForm: form } } = this.props;
    const { conditions } = this.state, [key] = _.keys(res), value = res[key].value;
    this.setState({
      conditions: _.map(conditions, c => {
        return {
          ...c, items: _.map(c.items, fields => {
            if (key === "sharedType" && getKey(fields) === "taxAgentIds") {
              fields = { ...fields, viewAttr: value === "0" ? 2 : 3, hide: value === "0" };
            } else if (key === "dataType" && (getKey(fields) === "roundingMode" || getKey(fields) === "pattern")) {
              fields = { ...fields, hide: value === "string" };
            } else if ((key === "dataType" || key === "pattern") && getKey(fields) === "defaultValue") {
              const otherParams = form.getFormParams().dataType === "number" ? { precision: Number(form.getFormParams().pattern) } : {};
              fields = {
                ...fields, otherParams, conditionType: value === "string" ? "INPUT" : "INPUTNUMBER",
                hide: form.getFormParams().valueType !== "1"
              };
            } else if (key === "valueType" && (getKey(fields) === "formulaContent" || getKey(fields) === "defaultValue")) {
              fields = {
                ...fields,
                label: getKey(fields) === "defaultValue" ? fields.label : form.getFormDatas().valueType.valueSpan,
                hide: (getKey(fields) === "formulaContent" && value === "1") || (getKey(fields) === "defaultValue" && value !== "1")
              };
            }
            return fields;
          })
        };
      })
    }, () => {
      form.getFormParams().valueType === "1" &&
      form.updateFields({ formulaContent: { value: "" }, formulaId: { value: "" } });
      (form.getFormParams().valueType === "2" || form.getFormParams().valueType === "3") &&
      form.updateFields({ defaultValue: { value: "" } });
    });
  };
  renderForm = () => {
    const { salaryItemStore: { itemsForm: form } } = this.props;
    const { conditions } = this.state, { isFormInit } = form, formParams = form.getFormParams();
    let group = [];
    isFormInit && conditions.map(c => {
      let items = [];
      c.items.map(fields => {
        items.push({
          com: (
            <WeaFormItem label={`${fields.label}`} labelCol={{ span: `${fields.labelcol}` }}
                         wrapperCol={{ span: `${fields.fieldcol}` }} error={form.getError(fields)} tipPosition="bottom">
              <WeaSwitch fieldConfig={fields} form={form} formParams={formParams} onChange={this.handleChangeFormItem}/>
              {
                getKey(fields) === "formulaContent" && form.getFormParams().valueType !== "1" &&
                this.props.showOperateBtn &&
                <div className="formula_input_div" onClick={() => this.setState({ visible: true })}/>
              }
              {
                fields.tip && <WeaHelpfulTip
                  style={{ marginLeft: 16 }} width={350} title={getLabel(fields.tipLanId, fields.tip)}
                  placement="topLeft"/>
              }
            </WeaFormItem>),
          hide: fields.hide
        });
      });
      group.push(<WeaSearchGroup col={1} needTigger showGroup={c.defaultshow} items={items}/>);
    });
    return group;
  };
  renderTitle = () => {
    const { title, buttons } = this.props;
    return <div className="titleDialog">
      <div className="titleCol titleLeftBox">
        <div className="titleIcon"><i className="icon-coms-fa"/></div>
        <div className="title">{title}</div>
      </div>
      <div className="titleCol titleRightBox">{buttons}</div>
    </div>;
  };

  render() {
    const { onClose, salaryItemStore: { itemsForm: form } } = this.props;
    const { visible } = this.state;
    return (<WeaSlideModal
        className="custom_salaryItemSlide"{...this.props}
        top={0} width={800} height={100} measureT="%" measureX="px" measureY="%"
        direction="right" title={this.renderTitle()} onClose={() => onClose()}
        content={<div className="form-dialog-layout">
          {this.renderForm()}
          {visible &&
            <FormalFormModal
              formulaId={form.getFormParams().formulaId}
              visible={visible}
              name={form.getFormParams().name}
              valueType={form.getFormParams().valueType}
              dataType={form.getFormParams().dataType}
              onSaveFormal={this.handleChange}
              onCancel={() => this.setState({ visible: false })}
            />
          }
        </div>}/>
    );
  }
}
