/*
 * Author: 黎永顺
 * name: 报送信息-编辑、新增弹框
 * Description:
 * Date: 2023/8/14
 */
import React, { Component } from "react";
import { WeaLocaleProvider, WeaSlideModal, WeaTools } from "ecCom";
import { Button, Col, message, Row } from "antd";
import { inject, observer } from "mobx-react";
import { declareConditions } from "../constants";
import { getSearchs } from "../../../util";
import { getQueryString } from "../../../util/url";
import { employeedeclareGetForm, getEmployeeSave } from "../../../apis/declare";
import { commonEnumList } from "../../../apis/archive";

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

@inject("employeeDeclareStore")
@observer
class EmployeeDeclareDetailSchemaEditDialog extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      eConditions: [],
      employeeInfo: {}
    };
    this.employeeChangeInfo = {};
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) this.employeedeclareGetForm(nextProps);
    if (nextProps.visible !== this.props.visible && !nextProps.visible) {
      this.props.employeeDeclareStore.initDeclareForm();
      this.employeeChangeInfo = {};
    }
  }

  employeedeclareGetForm = async (props) => {
    const { data: cardTypeEnum } = await commonEnumList({ enumClass: `com.engine.salary.enums.employeedeclare.CardTypeEnum` });
    employeedeclareGetForm(_.pick(props, ["id"])).then(({ status, data }) => {
      if (status) {
        this.setState({
          eConditions: _.map(declareConditions, it => {
            return {
              ...it,
              items: _.map(it.items, child => {
                if (getKey(child) === "employmentStatus") {
                  return {
                    ...child,
                    value: _.take(props.employmentStatusList)[0].enum,
                    options: _.map(props.employmentStatusList, it => ({
                      key: it.enum,
                      showname: getLabel(it.labelId, it.defaultLabel)
                    }))
                  };
                } else if (getKey(child) === "employmentType") {
                  return {
                    ...child,
                    value: _.take(props.employmentTypeList)[0].enum,
                    options: _.map(props.employmentTypeList, it => ({
                      key: it.enum,
                      showname: getLabel(it.labelId, it.defaultLabel)
                    }))
                  };
                } else if (getKey(child) === "gender") {
                  return {
                    ...child,
                    value: "MALE",
                    options: [
                      { key: "MALE", showname: getLabel(111, "男") },
                      { key: "FEMALE", showname: getLabel(111, "女") }
                    ]
                  };
                } else if (getKey(child) === "cardType") {
                  return {
                    ...child, options: _.map(cardTypeEnum, o => ({ key: o.enum, showname: o.defaultLabel }))
                  };
                } else if (getKey(child) === "employeeType") {
                  return {
                    ...child,
                    viewAttr: props.id ? 1 : 3,
                    options: [
                      { key: "ORGANIZATION", showname: getLabel(30042, "人员") }
                    ]
                  };
                }
                if (child.conditionType === "SELECT" && getKey(child) !== "gender" && getKey(child) !== "employmentStatus" && getKey(child) !== "employmentType" && getKey(child) !== "taxReasons") {
                  return {
                    ...child,
                    options: [
                      { key: "ON", showname: getLabel(538048, "是") },
                      { key: "OFF", showname: getLabel(111, "否") }
                    ]
                  };
                }
                return { ...child };
              })
            };
          }),
          employeeInfo: data.data
        }, () => {
          const { data: result, columns } = data;
          const { employeeDeclareStore: { declareForm }, id } = props;
          declareForm.initFormFields(this.state.eConditions);
          if (id) {
            const filedKes = _.map(columns, it => it.dataIndex);
            _.map(filedKes, item => {
              if (item === "disability" || item === "lonelyOld" || item === "martyrDependents" || item === "reissueSalary") {
                declareForm.updateFields({ [item]: result[item] || "OFF" });
              } else if (item === "deductExpenses") {
                declareForm.updateFields({ [item]: result[item] || "ON" });
              } else if (item === "gender") {
                declareForm.updateFields({ [item]: result[item] || "MALE" });
              } else if (item === "employmentStatus") {
                declareForm.updateFields({ [item]: result[item] || _.take(props.employmentStatusList)[0].enum });
              } else if (item === "employmentType") {
                declareForm.updateFields({ [item]: result[item] || _.take(props.employmentTypeList)[0].enum });
              } else if (item === "employee") {
                const [employeeData] = result[item] || [];
                !_.isEmpty(employeeData) && declareForm.updateFields({
                  employeeType: {
                    value: [employeeData._entityType, [employeeData.id, employeeData.name, [{
                      id: employeeData.id,
                      lastname: employeeData.name
                    }]]],
                    valueSpan: ["employeeId"]
                  }
                });
              } else {
                declareForm.updateFields({ [item]: result[item] || "" });
              }
            });
          }
        });
      }
    });
  };
  onChange = (res) => {
    const { eConditions } = this.state;
    const { employeeDeclareStore: { declareForm } } = this.props;
    const key = Object.keys(res)[0];
    const value = res[key].value;
    if (key === "employeeType") {
      const [v1, v2] = value;
      this.employeeChangeInfo = {
        employee: [{ _entityType: v1, name: v2[1], id: v2[0] }]
      };
    }
    switch (key) {
      case "employmentStatus":
        this.setState({
          eConditions: _.map(eConditions, it => {
            return {
              ...it,
              items: _.map(it.items, child => {
                if (getKey(child) === "dismissDate") {
                  return {
                    ...child,
                    viewAttr: value === "ABNORMAL" ? 3 : 2
                  };
                }
                return { ...child };
              })
            };
          })
        }, () => {
          declareForm.initFormFields(this.state.eConditions);
          const [employeeData] = this.state.employeeInfo["employee"] || this.employeeChangeInfo["employee"] || [];
          !_.isEmpty(employeeData) && declareForm.updateFields({
            employeeType: {
              value: [employeeData._entityType, [employeeData.id, employeeData.name, [{
                id: employeeData.id,
                lastname: employeeData.name
              }]]],
              valueSpan: ["employeeId"]
            }
          });
          if (value === "NORMAL" && declareForm.getFormParams().dismissDate) declareForm.updateFields({ dismissDate: "" });
        });
        break;
      case "employmentType":
        this.setState({
          eConditions: _.map(eConditions, it => {
            return {
              ...it,
              items: _.map(it.items, child => {
                if (getKey(child) === "employmentDate") {
                  return {
                    ...child,
                    viewAttr: value !== "OTHER" ? 3 : 2
                  };
                }
                return { ...child };
              })
            };
          })
        }, () => {
          declareForm.initFormFields(this.state.eConditions);
          const [employeeData] = this.state.employeeInfo["employee"] || this.employeeChangeInfo["employee"] || [];
          !_.isEmpty(employeeData) && declareForm.updateFields({
            employeeType: {
              value: [employeeData._entityType, [employeeData.id, employeeData.name, [{
                id: employeeData.id,
                lastname: employeeData.name
              }]]],
              valueSpan: ["employeeId"]
            }
          });
        });
        break;
      case "cardType":
        this.setState({
          eConditions: _.map(eConditions, it => {
            return {
              ...it,
              items: _.map(it.items, child => {
                if (
                  getKey(child) === "entryDate" || getKey(child) === "departureDate" ||
                  getKey(child) === "birthplace" || getKey(child) === "taxReasons"
                ) {
                  return {
                    ...child,
                    viewAttr: value !== "RESIDENT_IDENTITY_CARDS" ? 3 : 2
                  };
                }
                return { ...child };
              })
            };
          })
        }, () => {
          declareForm.initFormFields(this.state.eConditions);
          const [employeeData] = this.state.employeeInfo["employee"] || this.employeeChangeInfo["employee"] || [];
          !_.isEmpty(employeeData) && declareForm.updateFields({
            employeeType: {
              value: [employeeData._entityType, [employeeData.id, employeeData.name, [{
                id: employeeData.id,
                lastname: employeeData.name
              }]]],
              valueSpan: ["employeeId"]
            }
          });
        });
        break;
      case "dismissDate":
        const { employmentStatus } = declareForm.getFormParams();
        this.setState({
          eConditions: _.map(eConditions, it => {
            return {
              ...it, items: _.map(it.items, child => {
                if (getKey(child) === "dismissDate") {
                  return { ...child, viewAttr: 2 };
                }
                return { ...child };
              })
            };
          })
        }, () => declareForm.updateFields({ employmentStatus: (!value && employmentStatus === "ABNORMAL") ? "NORMAL" : "ABNORMAL" }));
        break;
      case "reissueSalary":
        this.setState({
          eConditions: _.map(eConditions, it => {
            return {
              ...it, items: _.map(it.items, child => {
                if (getKey(child) === "reissueTaxCycle") {
                  return { ...child, viewAttr: value === "ON" ? 3 : 2 };
                }
                return { ...child };
              })
            };
          })
        }, () => {
          declareForm.initFormFields(this.state.eConditions);
          const [employeeData] = this.state.employeeInfo["employee"] || this.employeeChangeInfo["employee"] || [];
          !_.isEmpty(employeeData) && declareForm.updateFields({
            employeeType: {
              value: [employeeData._entityType, [employeeData.id, employeeData.name, [{
                id: employeeData.id,
                lastname: employeeData.name
              }]]],
              valueSpan: ["employeeId"]
            }
          });
          if (value === "OFF" && declareForm.getFormParams().reissueTaxCycle) declareForm.updateFields({ reissueTaxCycle: "" });
        });
        break;
      case "reissueTaxCycle":
        const { reissueSalary } = declareForm.getFormParams();
        if (!value && reissueSalary === "ON") this.setState({
          eConditions: _.map(eConditions, it => {
            return {
              ...it, items: _.map(it.items, child => {
                if (getKey(child) === "reissueTaxCycle") {
                  return { ...child, viewAttr: 2 };
                }
                return { ...child };
              })
            };
          })
        }, () => declareForm.updateFields({ reissueSalary: "OFF" }));
        break;
      default:
        break;
    }
  };

  handleSubmit = () => {
    const { employeeDeclareStore: { declareForm: form } } = this.props;
    form.validateForm().then(f => {
      if (f.isValid) {
        const {
          employmentType, employmentDate, employmentStatus, dismissDate, cardType, entryDate, departureDate,
          birthplace, taxReasons, reissueSalary, reissueTaxCycle, ...params
        } = form.getFormParams();
        if ((employmentType !== "OTHER" && !employmentDate) || (employmentStatus === "ABNORMAL" && !dismissDate)) {
          form.showError("dismissDate", getLabel(111, "\"离职日期\"未填写"));
          return;
        }
        if (reissueSalary === "ON" && !reissueTaxCycle) {
          form.showError("reissueTaxCycle", getLabel(111, "\"补发税款所属月份\"未填写"));
          return;
        }
        if ((cardType !== "RESIDENT_IDENTITY_CARDS" && !entryDate && !departureDate && !birthplace && !taxReasons)) {
          form.showError("entryDate", getLabel(111, "\"首次入境时间\"未填写"));
          form.showError("departureDate", getLabel(111, "\"预计离境时间\"未填写"));
          form.showError("birthplace", getLabel(111, "\"出生地\"未填写"));
          form.showError("taxReasons", getLabel(111, "\"涉税事由\"未填写"));
          return;
        }
        if ((cardType !== "RESIDENT_IDENTITY_CARDS" && !entryDate)) {
          form.showError("entryDate", getLabel(111, "\"首次入境时间\"未填写"));
          return;
        }
        if ((cardType !== "RESIDENT_IDENTITY_CARDS" && !departureDate)) {
          form.showError("departureDate", getLabel(111, "\"预计离境时间\"未填写"));
          return;
        }
        if ((cardType !== "RESIDENT_IDENTITY_CARDS" && !birthplace)) {
          form.showError("birthplace", getLabel(111, "\"出生地\"未填写"));
          return;
        }
        if ((cardType !== "RESIDENT_IDENTITY_CARDS" && !taxReasons)) {
          form.showError("taxReasons", getLabel(111, "\"涉税事由\"未填写"));
          return;
        }
        const payload = {
          ...form.getFormParams(), id: this.props.id,
          taxAgentId: getQueryString("id"),
          taxCycle: this.props.taxCycle,
          reissueTaxCycle: reissueTaxCycle ? `${reissueTaxCycle}-01` : ""
        };
        this.setState({ loading: true });
        getEmployeeSave(payload).then(({ status, errormsg }) => {
          this.setState({ loading: false });
          if (status) {
            message.success(getLabel(22619, "保存成功！"));
            this.props.onClose("true");
          } else {
            message.error(errormsg || getLabel(22620, "保存失败！"));
          }
        }).catch(() => this.setState({ loading: false }));
      } else {
        f.showErrors();
      }
    });
  };

  render() {
    const { eConditions, loading } = this.state;
    const { employeeDeclareStore: { declareForm: form }, title = "" } = this.props;
    return (
      <WeaSlideModal
        {...this.props}
        top={0} measureT="%"
        width={800} measureX="px"
        height={100} measureY="%"
        direction="right"
        title={(<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">{title || getLabel(111, "本月新增数据")}</span>
          </Col>
          <Col span={12} className="declareSchemeDialogTitle-right">
            <Button type="primary" onClick={this.handleSubmit} loading={loading}>{getLabel(537558, "保存")}</Button>
          </Col>
        </Row>)}
        content={(<div className="declareSchemeDialog">{getSearchs(form, eConditions, 1, false, this.onChange)}</div>)}
      />
    );
  }
}

export default EmployeeDeclareDetailSchemaEditDialog;