/*
 * Author: 黎永顺
 * name: 分析图标范围数据设置弹框
 * Description:
 * Date: 2023/5/11
 */
import React, { Component } from "react";
import { Button, Col, message, Row } from "antd";
import {
  WeaDialog,
  WeaError,
  WeaFormItem,
  WeaHelpfulTip,
  WeaInputNumber,
  WeaLocaleProvider,
  WeaReqTop,
  WeaSearchGroup,
  WeaSelect
} from "ecCom";
import { saveRangeSetting } from "../../../apis/statistics";
import "./index.less";

const { getLabel } = WeaLocaleProvider;

class ChartsRangeSettingsModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      selectedKey: "1",
      rangeSetting: {
        itemValues: "",
        itemColValue: "",
        dimensionRange: "0"
      },
      rangeSettingExtra: {
        itemSortValue: "",
        itemColSortValue: "",
        sortType: "0",
        sortNum: ""
      },
      statisticalItemsOptions: [],
      statisticalColsOptions: [],
      rangeSettingExtraOptions: {
        sortStatisticsOptions: [],
        sortColumnsOptions: []
      }
    };
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.visible !== this.props.visible && nextProps.visible) {
      const { columns } = nextProps;
      this.setState({
        statisticalItemsOptions: _.map(_.filter(columns, item => !_.isEmpty(item.children)), it => ({
          key: it.column, showname: it.text,
          children: _.map(it.children, child => ({ key: child.column, showname: child.text }))
        }))
      });
    }
    if (nextProps.rangeVal !== this.props.rangeVal && nextProps.rangeVal) {
      const { rangeVal } = nextProps;
      const { rangeSetting, rangeSettingExtra } = this.state;
      this.setState({
        rangeSetting: {
          ...rangeSetting,
          ..._.reduce(Object.keys(rangeSetting), (pre, cur) => {
            return {
              ...pre,
              [cur]: Array.isArray(rangeVal[cur]) ? rangeVal[cur].join(",") :
                !_.isNil(rangeVal[cur]) ? rangeVal[cur].toString() : cur === "dimensionRange" ? "0" : ""
            };
          }, {})
        },
        rangeSettingExtra: {
          ...rangeSettingExtra,
          ..._.reduce(Object.keys(rangeSettingExtra), (pre, cur) => {
            return {
              ...pre,
              [cur]: !_.isNil(rangeVal[cur]) ? rangeVal[cur].toString() : cur === "sortType" ? "0" : ""
            };
          }, {})
        }
      }, () => {
        const { statisticalItemsOptions } = this.state;
        const { itemValues, itemSortValue } = rangeVal;
        let statisticalColsOptions = [], sortStatisticsOptions = [];
        _.forEach(itemValues, item => {
          _.forEach(statisticalItemsOptions, child => {
            if (item === child.key) {
              statisticalColsOptions = [...statisticalColsOptions, ...child.children];
              sortStatisticsOptions = [...sortStatisticsOptions, child];
            }
          });
        });
        this.setState({
          statisticalColsOptions,
          rangeSettingExtraOptions: {
            sortStatisticsOptions
          }
        }, () => {
          const { rangeSettingExtraOptions } = this.state;
          const { sortStatisticsOptions } = rangeSettingExtraOptions;
          this.setState({
            rangeSettingExtraOptions: {
              ...rangeSettingExtraOptions,
              sortColumnsOptions: !_.isEmpty(_.find(sortStatisticsOptions, it => it.key === itemSortValue)) ? _.find(sortStatisticsOptions, it => it.key === itemSortValue).children : []
            }
          });
        });
      });
    }
  }

  handleSaveChartsRangeSettings = () => {
    const { reportId, rangeVal } = this.props;
    const { rangeSetting, rangeSettingExtra, selectedKey: chartsType } = this.state;
    const { itemValues, itemColValue, dimensionRange } = rangeSetting;
    if (!itemColValue && !itemValues) {
      this.refs.itemValues.showError();
      this.refs.itemColValue.showError();
      return;
    }
    if (!itemValues) {
      this.refs.itemValues.showError();
      return;
    }
    if (!itemColValue) {
      this.refs.itemColValue.showError();
      return;
    }
    const payload = {
      reportId, chartsType, id: rangeVal.id,
      ...rangeSetting,
      itemValues: itemValues.split(",")
    };
    this.setState({ loading: true });
    saveRangeSetting(
      dimensionRange === "0" ? payload : { ...payload, ...rangeSettingExtra }
    ).then(({ status, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        message.success(getLabel(111, "保存成功"));
        this.props.onGetData();
        this.handleCancel();
      } else {
        message.error(errormsg || getLabel(111, "保存失败"));
      }
    }).catch(() => this.setState({ loading: false }));
  };
  handleCancel = () => {
    this.setState({
      rangeSetting: {
        itemValues: "",
        itemColValue: "",
        dimensionRange: "0"
      },
      rangeSettingExtra: {
        itemSortValue: "",
        itemColSortValue: "",
        sortType: "0",
        sortNum: ""
      },
      selectedKey: "1",
      statisticalItemsOptions: [],
      statisticalColsOptions: []
    }, () => this.props.onCancel());
  };
  handleResetFormVal = () => {
    const { selectedKey: chartsType } = this.state;
    const { reportId } = this.props;
    this.props.onChange({ reportId, chartsType });
  };
  handleChange = ({ key, val }) => {
    const { rangeSetting } = this.state;
    this.setState({
      rangeSetting: {
        ...rangeSetting,
        [key]: val
      }
    }, () => {
      if (key === "itemValues") {
        const { statisticalItemsOptions } = this.state;
        let statisticalColsOptions = [], sortStatisticsOptions = [];
        _.forEach(val.split(","), item => {
          _.forEach(statisticalItemsOptions, child => {
            if (item === child.key) {
              statisticalColsOptions = [...statisticalColsOptions, ...child.children];
              sortStatisticsOptions = [...sortStatisticsOptions, child];
            }
          });
        });
        this.setState({
          statisticalColsOptions,
          rangeSettingExtra: {
            itemSortValue: "",
            itemColSortValue: "",
            sortType: "0",
            sortNum: ""
          },
          rangeSettingExtraOptions: {
            sortStatisticsOptions
          }
        });
      }
    });
  };
  handleChangeRange = ({ key, val }) => {
    const { rangeSettingExtra } = this.state;
    this.setState({
      rangeSettingExtra: {
        ...rangeSettingExtra,
        [key]: val
      }
    }, () => {
      if (key === "itemSortValue") {
        const { rangeSettingExtraOptions } = this.state;
        const { sortStatisticsOptions } = rangeSettingExtraOptions;
        this.setState({
          rangeSettingExtraOptions: {
            ...rangeSettingExtraOptions,
            sortColumnsOptions: _.find(sortStatisticsOptions, it => it.key === val).children
          }
        });
      }
    });
  };

  render() {
    const {
      selectedKey,
      rangeSetting,
      statisticalItemsOptions,
      statisticalColsOptions,
      rangeSettingExtra,
      rangeSettingExtraOptions,
      loading
    } = this.state;
    const dataShowItems = [
      {
        com: RangSelect({
          name: "itemValues",
          label: getLabel(111, "统计项"),
          onChange: this.handleChange,
          value: rangeSetting.itemValues,
          options: statisticalItemsOptions,
          multiple: selectedKey !== "0"
        })
      },
      {
        com: RangSelect({
          name: "itemColValue",
          label: getLabel(111, "统计列"),
          onChange: this.handleChange,
          value: rangeSetting.itemColValue,
          options: statisticalColsOptions
        })
      }
    ];
    const rangValItems = [
      {
        com: RangSelect({
          name: "dimensionRange",
          label: getLabel(111, "统计维度查看范围"),
          onChange: this.handleChange,
          value: rangeSetting.dimensionRange,
          options: [
            { key: "0", showname: getLabel(111, "全部") },
            { key: "1", showname: getLabel(111, "设置范围") }
          ],
          detailtype: 3,
          helpfulTip: getLabel(111, "通过某个统计项统计值的排序，确定统计维度的查看范围。 例：查看统计项【薪资成本】的统计值降序为前10的部门的分析图情况")
        })
      }
    ];
    const rangValExtraItems = [
      {
        com: RangMultiItem({
          label: getLabel(111, "设置范围"),
          onChange: this.handleChangeRange,
          value: rangeSettingExtra,
          options: rangeSettingExtraOptions
        })
      }
    ];
    const { dimensionRange } = rangeSetting;
    return (
      <WeaDialog
        {...this.props} hasScroll style={{ width: 600 }}
        buttons={[]} onCancel={this.handleCancel}
        initLoadCss className="rangSettingWrapper"
        title={<RangSetingTitle
          loading={loading}
          selectedKey={selectedKey}
          onChange={selectedKey => this.setState({ selectedKey }, () => this.handleResetFormVal())}
          onSaveChartsRangeSettings={this.handleSaveChartsRangeSettings}
        />}
      >
        <WeaSearchGroup
          title={
            <div className="rangSettingItemTitle">
              <span>{getLabel(111, "统计项数据展示范围设置")}</span>
              <WeaHelpfulTip
                title={getLabel(111, "选择分析图要展示的统计项的统计列\n" +
                  "例：分析图想查看社保福利成本的合计和税前薪酬成本的合计\n" +
                  "则：统计项选择【社保福利成本】和【税前薪酬成本】查看列选择【本期合计】")}
                placement="bottomLeft"
                width={260}
              />
            </div>
          }
          showGroup items={dataShowItems} needTigger col={1}
        />
        {/*<WeaSearchGroup*/}
        {/*  title={getLabel(111, "统计维度值范围设置")}*/}
        {/*  showGroup items={dimensionRange === "0" ? rangValItems : [...rangValItems, ...rangValExtraItems]}*/}
        {/*  needTigger col={1}*/}
        {/*/>*/}
      </WeaDialog>
    );
  }
}

export default ChartsRangeSettingsModal;

const RangSetingTitle = (props) => {
  const { selectedKey, onChange, onSaveChartsRangeSettings, loading } = props;
  const btns = [<Button type="primary" loading={loading}
                        onClick={onSaveChartsRangeSettings}>{getLabel(111, "保存")}</Button>];
  return <WeaReqTop
    title={getLabel(111, "分析图数据展示范围设置")} icon={<i className="icon-coms-fa"/>}
    iconBgcolor="#F14A2D" buttons={btns} showDropIcon={false}
    tabDatas={[
      { key: "1", title: "柱状图" },
      { key: "2", title: "折线图" },
      { key: "0", title: "饼图" }
    ]} selectedKey={selectedKey} onChange={onChange}
  />;
};
const RangSelect = payload => {
  const {
    label, onChange, value, options = [],
    viewAttr = 3, multiple = false, name,
    detailtype = 1, helpfulTip
  } = payload;
  return (
    <WeaFormItem label={
      <React.Fragment>
        <span style={{ marginRight: 8 }}>{label}</span>
        {
          helpfulTip &&
          <WeaHelpfulTip
            title={helpfulTip}
            placement="bottomLeft"
            width={260}
          />
        }
      </React.Fragment>
    } labelCol={{ span: 8 }} wrapperCol={{ span: 12 }}>
      <WeaError
        tipPosition="bottom" ref={name}
        error={getLabel(111, "此项必填")}>
        <WeaSelect options={multiple ? options : [{ key: "", showname: "" }, ...options]} viewAttr={viewAttr}
                   value={value} multiple={multiple} detailtype={detailtype}
                   onChange={val => onChange({ key: name, val })}/>
      </WeaError>
    </WeaFormItem>
  );
};
const RangMultiItem = payload => {
  const { label, onChange, value, options } = payload;
  const { itemSortValue, itemColSortValue, sortType, sortNum } = value;
  const { sortStatisticsOptions, sortColumnsOptions } = options;
  return (
    <WeaFormItem label={label} labelCol={{ span: 8 }} wrapperCol={{ span: 12 }}>
      <Row style={{ marginBottom: 16 }}>
        <Col span={8}>{getLabel(111, "排序统计项：")}</Col>
        <Col span={16}><WeaSelect options={sortStatisticsOptions} value={itemSortValue}
                                  onChange={val => onChange({ key: "itemSortValue", val })}/></Col>
      </Row>
      <Row style={{ marginBottom: 16 }}>
        <Col span={8}>{getLabel(111, "排序列：")}</Col>
        <Col span={16}><WeaSelect options={sortColumnsOptions} value={itemColSortValue}
                                  onChange={val => onChange({ key: "itemColSortValue", val })}/></Col>
      </Row>
      <Row style={{ marginBottom: 16 }}>
        <Col span={12}>
          <WeaSelect
            options={
              [
                { key: "0", showname: "升序" },
                { key: "1", showname: "降序" }
              ]
            }
            detailtype={3} value={sortType} onChange={val => onChange({ key: "sortType", val })}
          />
        </Col>
        <Col span={12} className="extraCol">
          <span style={{ marginRight: 8 }}>{getLabel(111, "前")}</span>
          <WeaInputNumber value={sortNum} precision={2} onChange={val => onChange({ key: "sortNum", val })}/>
        </Col>
      </Row>
    </WeaFormItem>
  );
};
