/*
 * Author: 黎永顺
 * name: 新建自定义统计项目弹框
 * Description:
 * Date: 2023/4/10
 */
import React, { Component } from "react";
import { Button, message, Modal } from "antd";
import {
  WeaBrowser,
  WeaCheckbox,
  WeaDialog,
  WeaError,
  WeaFormItem,
  WeaHelpfulTip,
  WeaInput,
  WeaInputNumber,
  WeaLocaleProvider,
  WeaTable
} from "ecCom";
import { reportStatisticsItemSave, statisticsItemGetform } from "../../../apis/statistics";
import "../index.less";

const { getLabel } = WeaLocaleProvider;

class CustomStatisticsItemsModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      columns: [],
      dataSource: [],
      formData: {
        itemValue: "", itemValueSpan: "",
        itemName: ""
      }
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      this.statisticsItemGetform({ id: nextProps.statisticsItemId });
    } else {
      this.setState({
        columns: [],
        dataSource: [],
        formData: {
          itemValue: "", itemValueSpan: "",
          itemName: ""
        }
      });
    }
  }

  handleSaveStatisticalItems = () => {
    const { dataSource, formData } = this.state;
    const { id: statReportId, statisticsItemId } = this.props;
    const { itemValue, itemName } = formData;
    const isNoRules = _.some(dataSource, it => !!it.m2mValue || !!it.ratioValue || !!it.totalValue || !!it.y2yValue);
    const isChainRequired = _.some(dataSource, it => !!it.m2mValue && (!it.m2mLowerLimit || !it.m2mUpperLimit));
    const isChainValRight = _.some(dataSource, it => !!it.m2mValue && it.m2mLowerLimit !== 0 && it.m2mUpperLimit !== 0 && (Number(it.m2mLowerLimit) > Number(it.m2mUpperLimit)));
    const isYoyRequired = _.some(dataSource, it => !!it.y2yValue && (!it.y2yLowerLimit || !it.y2yUpperLimit));
    const isYoyValRight = _.some(dataSource, it => !!it.y2yValue && it.y2yLowerLimit !== 0 && it.y2yUpperLimit !== 0 && (Number(it.y2yLowerLimit) > Number(it.y2yUpperLimit)));
    if (!itemValue && !itemName) {
      this.refs.proError.showError();
      this.refs.nameError.showError();
      return;
    }
    if (!itemValue) {
      this.refs.proError.showError();
      return;
    }
    if (!itemName) {
      this.refs.nameError.showError();
      return;
    }
    if (!isNoRules) {
      message.warning(getLabel(111, "请至少设置一个统计规则"));
      return;
    }
    if (isChainRequired) {
      message.warning(getLabel(111, "请完善环比增幅正常区间设置上下限"));
      return;
    }
    if (isChainValRight) {
      message.warning(getLabel(111, "环比增幅上下限设置错误"));
      return;
    }
    if (isYoyRequired) {
      message.warning(getLabel(111, "请完善同比增幅正常区间设置上下限"));
      return;
    }
    if (isYoyValRight) {
      message.warning(getLabel(111, "同比增幅上下限设置错误"));
      return;
    }
    let payload = { statReportId, itemValue: itemValue.split(","), itemName };
    payload = {
      id: statisticsItemId,
      ...payload,
      ..._.reduce(dataSource, (pre, cur) => {
        if (!!cur.m2mValue || !!cur.ratioValue || !!cur.totalValue || !!cur.y2yValue) {
          const { y2yLowerLimit, y2yUpperLimit, m2mLowerLimit, m2mUpperLimit } = cur;
          if (!!cur.m2mValue) {
            return {
              ...pre,
              [`${cur["id"]}Rule`]: {
                m2mValue: cur.m2mValue.toString(),
                ratioValue: cur.ratioValue.toString(),
                totalValue: cur.totalValue.toString(),
                y2yValue: cur.y2yValue.toString(),
                m2mLowerLimit: m2mLowerLimit.toString(),
                m2mUpperLimit: m2mUpperLimit.toString()
              }
            };
          }
          if (!!cur.m2mValue) {
            return {
              ...pre,
              [`${cur["id"]}Rule`]: {
                m2mValue: cur.m2mValue.toString(),
                ratioValue: cur.ratioValue.toString(),
                totalValue: cur.totalValue.toString(),
                y2yValue: cur.y2yValue.toString(),
                y2yLowerLimit: y2yLowerLimit.toString(),
                y2yUpperLimit: y2yUpperLimit.toString()
              }
            };
          }
          if (!!cur.y2yValue && !!cur.y2yValue) {
            return {
              ...pre,
              [`${cur["id"]}Rule`]: {
                m2mValue: cur.m2mValue.toString(),
                ratioValue: cur.ratioValue.toString(),
                totalValue: cur.totalValue.toString(),
                y2yValue: cur.y2yValue.toString(),
                m2mLowerLimit: m2mLowerLimit.toString(),
                m2mUpperLimit: m2mUpperLimit.toString(),
                y2yLowerLimit: y2yLowerLimit.toString(),
                y2yUpperLimit: y2yUpperLimit.toString()
              }
            };
          }
          return {
            ...pre,
            [`${cur["id"]}Rule`]: {
              m2mValue: cur.m2mValue.toString(),
              ratioValue: cur.ratioValue.toString(),
              totalValue: cur.totalValue.toString(),
              y2yValue: cur.y2yValue.toString()
            }
          };
        }
        return { ...pre };
      }, {})
    };
    if (statisticsItemId) {
      Modal.confirm({
        title: getLabel(111, "信息确认"),
        content: getLabel(111, `确定要编辑统计项吗？编辑后，可能需要重新设置分析图设置。`),
        onOk: () => this.reportStatisticsItemSave(payload)
      });
    } else {
      this.reportStatisticsItemSave(payload);
    }
  };
  reportStatisticsItemSave = (payload) => {
    this.setState({ loading: true });
    reportStatisticsItemSave(payload).then(({ status, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        this.setState({
          formData: {
            itemValue: "", itemName: ""
          }
        }, () => this.props.onCancel(true));
      } else {
        message.error(errormsg);
      }
    }).catch(() => this.setState({ loading: false }));
  };


  statisticsItemGetform = (payload) => {
    statisticsItemGetform(payload).then(({ status, data }) => {
      if (status) {
        const { formData } = this.state;
        const { ruleData, baseForm } = data;
        const { data: dataDetail } = baseForm;
        const { columns, data: dataSource } = ruleData;
        this.setState({
          columns, dataSource,
          formData: {
            ...formData,
            itemName: dataDetail ? dataDetail.itemName : "",
            itemValue: dataDetail ? _.map(dataDetail.itemValue, it => it.id).join() : "",
            itemValueSpan: dataDetail ? _.map(dataDetail.itemValue, it => it.name).join() : ""
          }
        });
      }
    });
  };
  handleChangeColumnCheckBox = (key, value, id) => {
    const { dataSource } = this.state;
    this.setState({
      dataSource: _.map(dataSource, it => {
        if (it.id === id) {
          if (key !== "totalValue" && !!value && value !== "0") {
            return {
              ...it,
              totalValue: Number(value),
              [key]: Number(value)
            };
          }
          return {
            ...it,
            [key]: Number(value)
          };
        }
        return { ...it };
      })
    });
  };
  handleChangeColumnAllChecked = (key, val) => {
    const { dataSource } = this.state;
    this.setState({
      dataSource: _.map(dataSource, it => {
        if (key !== "totalValue" && !!val && val !== "0") {
          return {
            ...it,
            totalValue: Number(val),
            [key]: Number(val)
          };
        }
        return {
          ...it,
          [key]: Number(val)
        };
      })
    });
  };
  handleChangeColumnM2MValue = (key, value, id) => {
    const { dataSource } = this.state;
    this.setState({
      dataSource: _.map(dataSource, it => {
        if (it.id === id) {
          return {
            ...it,
            [key]: value
          };
        }
        return { ...it };
      })
    });
  };
  handleChangeStatisticalItems = (itemValue, _names, datas) => {
    const { formData } = this.state;
    this.setState({
      formData: {
        ...formData,
        itemValue,
        itemValueSpan: _.map(datas, it => it.name).join(","),
        itemName: datas.length === 1 ? _.map(datas, it => it.names).join(",") : ""
      }
    });
  };

  render() {
    const { loading, columns, dataSource, formData } = this.state;
    const { itemName, itemValue, itemValueSpan } = formData;
    const { statisticsItemId, isShare } = this.props;
    const cols = _.map(columns, it => {
      const { text, column } = it;
      if (column === "ruleName" || column === "ratio" || column === "m2m" || column === "y2y") {
        const key = column === "ruleName" ? "total" : column;
        return {
          ...it,
          title: <span>
                  <WeaCheckbox
                    disabled={isShare}
                    value={_.every(dataSource, child => !!child[`${key}Value`])}
                    onChange={val => this.handleChangeColumnAllChecked(`${key}Value`, val)}
                  />
                  <span style={{ marginLeft: 8 }}>{text}</span>
                </span>,
          render: (txt, record) => {
            return <span>
                    <WeaCheckbox
                      disabled={isShare}
                      value={record[`${key}Value`].toString()}
                      onChange={val => this.handleChangeColumnCheckBox(`${key}Value`, val, record.id)}
                    />
                    <span style={{ marginLeft: 8 }}>
                      {column === "ruleName" ? record["ruleName"] : text}
                    </span>
                  </span>;
          }
        };
      } else if (column === "m2mLimit") {
        return {
          ...it,
          title: <span>
                  <span style={{ marginRight: 8 }}>{text}</span>
                  <WeaHelpfulTip title={getLabel(111, "如：增幅>10%,差值和增幅标记为红色，增幅<-10%标记为绿色")}
                                 placement="top" width={200}/>
                </span>,
          render: (txt, record) => {
            return !!record["m2mValue"] && <IntervalSettingsComp
              isShare={isShare}
              LowerLimit={record[`${column.replace("Limit", "")}LowerLimit`]}
              UpperLimit={record[`${column.replace("Limit", "")}UpperLimit`]}
              onChange={(type, val) => this.handleChangeColumnM2MValue(`${column.replace("Limit", "")}${type === "min" ? "LowerLimit" : "UpperLimit"}`, val, record.id)}
            />;
          }
        };
      } else if (column === "y2yLimit") {
        return {
          ...it,
          title: <span>
                  <span style={{ marginRight: 8 }}>{text}</span>
                  <WeaHelpfulTip title={getLabel(111, "如：增幅>10%,差值和增幅标记为红色，增幅<-10%标记为绿色")}
                                 placement="top" width={200}/>
                </span>,
          render: (txt, record) => {
            return !!record["y2yValue"] && <IntervalSettingsComp
              isShare={isShare}
              LowerLimit={record[`${column.replace("Limit", "")}LowerLimit`]}
              UpperLimit={record[`${column.replace("Limit", "")}UpperLimit`]}
              onChange={(type, val) => this.handleChangeColumnM2MValue(`${column.replace("Limit", "")}${type === "min" ? "LowerLimit" : "UpperLimit"}`, val, record.id)}
            />;
          }
        };
      }
    });
    return (
      <WeaDialog
        {...this.props} hasScroll buttons={[]} initLoadCss
        title={
          <div className="itemsTitle">
            <span>{statisticsItemId ? getLabel(111, "编辑自定义统计项目") : getLabel(111, "新建自定义统计项目")}</span>
            {
              !isShare && <Button type="primary" loading={loading}
                                  onClick={this.handleSaveStatisticalItems}>{getLabel(111, "保存")}</Button>
            }
          </div>
        }
        style={{ width: 900, height: 450 }}
        className="statisticItemsWrapper"
      >
        <div className="statisticItemsBox">
          <WeaFormItem label={getLabel(111, "统计项目")} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
            <WeaError tipPosition="bottom" ref="proError" error={getLabel(111, "此项必填")}>
              <WeaBrowser
                title={getLabel(111, "统计项目")}
                type={162}
                viewAttr={!isShare ? 3 : 1}
                isSingle={false}
                value={itemValue}
                replaceDatas={itemValue ? _.map(itemValue.split(","), (it, idx) => ({
                  id: it,
                  name: itemValueSpan.split(",")[idx]
                })) : []}
                completeParams={{
                  type: 162,
                  fielddbtype: "browser.salaryItemBrowser",
                  f_weaver_belongto_usertype: "0"
                }}
                conditionDataParams={{
                  type: "browser.salaryItemBrowser",
                  fielddbtype: "browser.salaryItemBrowser",
                  f_weaver_belongto_usertype: "0"
                }}
                dataParams={{
                  type: "browser.salaryItemBrowser",
                  f_weaver_belongto_usertype: "0"
                }}
                destDataParams={{
                  type: "browser.salaryItemBrowser",
                  f_weaver_belongto_usertype: "0"
                }}
                isMultCheckbox
                inputStyle={{ width: "100%" }}
                onChange={this.handleChangeStatisticalItems}
              />
            </WeaError>
          </WeaFormItem>
          <WeaFormItem label={getLabel(111, "统计项名称")} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
            <WeaError tipPosition="bottom" ref="nameError" error={getLabel(111, "此项必填")}>
              <WeaInput value={itemName} viewAttr={!isShare ? 3 : 1}
                        onChange={itemName => this.setState({ formData: { ...formData, itemName } })}/>
            </WeaError>
          </WeaFormItem>
          <div className="customRuleTableWrapper">
            <WeaTable
              dataSource={dataSource}
              columns={cols}
              pagination={false}
            />
          </div>
        </div>
      </WeaDialog>
    );
  }
}

export default CustomStatisticsItemsModal;
/*
 * Author: 黎永顺
 * Description: 区间设置
 * Params:
 * Date: 2023/4/23
 */
const IntervalSettingsComp = (props) => {
  const { LowerLimit, UpperLimit, onChange, isShare } = props;
  return <div className="intervalSettingsCompWrapper">
    <WeaInputNumber value={LowerLimit} precision={2} onChange={val => onChange("min", val)} disabled={isShare}/>
    <span className="increaseTitle">{`% <${getLabel(111, "增幅")}<`}</span>
    <WeaInputNumber value={UpperLimit} precision={2} onChange={val => onChange("max", val)} disabled={isShare}/>
    <span className="pecentTitle">%</span>
  </div>;
};
