/*
 * Author: 黎永顺
 * name: 新增统计维度弹框
 * Description:
 * Date: 2023/4/11
 */
import React, { Component } from "react";
import { WeaDialog, WeaLocaleProvider, WeaSearchGroup } from "ecCom";
import { Button, message, Modal } from "antd";
import { dimensionGetForm, dimensionSave } from "../../../apis/statistics";
import { getSearchs } from "../../../util";
import GroupSpacingEditTable from "./groupSpacingEditTable";
import GroupIndividualEditTable from "./groupIndividualEditTable";
import "../index.less";

const { getLabel } = WeaLocaleProvider;
const keyObj = {
  "RATION_GROUP_SPACING": "setting4RationGroupSpacing",
  "RATION_GROUP_INDIVIDUAL": "setting4RationGroupIndividual"
};

class DimensionSlide extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      dimType: "QUALITATIVE",
      setting4RationGroupSpacing: [],
      setting4RationGroupIndividual: []
    };
  }

  componentDidMount() {
    this.props.initCondition();
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.formId) this.dimensionGetForm({ id: nextProps.formId });
    if (nextProps.visible !== this.props.visible && !nextProps.formId) {
      nextProps.form.updateFields({
        dimType: "QUALITATIVE"
      });
      nextProps.onChangeCondition("QUALITATIVE");
    }
    if (nextProps.visible !== this.props.visible && !nextProps.visible) {
      this.setState({
        loading: false,
        dimType: "QUALITATIVE",
        setting4RationGroupSpacing: [],
        setting4RationGroupIndividual: []
      });
    }
  }


  dimensionGetForm = (payload) => {
    dimensionGetForm(payload).then(({ status, data }) => {
      if (status) {
        const { baseForm: { data: formData } } = data;
        const setting = formData.setting ? JSON.parse(formData.setting) : {};
        this.props.onChangeCondition(formData["dimType"], 1);
        this.setState({
          dimType: formData.dimType,
          [keyObj[formData["dimType"]]]: setting
        }, () => {
          const fields = _.map(this.props.condition[0].items, it => {
            return it.domkey[0];
          });
          fields.map(item => {
            if (item !== "setting4Qualitative") {
              this.props.form.updateFields({
                [item]: formData[item] || ""
              });
            } else if (item === "setting4Qualitative" && formData.statsDim) {
              this.props.form.updateFields({
                setting4Qualitative: formData.statsDim
              });
            }
          });
        });
      }
    });
  };
  handleSave = () => {
    const { dimType } = this.state;
    const { condition, onCancel, formId } = this.props;
    const { setting4Qualitative, dimCode, ...extraParams } = this.props.form.getFormParams();
    let payload = { id: formId, ...extraParams };
    if (dimType === "QUALITATIVE") {
      if (!setting4Qualitative || !extraParams.dimName) {
        Modal.warning({
          title: getLabel(111, "信息确认"),
          content: getLabel(111, "必要信息不完整，红色*为必填项！")
        });
        return;
      }
      const tjOptions = _.find(condition[0].items, item => item.domkey[0] === "setting4Qualitative").options;
      const tjObj = _.find(tjOptions, item => item.key === setting4Qualitative);
      payload = { ...payload, setting4Qualitative: { id: tjObj.key, name: tjObj.showname } };
    } else {
      if (!extraParams.dimName) {
        Modal.warning({
          title: getLabel(111, "信息确认"),
          content: getLabel(111, "必要信息不完整，红色*为必填项！")
        });
        return;
      }
      if (dimType === "RATION_GROUP_SPACING") {
        const { setting4RationGroupSpacing } = this.state;
        const bool = _.every(setting4RationGroupSpacing, it => it.startValue !== "" && it.endValue !== "" && it.startValue <= it.endValue);
        if (_.isEmpty(setting4RationGroupSpacing) || !bool) {
          message.warning(getLabel(111, "请完善分组设置相关数据!分组设置不能为空，起始值结束值必填，且起始值需小于结束值！"));
          return;
        } else {
          payload = {
            ...payload, dimCode,
            setting4RationGroupSpacing: _.map(setting4RationGroupSpacing, (it, index) => ({
              id: index + 1,
              endValue: it.endValue,
              startValue: it.startValue,
              includeEnd: it.includeEnd === "1",
              includeStart: it.includeStart === "1"
            }))
          };
        }
      } else if (dimType === "RATION_GROUP_INDIVIDUAL") {
        const { setting4RationGroupIndividual } = this.state;
        const bool = _.every(setting4RationGroupIndividual, it => it.value !== "");
        if (_.isEmpty(setting4RationGroupIndividual) || !bool) {
          message.warning(getLabel(111, "请完善分组设置相关数据!分组设置不能为空,且数值必填"));
          return;
        } else {
          payload = {
            ...payload, dimCode,
            setting4RationGroupIndividual: _.map(setting4RationGroupIndividual, (it, index) => ({ id: index + 1, ...it }))
          };
        }
      }
    }
    this.setState({ loading: true });
    dimensionSave(payload).then(({ status, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        message.success(getLabel(111, "保存成功"));
        onCancel(true);
        this.props.form.resetForm();
      } else {
        message.error(errormsg || getLabel(111, "保存失败"));
      }
    }).catch(() => this.setState({ loading: false }));
  };
  formItemChange = (formObj) => {
    const { onChangeCondition } = this.props;
    const filedKey = _.keys(formObj)[0];
    if (filedKey === "dimType") {
      this.setState({
        dimType: formObj[filedKey].value,
        setting4RationGroupSpacing: [],
        setting4RationGroupIndividual: []
      }, () => onChangeCondition(formObj[filedKey].value));
    }
  };
  handleConvertGroupDatasource = (data) => {
    const { dimType } = this.state;
    this.setState({ [keyObj[dimType]]: data });
  };

  render() {
    const { loading, dimType, setting4RationGroupSpacing, setting4RationGroupIndividual } = this.state;
    const { form, condition, formId } = this.props;
    return (
      <WeaDialog
        {...this.props}
        initLoadCss hasScroll
        style={{ width: 900, height: 450 }}
        className="dimensionSlideWrapper"
        title={
          <div className="dimensionTitle">
            <span>{formId ? getLabel(111, "编辑统计维度") : getLabel(111, "新建统计维度")}</span>
            <Button type="primary" onClick={this.handleSave} loading={loading}>{getLabel(111, "保存")}</Button>
          </div>
        }
      >
        {getSearchs(form, condition, 1, false, this.formItemChange)}
        {
          dimType !== "QUALITATIVE" &&
          <WeaSearchGroup title={getLabel(111, "分组设置")} showGroup>
            {
              dimType === "RATION_GROUP_SPACING" &&
              <GroupSpacingEditTable onChange={this.handleConvertGroupDatasource}
                                     setting4RationGroupSpacing={setting4RationGroupSpacing}/>
            }
            {
              dimType === "RATION_GROUP_INDIVIDUAL" &&
              <GroupIndividualEditTable onChange={this.handleConvertGroupDatasource}
                                        setting4RationGroupIndividual={setting4RationGroupIndividual}/>
            }
          </WeaSearchGroup>
        }
      </WeaDialog>
    );
  }
}

export default DimensionSlide;
