/*
 * Author: 黎永顺
 * name: 个税申报人员-新增与编辑
 * Description:
 * Date: 2023/12/27
 */
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { incomeTaxDecConditions } from "./constants";
import { WeaLocaleProvider, WeaSlideModal, WeaTools } from "ecCom";
import { Button, Col, message, Row } from "antd";
import { getConditionDomkeys, getSearchs, toDecimal_n } from "../../../util";
import * as API from "../../../apis/declare";

const getLabel = WeaLocaleProvider.getLabel;
const getKey = WeaTools.getKey;
const APIFOX = {
  add: API.taxdeclarationAdd,
  edit: API.taxdeclarationEdit
};

@inject("declareStore")
@observer
class IncomeTaxDeclarationPersonnelSlide extends Component {
  constructor(props) {
    super(props);
    this.state = {
      conditions: [], employeeDeclares: [], taxReportColumns: [],
      loading: false, detailInfo: {}
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) this.getTaxDecForm(nextProps);
    if (nextProps.visible !== this.props.visible && !nextProps.visible) {
      const { declareStore: { initTaxDecForm } } = nextProps;
      this.setState({
        conditions: [], employeeDeclares: [], taxReportColumns: [],
        loading: false, detailInfo: {}
      }, () => initTaxDecForm());
    }
  }

  getTaxDecForm = (props) => {
    const { taxDeclarationId, id } = props;
    API.getTaxDecForm({ taxDeclarationId }).then(({ status, data }) => {
      if (status) {
        const { employeeDeclares, taxReportColumns } = data;
        this.setState({
          employeeDeclares, taxReportColumns,
          conditions: _.map(incomeTaxDecConditions, item => {
            if (item.title === "baseInfo") {
              return {
                ...item, title: getLabel(1361, "基本信息"),
                items: _.map(item.items, o => {
                  if (getKey(o) === "employeeId") {
                    if (!id) {
                      return {
                        ...o, otherParams: { showSearch: true, optionFilterProp: "children" },
                        label: getLabel(o.lanId, o.label),
                        options: _.map(employeeDeclares, g => ({
                          key: g.employeeId.toString(),
                          showname: g.employeeName
                        }))
                      };
                    } else {
                      return {
                        conditionType: "INPUT",
                        domkey: ["username"],
                        fieldcol: 16,
                        label: getLabel(25034, "姓名"),
                        labelcol: 8,
                        value: "",
                        viewAttr: 1
                      };
                    }
                  }
                  return { ...o, label: getLabel(o.lanId, o.label) };
                })
              };
            } else if (item.title === "salaryItems") {
              return {
                ...item, title: getLabel(111, "薪资项"),
                items: _.map(taxReportColumns, o => ({
                  conditionType: o.dataType === "number" ? "INPUTNUMBER" : "INPUT",
                  domkey: [o.reportColumnDataIndex],
                  fieldcol: 16,
                  label: o.reportColumnName,
                  labelcol: 8,
                  value: o.dataType === "number" ? 0 : "",
                  rules: o.dataType === "number" ? "required" : "",
                  otherParams: { precision: 2 },
                  viewAttr: o.dataType === "number" ? 3 : 2
                }))
              };
            }
          })
        }, () => {
          const { declareStore: { taxDecForm } } = props;
          taxDecForm.initFormFields(this.state.conditions);
          id && this.getTaxdeclarationDetailInfo(id);
        });
      }
    });
  };
  getTaxdeclarationDetailInfo = (id) => {
    API.getTaxdeclarationDetailInfo({ id }).then(({ status, data, errormsg }) => {
      if (status) {
        const { conditions } = this.state;
        const { declareStore: { taxDecForm } } = this.props;
        const detailInfo = { ...data, ...data["resultValue"] };
        this.setState({
          detailInfo: detailInfo
        }, () => {
          _.forEach(getConditionDomkeys(conditions), o => {
            taxDecForm.updateFields({
              [o]: this.state.detailInfo[o] || ""
            });
          });
        });
      } else {
        message.error(errormsg);
        this.props.onClose();
      }
    });
  };
  handleFormChange = (params) => {
    const { declareStore: { taxDecForm } } = this.props;
    const { employeeDeclares } = this.state;
    const key = Object.keys(params)[0];
    const value = params[key].value;
    if (key === "employeeId") {
      taxDecForm.updateFields({
        jobNum: _.find(employeeDeclares, o => o.employeeId == value).jobNum,
        cardNum: _.find(employeeDeclares, o => o.employeeId == value).cardNum
      });
    }
  };
  save = () => {
    const { declareStore: { taxDecForm }, taxDeclarationId, id } = this.props;
    const { employeeDeclares, detailInfo } = this.state;
    const type = id ? "edit" : "add";
    taxDecForm.validateForm().then(f => {
      if (f.isValid) {
        const { cardNum, jobNum, employeeId, ...taxReportColumnValues } = taxDecForm.getFormParams();
        const payload = {
          taxDeclarationId, employeeId: employeeId || detailInfo.employeeId,
          employeeType: employeeId ? _.find(employeeDeclares, o => o.employeeId == employeeId).employeeType : detailInfo.employeeType,
          taxReportColumnValues: _.reduce(_.keys(taxReportColumnValues), (pre, cur) => {
            if (Object.prototype.toString.call(taxReportColumnValues[cur]) === "[object Number]") {
              return { ...pre, [cur]: toDecimal_n(taxReportColumnValues[cur], 2) };
            } else {
              return { ...pre, [cur]: taxReportColumnValues[cur] };
            }
          }, {})
        };
        this.setState({ loading: true });
        APIFOX[type](type === "add" ? payload : { ...payload, id }).then(({ status, errormsg }) => {
          this.setState({ loading: false });
          if (status) {
            message.success(getLabel(30700, "操作成功！"));
            this.props.onClose(true);
          } else {
            message.error(errormsg);
          }
        }).catch(() => this.setState({ loading: false }));
      } else {
        f.showErrors();
      }
    });
  };
  renderTitle = () => {
    return <Row className="declareSchemeDialogTitle" type="flex">
      <Col span={12} className="declareSchemeDialogTitle-left">
        <div className="icon-circle-base"><i className="icon-coms-fa"/></div>
        <span className="title">{this.props.title}</span>
      </Col>
      <Col span={12} className="declareSchemeDialogTitle-right">
        <Button type="primary" loading={this.state.loading} onClick={this.save}>{getLabel(537558, "保存")}</Button>
      </Col>
    </Row>;
  };

  render() {
    const { declareStore: { taxDecForm } } = this.props;
    const { conditions } = this.state;
    return (
      <WeaSlideModal {...this.props} className="incomeTaxDecPerSlideWrapper" onClose={() => this.props.onClose()}
                     top={0} width={60} height={100} measure="%" direction="right" title={this.renderTitle()}
                     content={getSearchs(taxDecForm, conditions, 2, false, this.handleFormChange)}
      />
    );
  }
}

export default IncomeTaxDeclarationPersonnelSlide;
