import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Select, TreeSelect } from 'amos-antd';
import { Input, Form, message, Modal } from 'amos-framework';
// import { currentUser } from 'amos-security/lib/model/auth';
import { PubSub } from 'ray-eventpool';
import { ELE_DEL_TOPIC, ELE_UPDATE_TOPIC } from './../ruleStatge/modelConf/stageConf';
import { subViewListAction, fetchSubEgpListAction, fetchCompanyById, subviewByOrgCodeAction } from './../../../services/topoService';
import { updateNode, fetchNodeConfigAction } from './../../../services/ruleDesignService';
import { getTaskDataAction } from './../../../services/monitorRuleService';
import { getCurrentUser } from './../../../services/securityService';

const Option = Select.Option;
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 DataSourceConfig
 * @extends {Component}
 */
class DataSourceConfig extends Component {
  constructor(props) {
    super(props);
    let { config } = this.props;
    this.state = {
      nodeConfig: {},
      form: {
        isSubUser: false,
        treeData: [],
        deviceOption: [],
        viewOption: [],
        taskOption: [],
        itemName: config.label,
        viewName: config.label,
        taskName: config.label,
        isEdited: false
      }
    };
  }
  componentWillMount() {}

  componentDidMount() {
    this.getSubviewByUserID();
    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 === 'datanodeDevice') {
          form.itemName = label;
        } else if (config.nodeType === 'datanodeView') {
          form.viewName = label;
        } else if (config.nodeType === 'datanodeTask') {
          form.taskName = 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 });
  };

  onSelect = (key, value) => {
    let { form } = this.state;
    form[key] = value;
    if (key === 'userType') {
      // this.getSubviewByUserID();
      // this.setState({ isSubUser: form[key] === '1' ? true : false });
    } else if (key === 'company') {
      form.device = undefined;
      form.view = undefined;
      this.getSubviewByOrgCode(value);
    } else if (key === 'view' && this.props.config.nodeType === 'datanodeDevice') {
      form.device = undefined;
      this.getEgpBySubviewID(value);
    }
    this.setState({ form, isEdited: true });
  };

  getNodeConfig = config => {
    fetchNodeConfigAction(config.id).then(data => {
      this.setState({ nodeConfig: data });
      //如果有配置信息，说明已经保存过了，需要初始化视图和设备的下拉框
      let { form } = this.state;
      form.itemName = data.label;
      if (config.nodeType === 'datanodeDevice') {
        if (data.configInfo) {
          //初始化form
          form.view = data.configInfo.view;
          form.device = data.configInfo.eqpId;
          form.company = data.configInfo.orgCode;
          form.itemName = data.configInfo.name;
          this.getSubviewByOrgCode(form.company);
          this.getEgpBySubviewID(form.view);
        } else {
          form.view = undefined;
          form.device = undefined;
          form.company = undefined;
          form.itemName = config.label;
        }
      } else if (config.nodeType === 'datanodeView') {
        if (data.configInfo) {
          //初始化form
          form.view = data.configInfo.view;
          form.company = data.configInfo.orgCode;
          form.viewName = data.configInfo.name;
          this.getSubviewByOrgCode(form.company);
        } else {
          form.view = undefined;
          form.company = undefined;
          form.viewName = config.label;
        }
      } else if (config.nodeType === 'datanodeTask') {
        if (data.configInfo) {
          //初始化form
          form.task = data.configInfo.monitorRuleId;
          form.taskName = data.configInfo.name;
        } else {
          form.task = undefined;
          form.taskName = config.label;
        }
        this.getAllTaskData();
      } else if (config.nodeType === 'datanodeCurrentUser') {
        form.userName = config.label;
      }

      this.setState({ form });
    });
  };

  getSubviewByUserID = () => {
    subViewListAction().then(data => {
      this.setState({ treeData: data });
    });
  };

  getSubviewByOrgCode = id => {
    fetchCompanyById(id).then(data => {
      data &&
        subviewByOrgCodeAction(data.compCode).then(data => {
          let viewOption = [];
          data.map(e =>
            viewOption.push(
              <Option key={e.id} value={`${e.id}`}>
                {e.name}
              </Option>
            )
          );
          this.setState({ viewOption });
        });
    });
  };

  getEgpBySubviewID = id => {
    if (id) {
      fetchSubEgpListAction(id).then(data => {
        let deviceOption = [];
        data.map(e =>
          deviceOption.push(
            <Option key={e.id} value={e.id}>
              {e.name}
            </Option>
          )
        );
        this.setState({ deviceOption });
      });
    }
  };

  getAllTaskData = () => {
    getTaskDataAction().then(data => {
      let taskOption = [];
      data.content.map(e =>
        taskOption.push(
          <Option key={e.id} value={e.id}>
            {e.name}
          </Option>
        )
      );
      this.setState({ taskOption });
    });
  };

  getFormByType = () => {
    const rules = {
      itemName: [{ required: true, message: '请输入活动名称' }, { min: 1, max: 150, message: '长度范围：0-150！' }],
      // userType: [
      //   { required: true, message: '不能为空！' },
      //   { validator: this.checkSelect }
      // ],
      subUser: [{ required: true, message: '不能为空！' }, { validator: this.checkSelect }],
      company: [{ required: true, message: '不能为空！' }, { validator: this.checkSelect }],
      view: [{ required: true, message: '不能为空！' }, { validator: this.checkSelect }],
      device: [{ required: true, message: '不能为空！' }, { validator: this.checkSelect }],
      task: [{ required: true, message: '不能为空！' }, { validator: this.checkSelect }]
    };
    let { config } = this.props;
    let { form, treeData, deviceOption, nodeConfig, viewOption, taskOption } = this.state;
    let htmlContent = [];
    //已保存节点配置信息时：第一次treeData赋值，第二次deviceOption赋值时渲染
    //未保存节点配置信息时：没有deviceOption赋值，所以treeData赋值时渲染
    if (config.nodeType === 'datanodeDevice' && treeData && (deviceOption !== undefined || nodeConfig.configInfo === null)) {
      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="userType" {...formItemLayout}>
            <Select
              style={{ width: '100%' }}
              dropdownStyle={{ width: '100%' }}
              dropdownMatchSelectWidth
              onChange={e => this.onSelect('userType', e)}
              placeholder="选择输入内容"
              value="0"
            >
              <Option key="0" value="0">
                当前用户
              </Option>
              {/*<Option key='1' value='1'>子用户</Option>*/}
            </Select>
          </FormItem>
          {/*{isSubUser ? <FormItem label="子用户" field="subUser" {...formItemLayout} >
          <Select
            style={{ width: '100%' }}
            dropdownStyle={{ width: '100%' }}
            dropdownMatchSelectWidth
            onChange={(e) => this.onSelect('subUser', e)}
            placeholder='选择输入内容'
            defaultValue='0'
          >
            <Option key='0' value='0'>所有</Option>
          </Select>
    </FormItem> : ''}*/}
          <FormItem label="公司" field="company" {...formItemLayout}>
            <TreeSelect
              dropdownMatchSelectWidth
              style={{ width: 'calc(20rem + 15px)' }}
              value={form.company}
              dropdownStyle={{ maxHeight: 160, overflow: 'auto', width: 'calc(20rem + 15px)' }}
              treeData={treeData}
              placeholder="选择公司"
              treeDefaultExpandAll
              onChange={e => this.onSelect('company', e)}
            />
          </FormItem>
          <FormItem label="视图" field="view" {...formItemLayout}>
            <Select
              style={{ width: '100%' }}
              dropdownStyle={{ width: '100%' }}
              dropdownMatchSelectWidth
              onChange={e => this.onSelect('view', e)}
              placeholder="选择输入内容"
              defaultValue={form.view}
              value={form.view}
            >
              {viewOption}
            </Select>
          </FormItem>
          <FormItem label="设备" field="device" {...formItemLayout}>
            <Select
              style={{ width: '100%' }}
              dropdownStyle={{ width: '100%' }}
              dropdownMatchSelectWidth
              onChange={e => this.onSelect('device', e)}
              placeholder="选择输入内容"
              defaultValue={form.device}
              value={form.device}
            >
              {deviceOption}
            </Select>
          </FormItem>
        </Form>
      );
    } else if (config.nodeType === 'datanodeCurrentUser') {
      // let user = currentUser();
      getCurrentUser().then(user => {
        htmlContent.push(
          <Form className="config-form" ref={component => (this.form = component)} model={form} rules={rules}>
            <FormItem label={<span>节点名称</span>} field="userName" {...formItemLayout}>
              <Input placeholder="输入内容" value={form.userName} disabled style={{ width: '100%' }} onChange={e => this.onInput('userName', e)} />
            </FormItem>
            <FormItem label="用户名" {...formItemLayout}>
              <Input placeholder="输入内容" defaultValue={user.userName} disabled style={{ width: '100%' }} />
            </FormItem>
          </Form>
        );
      });
    } else if (config.nodeType === 'datanodeTask') {
      htmlContent.push(
        <Form className="config-form" ref={component => (this.form = component)} model={form} rules={rules}>
          <FormItem label={<span>节点名称</span>} field="taskName" {...formItemLayout}>
            <Input placeholder="输入内容" value={form.taskName} style={{ width: '100%' }} onChange={e => this.onInput('taskName', e)} />
          </FormItem>
          <FormItem label="用户类型" field="userType" {...formItemLayout}>
            <Select
              style={{ width: '100%' }}
              dropdownStyle={{ width: '100%' }}
              dropdownMatchSelectWidth
              onChange={e => this.onSelect('userType', e)}
              placeholder="选择输入内容"
              value="0"
            >
              <Option key="0" value="0">
                当前用户
              </Option>
              {/*<Option key='1' value='1'>子用户</Option>*/}
            </Select>
          </FormItem>
          <FormItem label="任务" field="task" {...formItemLayout}>
            <Select
              style={{ width: '100%' }}
              dropdownStyle={{ width: '100%' }}
              dropdownMatchSelectWidth
              onChange={e => this.onSelect('task', e)}
              placeholder="选择输入内容"
              defaultValue={form.task}
              value={form.task}
            >
              {taskOption}
            </Select>
          </FormItem>
        </Form>
      );
    } else if (config.nodeType === 'datanodeView') {
      htmlContent.push(
        <Form className="config-form" ref={component => (this.form = component)} model={form} rules={rules}>
          <FormItem label={<span>节点名称</span>} field="viewName" {...formItemLayout}>
            <Input placeholder="输入内容" value={form.viewName} style={{ width: '100%' }} onChange={e => this.onInput('viewName', e)} />
          </FormItem>
          <FormItem label="用户类型" field="userType" {...formItemLayout}>
            <Select
              style={{ width: '100%' }}
              dropdownStyle={{ width: '100%' }}
              dropdownMatchSelectWidth
              onChange={e => this.onSelect('userType', e)}
              placeholder="选择输入内容"
              value="0"
            >
              <Option key="0" value="0">
                当前用户
              </Option>
              {/*<Option key='1' value='1'>子用户</Option>*/}
            </Select>
          </FormItem>
          <FormItem label="公司" field="company" {...formItemLayout}>
            <TreeSelect
              dropdownMatchSelectWidth
              style={{ width: 'calc(20rem + 15px)' }}
              value={form.company}
              dropdownStyle={{ maxHeight: 160, overflow: 'auto', width: 'calc(20rem + 15px)' }}
              treeData={treeData}
              placeholder="选择公司"
              treeDefaultExpandAll
              onChange={e => this.onSelect('company', e)}
            />
          </FormItem>
          <FormItem label="视图" field="view" {...formItemLayout}>
            <Select
              style={{ width: '100%' }}
              dropdownStyle={{ width: '100%' }}
              dropdownMatchSelectWidth
              onChange={e => this.onSelect('view', e)}
              placeholder="选择输入内容"
              defaultValue={form.view}
              value={form.view}
            >
              {viewOption}
            </Select>
          </FormItem>
        </Form>
      );
    }
    // else if (dataSourceType === 3) {
    //   htmlContent.push(<Form className="config-form" ref={component => this.form = component} model={form} rules={rules}>
    //     <FormItem label={<span>节点名称</span>} field="itemName" {...formItemLayout} >
    //       <Input placeholder="输入内容" defaultValue={form.itemName} style={{ width: '100%' }} />
    //     </FormItem>
    //     <FormItem label={<span>子用户</span>} field="subUser" {...formItemLayout} >
    //       <Select
    //         style={{ width: '100%' }}
    //         dropdownStyle={{ width: '100%' }}
    //         dropdownMatchSelectWidth
    //         onChange={(e) => this.test('name', e)}
    //         placeholder='选择输入内容'
    //       >
    //         <Option key='0' value='0'>所有</Option>
    //       </Select>
    //     </FormItem>
    //   </Form>);
    // }

    return htmlContent;
  };

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

  checkSelect = (rule, value, callback) => {
    if (value === '0') {
      callback('请选择！');
    } else {
      callback();
    }
  };

  saveConfig = () => {
    let { config } = this.props;
    let { form, nodeConfig } = this.state;
    let param;
    let configInfo;
    if (config.nodeType === 'datanodeDevice') {
      param = { nodeId: config.id, nodeType: config.nodeType, label: form['itemName'] === undefined ? nodeConfig.label : form['itemName'] };
      configInfo = {
        user_type: '0',
        view: form['view'] === undefined ? nodeConfig.configInfo.view : form['view'],
        eqpId: form['device'] === undefined ? nodeConfig.configInfo.eqpId : form['device'],
        orgCode: form['company'] === undefined ? nodeConfig.configInfo.orgCode : form['company']
      };
    } else if (config.nodeType === 'datanodeTask') {
      param = { nodeId: config.id, nodeType: config.nodeType, label: form['taskName'] === undefined ? nodeConfig.label : form['taskName'] };
      configInfo = {
        user_type: '0',
        monitorRuleId: form['task'] === undefined ? nodeConfig.configInfo.monitorRuleId : form['task']
      };
    } else if (config.nodeType === 'datanodeView') {
      param = { nodeId: config.id, nodeType: config.nodeType, label: form['viewName'] === undefined ? nodeConfig.label : form['viewName'] };
      configInfo = {
        user_type: '0',
        view: form['view'] === undefined ? nodeConfig.configInfo.view : form['view'],
        orgCode: form['company'] === undefined ? nodeConfig.configInfo.orgCode : form['company']
      };
    }
    param = { ...param, configInfo };
    updateNode(param).then(data => {
      PubSub.publish(ELE_UPDATE_TOPIC.trigger, { label: param.label, nodeId: config.id });
      message.success('保存成功');
    });
  };

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

  render() {
    let { closeTriggerDesigner, config } = this.props;
    let { isEdited } = this.state;
    return (
      <div className="data-source-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>
    );
  }
}

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

DataSourceConfig.defaultProps = {
  //dataSourceType: 1//1：设备节点 2：用户节点 3：子用户节点
};

export default DataSourceConfig;
