/*
 * Author: 黎永顺
 * name:流量不足提醒
 * Description:
 * Date: 2023/7/19
 */
import React, { Component } from "react";
import {
  WeaButtonIcon,
  WeaCheckbox,
  WeaFormItem,
  WeaInputNumber,
  WeaLocaleProvider,
  WeaSearchGroup,
  WeaTable
} from "ecCom";
import { message, Modal, Spin } from "antd";
import EditBeRemindObjDialog from "./editBeRemindObjDialog";
import {
  apiflowWarnConfigGetForm,
  apiflowWarnReceiverDelete,
  apiflowWarnReceiverList
} from "../../../apis/intelligentCalculateSalarySettings";

const getLabel = WeaLocaleProvider.getLabel;

class InsufficientTrafficAlert extends Component {
  constructor(props) {
    super(props);
    this.state = {
      enable: "0",
      remindEvent: { businessId: "", eventId: "", moduleId: "", id: "" },
      threshold: null, channelList: [
        { label: "EMobile", type: "IM", channel: "1", value: "1", config: {} },
        { label: "邮件", type: "email", channel: "3", value: "1", config: {} },
        { label: "短信", type: "message", channel: "4", value: "1", config: {} }
      ], columns: [], dataSource: [],
      loading: false, remindObjDialog: { visible: false, title: "", warnConfigId: "", id: "" }
    };
  }

  componentDidMount() {
    this.apiflowWarnConfigGetForm();
  }

  apiflowWarnConfigGetForm = () => {
    const { remindEvent } = this.state;
    apiflowWarnConfigGetForm().then(({ status, data }) => {
      if (status) {
        const { enable, businessId, eventId, moduleId, id, threshold } = data;
        this.setState({
          enable: enable ? "1" : "0",
          remindEvent: { ...remindEvent, businessId, eventId, moduleId, id },
          threshold
        }, () => {
          this.state.enable === "1" && this.apiflowWarnReceiverList();
        });
      }
    });
  };
  apiflowWarnReceiverList = () => {
    const { remindEvent } = this.state;
    const { id } = remindEvent;
    const payload = {
      warnConfigId: id || this.props.warnConfigId
    };
    apiflowWarnReceiverList(payload).then(({ status, data }) => {
      if (status) {
        const { columns, list: dataSource } = data;
        this.setState({
          dataSource,
          columns: _.map(columns, item => {
            const { dataIndex } = item;
            let width = "";
            switch (dataIndex) {
              case "employeeName":
              case "mobile":
                width = "30%";
                break;
              case "email":
                width = "40%";
                break;
              default:
                break;
            }
            return { ...item, width };
          })
        });
      }
    });
  };
  apiflowWarnReceiverDelete = (id) => {
    Modal.confirm({
      title: getLabel(131329, "信息确认"),
      content: getLabel(111, "确定删除吗？删除后数据不可找回"),
      onOk: () => {
        apiflowWarnReceiverDelete({ id }).then(({ status, errormsg }) => {
          if (status) {
            message.success(getLabel(502230, "删除成功！"));
            this.apiflowWarnReceiverList();
          } else {
            message.error(errormsg || getLabel(20462, "删除失败！"));
          }
        });
      }
    });
  };
  handleEnale = (enable) => {
    if (enable === "1") {
      this.setState({ enable }, () => this.apiflowWarnReceiverList());
    } else {
      Modal.confirm({
        title: getLabel(131329, "信息确认"),
        content: getLabel(111, "确认关闭提醒吗？关闭并保存后，流量不足时将无法及时提醒。"),
        onOk: () => {
          this.setState({ enable });
        },
        onCancel: () => {
          this.setState({ enable: this.state.enable });
        }
      });
    }
  };
  handleChangeChannel = (o) => {
    const { channelList } = this.state;
    this.setState({
      channelList: _.map(channelList, item => {
        if (item.type === o.type) {
          return { ...item, ...o };
        }
        return { ...item };
      })
    });
  };

  render() {
    const {
      remindEvent, enable, channelList, threshold,
      loading, columns, dataSource, remindObjDialog
    } = this.state;
    const { id } = remindEvent;
    return (
      <WeaSearchGroup showGroup needTigger={false} className="insufficientAlertWrapper">
        <WeaFormItem label={getLabel(501480, "提醒")} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
          <WeaCheckbox display="switch" value={enable} onChange={this.handleEnale}/>
        </WeaFormItem>
        {
          enable === "1" &&
          <React.Fragment>
            <WeaFormItem
              label={getLabel(544288, "提醒规则")}
              labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}
            >
              <ReminderRules value={threshold} onChange={o => this.setState({ threshold: o })}/>
            </WeaFormItem>
            {/*<WeaFormItem*/}
            {/*  colon={false} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}*/}
            {/*  label={*/}
            {/*    <div className="flex items-center">*/}
            {/*      <span>{getLabel(544287, "提醒推送方式")}:</span>*/}
            {/*      <WeaHelpfulTip*/}
            {/*        width={200} style={{ marginLeft: 10 }}*/}
            {/*        title={getLabel(111, "使用邮箱之前，请先确认是否设置邮件提醒账号。\n" + "使用短信之前，请先确认是否新建签名。")}*/}
            {/*        placement="topLeft"*/}
            {/*      />*/}
            {/*    </div>*/}
            {/*  }*/}
            {/*>*/}
            {/*  <Pushmethod channelList={channelList} onChange={this.handleChangeChannel}/>*/}
            {/*</WeaFormItem>*/}
          </React.Fragment>
        }
        {
          enable === "1" &&
          <div className="table">
            <div className="title flex items-center">
              <span className="titleLeft">{getLabel(111, "提醒对象设置")}</span>
              <WeaButtonIcon
                buttonType="add" type="primary"
                onClick={() => this.setState({
                  remindObjDialog: {
                    ...remindObjDialog, visible: true, title: getLabel(111, "添加提醒对象"),
                    warnConfigId: id || this.props.warnConfigId
                  }
                })}
              />
              {/*  添加提醒对象*/}
              <EditBeRemindObjDialog
                {...remindObjDialog}
                updateWarnList={this.apiflowWarnReceiverList}
                onCancel={() => this.setState({
                  remindObjDialog: {
                    ...remindObjDialog, visible: false, title: "", warnConfigId: "", id: ""
                  }
                })}
              />
            </div>
            {
              loading ? <div className="loading-layout">
                <Spin spinning={loading}/>
              </div> : <WeaTable
                dataSource={dataSource} loading={loading}
                columns={[
                  ...columns,
                  {
                    title: getLabel(30585, "操作"), dataIndex: "operate", width: 120,
                    render: (__, record) => (<div className="space">
                      <a
                        href="javascript:void(0);" className="mr10"
                        onClick={() => this.setState({
                          remindObjDialog: {
                            ...remindObjDialog, visible: true, title: getLabel(111, "添加提醒对象"),
                            warnConfigId: id || this.props.warnConfigId, id: record.id
                          }
                        })}>{getLabel(501169, "编辑")}</a>
                      <a href="javascript:void(0);"
                         onClick={() => this.apiflowWarnReceiverDelete(record.id)}>{getLabel(535052, "删除")}</a>
                    </div>)
                  }
                ]} pagination={false}
                scroll={{ y: `calc(100vh - 190px)` }}
              />
            }
          </div>
        }
      </WeaSearchGroup>
    );
  }
}

export default InsufficientTrafficAlert;


const ReminderRules = (props) => {
  const { onChange, value } = props;
  return (
    <div className="threshold">
      <span className="before">{getLabel(111, "流量不足")}</span>
      <WeaInputNumber value={value} onChange={onChange} style={{ width: 180 }} viewAttr={3}/>
      <span className="after">{getLabel(111, "时提醒")}</span>
      <span
        className="tip">{getLabel(111, "为确保智能算薪正常使用，设置建议:若每个月消耗流量10,000，则不足10,000时提醒，以此预留一个月时间续流量")}</span>
    </div>
  );
};

const Pushmethod = (props) => {
  const { onChange, channelList } = props;
  return <div className="channel-list">
    {
      _.map(channelList, item => {
        const { label, type, value } = item;
        return (
          <div className="channel-item">
            <WeaCheckbox value={value} content={label} onChange={o => onChange({ ...item, value: o })}/>
            {(type !== "email" && value === "1") && <i className="icon-coms-Flow-setting"/>}
          </div>
        );
      })
    }
  </div>;
};


