/*
  *  浮动薪酬
  *  新建编辑薪资档案
  * @Author:    黎永顺
  * @Date:      2024/8/8
  * @Wechat:
  * @Email:     971387674@qq.com
  * @description:
*/
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaLocaleProvider, WeaSlideModal, WeaTools } from "ecCom";
import { Button, message } from "antd";
import { getSearchs } from "../../../../util";
import { salaryFileConditions } 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) {
      document.querySelector(".variable_salary_wrapper").classList.add("zIndex0-weaslide-title");
      this.initForm(nextProps);
    } else if (nextProps.visible !== this.props.visible && !nextProps.visible) {
      document.querySelector(".variable_salary_wrapper").classList.remove("zIndex0-weaslide-title");
      this.props.baseTableStore.initVSSalaryFileForm();
    }
  }

  initForm = async (props) => {
    const { baseTableStore: { VSSalaryFileForm }, detail } = props;
    const { data: taxAgentOption } = await API.getAdminTaxAgentList();
    API.getCreateForm().then(({ data }) => {
      this.setState({
        conditions: [..._.map(salaryFileConditions, item => ({
          ...item, items: _.map(item.items, o => {
            if (getKey(o) === "taxAgentIds") {
              return {
                ...o, viewAttr: !_.isEmpty(detail) ? 1 : 3, label: getLabel(o.lanId, o.label),
                value: detail[getKey(o)] || "",
                options: _.map(taxAgentOption, (o, i) => ({ key: o.id, showname: o.content }))
              };
            }
            return {
              ...o, viewAttr: !_.isEmpty(detail) ? 1 : 3, label: getLabel(o.lanId, o.label),
              value: detail[getKey(o)] || ""
            };
          })
        })), {
          items: _.map(data, o => ({
            conditionType: "INPUT", domkey: [String(o.id)], fieldcol: 14, label: o.name, labelcol: 6,
            value: detail[`${String(o.id)}_variableItem`] || "", viewAttr: 2, dataType: o.dataType
          })), title: "", col: 2, defaultshow: true
        }]
      }, () => {
        VSSalaryFileForm.initFormFields(this.state.conditions);
        if (!_.isEmpty(detail)) {
          VSSalaryFileForm.updateFields({
            employeeId: {
              value: detail["employeeId"], valueSpan: detail["username"],
              valueObj: [{ id: detail["employeeId"], name: detail["username"] }]
            }
          });
        }
      });
    });
  };
  convertPayload = (payload) => {
    const itemValueList = [];
    return _.reduce(_.keys(payload), (pre, cur) => {
      if (!_.isNaN(parseInt(cur))) {
        itemValueList.push({ variableItemId: cur, itemValue: payload[cur] });
        return { ...pre, itemValueList };
      }
      return { ...pre, [cur]: payload[cur] };
    }, {});
  };
  save = () => {
    const { baseTableStore: { VSSalaryFileForm }, onSearch, detail: { id } } = this.props;
    VSSalaryFileForm.validateForm().then(f => {
      if (f.isValid) {
        const payload = VSSalaryFileForm.getFormParams();
        this.setState({ loading: true });
        API.createVariableSalary({ ...this.convertPayload(payload), id })
          .then(({ status, errormsg }) => {
            this.setState({ loading: false });
            if (status) {
              message.success(getLabel(30700, "操作成功"));
              this.props.onClose(onSearch());
            } else {
              message.error(errormsg);
            }
          }).catch(() => this.setState({ loading: false }));
      } else {
        f.showErrors();
      }
    });
  };
  renderTitle = () => {
    const { loading } = this.state, { title } = 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">
        <Button type="primary" loading={loading} onClick={this.save}>{getLabel(537558, "保存")}</Button>
      </div>
    </div>;
  };
  handleChange = (formVal) => {
    const key = _.keys(formVal)[0], value = formVal[key].value;
    const [__, fields] = this.state.conditions, { items } = fields;
    _.forEach(items, o => {
      if (getKey(o) === key && o.dataType === "number") {
        if (_.isNaN(Number(value)) || value.indexOf(" ") !== -1) {
          const { baseTableStore: { VSSalaryFileForm } } = this.props;
          message.warning(getLabel(111, "数值类型有误！"));
          VSSalaryFileForm.updateFields({ [getKey(o)]: { value: "" } });
        }
      }
    });
  };

  render() {
    const { conditions } = this.state;
    const { baseTableStore: { VSSalaryFileForm }, onClose } = this.props;
    return (<WeaSlideModal
      className="variable_salary_file_dialog" {...this.props} direction="right" onClose={() => onClose()}
      top={0} width={800} height={100} measureT="%" measureX="px" measureY="%" title={this.renderTitle()}
      content={<div
        className="form-dialog-layout">{getSearchs(VSSalaryFileForm, conditions, 2, false, this.handleChange)}</div>}
    />);
  }
}

export default Index;
