import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Input, Form, message } from 'amos-framework';
import { Checkbox } from 'amos-antd';
import { isNum } from 'ray-validate';
import { PubSub } from 'ray-eventpool';
import { ELE_DEL_TOPIC, ELE_UPDATE_TOPIC } from './../ruleStatge/modelConf/stageConf';
import { updateNode, fetchNodeConfigAction } from './../../../services/ruleDesignService';

const maxPort = 65535;
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6, offset: 0 },
    className: 'colspanlab'
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 17, offset: 0 },
    className: 'colspan'
  }
};

/**
 * 输出节点配置
 *
 * @class OutputNodeConfig
 * @extends {Component}
 */
class OutputNodeConfig extends Component {
  constructor(props) {
    super(props);
    let { config } = this.props;
    this.state = {
      form: {
        itemName: config.label,
        mqttName: config.label,
        tcpName: config.label,
        isEdited: false
      }
    };
  }
  componentWillMount() {}

  componentDidMount() {
    this.getNodeConfig(this.props.config);

    //updatename
    this.pubsub_update = PubSub.subscribe(ELE_UPDATE_TOPIC.eleUpdate, (topic, { label, nodeId }) => {
      let { config } = this.props;
      if (nodeId === config.id) {
        let { form } = this.state;
        if (config.nodeType === 'outputEmail') {
          form.itemName = label;
        } else if (config.nodeType === 'outputMqtt') {
          form.mqttName = label;
        } else if (config.nodeType === 'outputTcp') {
          form.tcpName = label;
        }
        this.setState({ form });
      }
    });
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.config.id !== nextProps.config.id) {
      this.getNodeConfig(nextProps.config);
    }
  }

  componentWillUnmount() {
    PubSub.unsubscribe(this.pubsub_update);
  }

  onInput = (key, e) => {
    let { form } = this.state;
    form[key] = e.target.value;
    this.setState({ form, isEdited: true });
  };

  onSelectedChange = e => {
    let { form } = this.state;
    form['emailSsl'] = !form['emailSsl'];
    this.setState({ form, isEdited: true });
  };

  getNodeConfig = config => {
    fetchNodeConfigAction(config.id).then(data => {
      let { form } = this.state;
      if (config.nodeType === 'outputEmail') {
        form['itemName'] = data.configInfo === null ? config.label : data.configInfo.name;
        form['emailAddress'] = data.configInfo === null ? '' : data.configInfo.toEmail;
        form['emailServer'] = data.configInfo === null ? 'smtp.exmail.qq.com' : data.configInfo.server;
        form['emailPort'] = data.configInfo === null ? '465' : data.configInfo.port;
        form['emailUser'] = data.configInfo === null ? 'amospm@yeejoin.com' : data.configInfo.fromEmail;
        form['emailPwd'] = data.configInfo === null ? 'QJamos_123' : data.configInfo.fromPassword;
        form['emailSsl'] = data.configInfo === null ? true : data.configInfo.isSSL;
      } else if (config.nodeType === 'outputMqtt') {
        form['mqttName'] = data.configInfo === null ? config.label : data.configInfo.name;
        form['mqttIP'] = data.configInfo === null ? '' : data.configInfo.serverIp;
        form['mqttPort'] = data.configInfo === null ? '' : data.configInfo.port;
        form['mqttTopic'] = data.configInfo === null ? '' : data.configInfo.theme;
        form['mqttUser'] = data.configInfo === null ? '' : data.configInfo.userName;
        form['mqttPwd'] = data.configInfo === null ? '' : data.configInfo.password;
      } else if (config.nodeType === 'outputTcp') {
        form['tcpName'] = data.configInfo === null ? config.label : data.configInfo.name;
        form['tcpServer'] = data.configInfo === null ? '' : data.configInfo.serverIp;
        form['tcpPort'] = data.configInfo === null ? '' : data.configInfo.port;
      }
      this.setState({ nodeConfig: data, form });
    });
  };

  getFormByType = () => {
    let { config } = this.props;
    let { form, nodeConfig } = this.state;
    let htmlContent = [];
    const rules = {
      itemName: [{ required: true, message: '请输入活动名称' }, { min: 1, max: 150, message: '长度范围：0-150！' }],
      emailAddress: [{ required: true, message: '不能为空！' }, { type: 'email', message: '非法的email地址！' }],
      emailServer: [{ required: true, message: '不能为空！' }],
      emailPort: [{ required: true, message: '不能为空！' }, { validator: this.checkPort }],
      emailUser: [{ required: true, message: '不能为空！' }, { type: 'email', message: '非法的email地址！' }],
      emailPwd: [{ required: true, message: '不能为空！' }],
      mqttName: [{ required: true, message: '不能为空！' }],
      mqttIP: [{ required: true, message: '不能为空！' }],
      mqttPort: [{ required: true, message: '不能为空！' }, { validator: this.checkPort }],
      mqttTopic: [{ required: true, message: '不能为空！' }],
      mqttUser: [{ required: true, message: '不能为空！' }],
      mqttPwd: [{ required: true, message: '不能为空！' }],
      tcpName: [{ required: true, message: '不能为空！' }],
      tcpPort: [{ required: true, message: '不能为空！' }, { validator: this.checkPort }],
      tcpServer: [{ required: true, message: '不能为空！' }]
    };
    if (nodeConfig) {
      //初始化配置信息
      if (config.nodeType === 'outputEmail') {
        htmlContent.push(
          <Form className="config-form" ref={component => (this.form = component)} model={form} rules={rules}>
            <FormItem label={<span>节点名称</span>} field="itemName" {...formItemLayout}>
              <Input placeholder="节点名称" value={form.itemName} style={{ width: '100%' }} onChange={e => this.onInput('itemName', e)} />
            </FormItem>
            <FormItem label="接收邮箱" field="emailAddress" {...formItemLayout}>
              <Input placeholder="接收邮箱" value={form['emailAddress']} style={{ width: '100%' }} onChange={e => this.onInput('emailAddress', e)} />
            </FormItem>
            <FormItem label="服务器" field="emailServer" {...formItemLayout}>
              <Input placeholder="服务器" value={form['emailServer']} style={{ width: '100%' }} onChange={e => this.onInput('emailServer', e)} />
            </FormItem>
            <FormItem label="端口" field="emailPort" {...formItemLayout}>
              <Input placeholder="端口" value={form['emailPort']} style={{ width: '46%', float: 'left' }} onChange={e => this.onInput('emailPort', e)} />
              <Checkbox
                value="0"
                checked={form['emailSsl']}
                onChange={selects => this.onSelectedChange(selects)}
                style={{ lineHeight: '31px', float: 'left', 'margin-left': '7px' }}
              >
                使用安全连接(SSL)
              </Checkbox>
            </FormItem>
            <FormItem label="发送邮箱" field="emailUser" {...formItemLayout}>
              <Input placeholder="发送邮箱" value={form['emailUser']} style={{ width: '100%' }} onChange={e => this.onInput('emailUser', e)} />
            </FormItem>
            <FormItem label="密码" field="emailPwd" {...formItemLayout}>
              <Input placeholder="密码" value={form['emailPwd']} style={{ width: '100%' }} onChange={e => this.onInput('emailPwd', e)} type="password" />
            </FormItem>
          </Form>
        );
      } else if (config.nodeType === 'outputMqtt') {
        htmlContent.push(
          <Form className="config-form" ref={component => (this.form = component)} model={form} rules={rules}>
            <FormItem label={<span>节点名称</span>} field="mqttName" {...formItemLayout}>
              <Input placeholder="节点名称" value={form.mqttName} style={{ width: '100%' }} onChange={e => this.onInput('mqttName', e)} />
            </FormItem>
            <FormItem label={<span>Broker</span>} field="mqttIP" {...formItemLayout}>
              <Input placeholder="mqtt服务所在服务器IP" value={form.mqttIP} style={{ width: '100%' }} onChange={e => this.onInput('mqttIP', e)} />
            </FormItem>
            <FormItem label={<span>端口</span>} field="mqttPort" {...formItemLayout}>
              <Input placeholder="mqtt服务端口号" value={form.mqttPort} style={{ width: '100%' }} onChange={e => this.onInput('mqttPort', e)} />
            </FormItem>
            <FormItem label={<span>主题</span>} field="mqttTopic" {...formItemLayout}>
              <Input placeholder="mqtt主题" value={form.mqttTopic} style={{ width: '100%' }} onChange={e => this.onInput('mqttTopic', e)} />
            </FormItem>
            <FormItem label="用户名" field="mqttUser" {...formItemLayout}>
              <Input placeholder="用户名" value={form['mqttUser']} style={{ width: '100%' }} onChange={e => this.onInput('mqttUser', e)} />
            </FormItem>
            <FormItem label="密码" field="mqttPwd" {...formItemLayout}>
              <Input placeholder="密码" value={form['mqttPwd']} style={{ width: '100%' }} onChange={e => this.onInput('mqttPwd', e)} type="password" />
            </FormItem>
          </Form>
        );
      } else if (config.nodeType === 'outputTcp') {
        htmlContent.push(
          <Form className="config-form" ref={component => (this.form = component)} model={form} rules={rules}>
            <FormItem label={<span>节点名称</span>} field="tcpName" {...formItemLayout}>
              <Input placeholder="节点名称" value={form.tcpName} style={{ width: '100%' }} onChange={e => this.onInput('tcpName', e)} />
            </FormItem>
            <FormItem label={<span>主机</span>} field="tcpServer" {...formItemLayout}>
              <Input placeholder="tcp服务所在服务器IP" value={form.tcpServer} style={{ width: '100%' }} onChange={e => this.onInput('tcpServer', e)} />
            </FormItem>
            <FormItem label={<span>端口</span>} field="tcpPort" {...formItemLayout}>
              <Input placeholder="tcp服务端口号" value={form.tcpPort} style={{ width: '100%' }} onChange={e => this.onInput('tcpPort', e)} />
            </FormItem>
          </Form>
        );
      }
    }
    return htmlContent;
  };

  /**
   * 校验端口
   */
  checkPort = (rule, value, callback) => {
    if (value && !isNum(value)) {
      callback('请输入正确的端口号！');
    } else {
      let port = parseInt(value);
      if (port > 0 && port < maxPort) {
        callback();
      } else {
        callback('端口号范围（0-65535）！');
      }
    }
  };

  handleSubmit = e => {
    e.preventDefault();
    this.form.validate((valid, dataValues) => {
      console.log('返回内容:', dataValues, valid);
      if (valid) {
        this.saveConfig();
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  };

  removeItem = (e, id) => {
    if (id) {
      PubSub.publish(ELE_DEL_TOPIC.trigger, {
        eleId: id
      });
      this.props.closeTriggerDesigner();
    }
  };

  saveConfig = () => {
    let { config } = this.props;
    let { form, nodeConfig } = this.state;
    let param;
    let configInfo;
    if (config.nodeType === 'outputEmail') {
      param = { nodeId: config.id, nodeType: config.nodeType, label: form['itemName'] === undefined ? nodeConfig.label : form['itemName'] };
      configInfo = {
        toEmail: form['emailAddress'] === undefined ? nodeConfig.configInfo.toEmail : form['emailAddress'],
        server: form['emailServer'] === undefined ? nodeConfig.configInfo.server : form['emailServer'],
        port: form['emailPort'] === undefined ? nodeConfig.configInfo.port : form['emailPort'],
        fromEmail: form['emailUser'] === undefined ? nodeConfig.configInfo.fromEmail : form['emailUser'],
        fromPassword: form['emailPwd'] === undefined ? nodeConfig.configInfo.fromPassword : form['emailPwd'],
        isSSL: form['emailSsl'] === undefined ? nodeConfig.configInfo.isSSL : form['emailSsl']
      };
    } else if (config.nodeType === 'outputMqtt') {
      param = { nodeId: config.id, nodeType: config.nodeType, label: form['mqttName'] === undefined ? nodeConfig.label : form['mqttName'] };
      configInfo = {
        serverIp: form['mqttIP'] === undefined ? nodeConfig.configInfo.serverIp : form['mqttIP'],
        port: form['mqttPort'] === undefined ? nodeConfig.configInfo.port : form['mqttPort'],
        theme: form['mqttTopic'] === undefined ? nodeConfig.configInfo.theme : form['mqttTopic'],
        userName: form['mqttUser'] === undefined ? nodeConfig.configInfo.userName : form['mqttUser'],
        password: form['mqttPwd'] === undefined ? nodeConfig.configInfo.password : form['mqttPwd']
      };
    } else if (config.nodeType === 'outputTcp') {
      param = { nodeId: config.id, nodeType: config.nodeType, label: form['tcpName'] === undefined ? nodeConfig.label : form['tcpName'] };
      configInfo = {
        serverIp: form['tcpServer'] === undefined ? nodeConfig.configInfo.serverIp : form['tcpServer'],
        port: form['tcpPort'] === undefined ? nodeConfig.configInfo.port : form['tcpPort']
      };
    }
    param = { ...param, configInfo };
    updateNode(param).then(data => {
      PubSub.publish(ELE_UPDATE_TOPIC.trigger, { label: param.label, nodeId: config.id });
      message.success('保存成功');
    });
  };

  render() {
    let { closeTriggerDesigner, config } = this.props;
    let { isEdited } = this.state;
    return (
      <div className="output-config-root">
        <div className="head-root">
          <div className="head-one">节点编辑</div>
          <div className="head-two">
            {/*<div className='head-two-one' />
            <div className='head-two-two' onClick={e=>this.removeItem(e,config.id)}>
              删除
            </div>*/}
            {isEdited ? (
              <div className="head-two-four" onClick={this.handleSubmit}>
                保存
              </div>
            ) : (
              ''
            )}
            <div className="head-two-three" onClick={closeTriggerDesigner}>
              取消
            </div>
          </div>
        </div>
        <div className="content-panel">{this.getFormByType()}</div>
      </div>
    );
  }
}

OutputNodeConfig.propTypes = {
  config: PropTypes.object,
  closeTriggerDesigner: PropTypes.func
};

OutputNodeConfig.defaultProps = {
  // outputType: 1//1：mail
};

export default OutputNodeConfig;
