import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { WeaLocaleProvider, WeaReqTop } from "ecCom";
import { Button, message, Modal } from "antd";
import EnableSettings from "./components/enableSettings";
import InsufficientTrafficAlert from "./components/insufficientTrafficAlert";
import TrafficUsageRecords from "./components/trafficUsageRecords";
import InterfaceFlowStatistics from "./components/interfaceFlowStatistics";
import { apiflowWarnConfigSave } from "../../apis/intelligentCalculateSalarySettings";
import "./index.less";
import { convertToUrlString } from "../../util/url";

const getLabel = WeaLocaleProvider.getLabel;
const tabs = [
  { key: "ENABLE_SETTINGS", title: getLabel(111, "启用设置") },
  { key: "INTERFACE_FLOW_STATISTICS", title: getLabel(111, "接口流量统计") },
  { key: "INSUFFICIENT_TRAFFIC_ALERT", title: getLabel(111, "流量不足提醒") },
  { key: "TRAFFIC_USAGE_RECORD", title: getLabel(111, "流量使用记录") }
];

@inject("intelligentStore")
@observer
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedKey: "ENABLE_SETTINGS", lastUpdateTime: "",
      loading: false, warnConfigId: ""
    };
    this.alertRef = null;
  }

  /*
   * Author: 黎永顺
   * Description:流量不足提醒 - 基础信息保存
   * Params:
   * Date: 2023/8/29
   */
  saveItaBaseInfo = () => {
    const { channelList, enable, threshold, remindEvent } = this.alertRef.state;
    const validateError = (enable === "1") && (_.every(channelList, o => o.channel !== "1") || _.isNil(threshold));
    if (validateError) {
      Modal.warning({
        title: getLabel(131329, "信息确认"),
        content: getLabel(518702, "必要信息不完整，红色*为必填项！")
      });
      return;
    }
    const { businessId, id } = remindEvent;
    const config = _.map(_.filter(channelList, p => p.value === "1"), o => ({ channel: o.channel, config: o.config }));
    const payload = {
      id, businessId, threshold,
      enable: enable === "1",
      config: JSON.stringify(config)
    };
    this.setState({ loading: true });
    apiflowWarnConfigSave(payload).then(({ status, data, errormsg }) => {
      this.setState({ loading: false });
      if (status) {
        message.success(getLabel(22619, "保存成功！"));
        this.setState({ warnConfigId: data });
        payload.enable && this.alertRef.apiflowWarnReceiverList();
      } else {
        message.error(errormsg);
      }
    }).catch(() => this.setState({ loading: false }));
  };
  renderChildren = () => {
    const { selectedKey, warnConfigId } = this.state;
    let CurrentDom = null;
    switch (selectedKey) {
      case "ENABLE_SETTINGS":
        CurrentDom = <EnableSettings/>;
        break;
      case "INTERFACE_FLOW_STATISTICS":
        CurrentDom =
          <InterfaceFlowStatistics updateTime={(data) => this.setState({ lastUpdateTime: data.lastUpdateTime })}/>;
        break;
      case "INSUFFICIENT_TRAFFIC_ALERT":
        CurrentDom = <InsufficientTrafficAlert ref={dom => this.alertRef = dom} warnConfigId={warnConfigId}/>;
        break;
      case "TRAFFIC_USAGE_RECORD":
        CurrentDom = <TrafficUsageRecords/>;
        break;
      default:
        CurrentDom = null;
        break;
    }
    return CurrentDom;
  };
  handleExport = () => {
    const { intelligentStore: { form } } = this.props;
    window.open(`${window.ecologyContentPath || ""}/api/bs/hrmsalary/taxdeclaration/apiflow/record/export?${convertToUrlString(form.getFormParams())}`, "_blank");
  };

  render() {
    const { selectedKey, lastUpdateTime, loading } = this.state;
    const buttons = selectedKey === "INSUFFICIENT_TRAFFIC_ALERT" ?
      [<Button type="primary" onClick={this.saveItaBaseInfo} loading={loading}>{getLabel(537558, "保存")}</Button>] :
      selectedKey === "TRAFFIC_USAGE_RECORD" ?
        [<Button type="primary" onClick={this.handleExport}>{getLabel(17416, "导出")}</Button>] :
        selectedKey === "INTERFACE_FLOW_STATISTICS" ? [
          <span className="statistic-time">
            <span className="label">{getLabel(111, "最后统计时间：")}</span>
            <span className="value">{lastUpdateTime}</span>
          </span>
        ] : [];
    return (
      <WeaReqTop
        title={getLabel(111, "智能算薪")} selectedKey={selectedKey}
        icon={<i className="icon-coms-fa"/>} iconBgcolor="#F14A2D"
        tabDatas={tabs} onChange={selectedKey => this.setState({ selectedKey })}
        buttons={buttons} className="intelligentSetting-layout"
      >
        <div style={{ height: "100%", background: "#f6f6f6", padding: 16 }}>{this.renderChildren()}</div>
      </WeaReqTop>
    );
  }
}

export default Index;
