import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form,Row,Col,Select,Input,Tabs,Transfer,Icon,Button,Modal } from 'amos-antd';
import { AmosFetch } from '../../utils/processor';
import { trim } from 'amos-tool';
import OltSerUrl from '../../consts/urlConsts';
import { message } from 'amos-framework';
import './common/index.scss';

const TabPane = Tabs.TabPane;
const createForm = Form.create();
const FormItem = Form.Item;
const Option = Select.Option;

const monitorTypeArr = [
  { title: '采集', value: 1 },
  { title: '监听', value: 2 }
];

const periodArr = [
  { title: '30秒/次', value: 30 },
  { title: '60秒/次', value: 60 },
  { title: '300秒/次', value: 300 },
  { title: '900秒/次', value: 900 },
  { title: '1800秒/次', value: 1800 }
];

const noSpaceLengthValidate = (maxLength) => {
  return (rule, value, callback) => {
    if (value){
      if (/^\S*$/.test(value)){
        if (trim(value).length > maxLength){
          callback(`支持1-${maxLength}位非空格字符！`);
        }
      } else {
        callback(`支持1-${maxLength}位非空格字符！`);
      }
    }
    callback();
  };
};

const nameIsReplaceValidate = (oldName) => {
  return (rule, value, callback) => {
    if (value){
      if (value === oldName){
        callback();
      } else {
        let url = `${OltSerUrl.monitorRuleNameIsReplace}/${value}`;
        AmosFetch.get(url).then(res => {
          if (res.ok) {
            return res.json();
          }
          else
            {
            throw new Error('从服务端获取数据失败！');
          }
        }).then((data)=>{
          if (data.result === 'SUCCESS'){
            if (data.message === 'ok'){
              callback();
            } else {
              callback('任务名称重复，请重新输入！');
            }
          } else {
            callback('系统错误！');
          }
        });
      }
    } else {
      callback();
    }
  };
};

/**
 * 新增监测规则
 * @class AddRule
 * @extends {Component}
 */
class AddEditRule extends Component {
  constructor(props) {
    super(props);
    this.state = {
      mockData: [],
      targetKeys: []
    };
  }

  componentWillMount(){
    let monitorRuleInfo = this.props.monitorRuleInfo;
    this.setState({
      targetKeys: monitorRuleInfo.deviceIds
    });
  }

  /**
   * 初始化
   */
  componentDidMount() {
    this.getMock();
  }

  componentWillReceiveProps(nextProps){
    if (nextProps.monitorRuleInfo){
      this.setState({
        targetKeys: nextProps.monitorRuleInfo.deviceIds
      });
    }

  }
  getMock = () => {
    AmosFetch.get(OltSerUrl.realDevice).then(res => {
      if (res.ok) {
        return res.json();
      }
      else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      if (data.result === 'SUCCESS'){
        if (data.dataList.length !== 0){
          this.makeMock(data.dataList);
        }
      }
      this.setState({ dataList: [] });
    });
  }

  makeMock = (dataList) => {
    let mockData = [];
    dataList.map(data=>{
      data.key = data.id;
      data.title = data.name;
      mockData.push(data);
    });
    this.setState({ dataList,mockData });
  }

  handleSave = (obj) => {
    let { targetKeys } = this.state;
    let { monitorRuleInfo } = this.props;
    monitorRuleInfo.name = obj.name;
    monitorRuleInfo.monitorType = obj.monitorType;
    if (obj.monitorType === '1'){
      monitorRuleInfo.period = obj.period;
    } else {
      monitorRuleInfo.period = 0;
    }
    monitorRuleInfo.remark = obj.remark;
    if (!targetKeys || targetKeys.length === 0){
      Modal.info({
        title: '系统提示',
        content: '监测对象不能为空！'
      });
      return;
    }
    monitorRuleInfo.deviceIds = targetKeys;
    AmosFetch.post(OltSerUrl.monitorRuleAddOrUpdate,{ data: monitorRuleInfo }).then(res => {
      if (res.ok) {
        return res.json();
      }
      else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      if (data.result === 'SUCCESS'){
        this.handleCancel();
        message.success('保存成功！');
      } else {
        message.danger('保存失败！');
      }
    });
  }
  /**
   * 关闭新增监测规则对话框
   */
  handleCancel = () => {
    this.props.form.resetFields();
    this.setState({
      targetKeys: []
    });
    this.props.cancel();
    this.props.reload();
  }
  /**
   * 保存按钮事件
   */
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((errors, values) => {
      if (errors) {
        return;
      }
      this.handleSave(values);
    });
  }

  handleChange = (targetKeys) => {
    this.setState({ targetKeys });
  }

  monitorTypeChange = (value) => {
    this.props.typeChange(value);
  }
  render() {
    let { mockData,targetKeys } = this.state;
    let { monitorRuleInfo,isCycle } = this.props;
    let { name, monitorType, period, remark } = monitorRuleInfo;
    const { getFieldProps } = this.props.form;
    const nameProps = getFieldProps('name', {
      initialValue: name,
      rules: [
          { required: true, message: '任务名称不能为空！' },
          { validator: noSpaceLengthValidate(50) },
          { validator: nameIsReplaceValidate(name) }
      ]
    });
    const monitorTypeProps = getFieldProps('monitorType', {
      initialValue: monitorType ? `${monitorType}` : '2',
      rules: [
          { required: true, message: '请选择监测方式！' }
      ]
    });
    const periodProps = getFieldProps('period', {
      initialValue: period ? `${period}` : '30',
      rules: [
      ]
    });
    const remarkProps = getFieldProps('remark', {
      initialValue: remark,
      rules: [
        { validator: noSpaceLengthValidate(500) }
      ]
    });
    const formItemLayout = {
      labelCol: { span: 9 },
      wrapperCol: { span: 8 }
    };
    return (
      <div>
        <div className='amos-grid-from'>
          <Form inline onSubmit={this.handleSubmit}>
            <Row style={{ marginTop: '20px' }} >
              <Col span={24}>
                <FormItem hasFeedback label={'任务名称'}  {...formItemLayout}>
                  <Input className='amos-grid-form-input' {...nameProps} placeholder='请输入任务名称' style={{ width: '250px' }} />
                </FormItem>
              </Col>
            </Row>
            <Row style={{ marginTop: '20px' }}>
              <Col span={24}>
                <FormItem hasFeedback label={'监测方式'}  {...formItemLayout} >
                  <Select style={{ width: 250 }} onSelect={this.monitorTypeChange} {...monitorTypeProps}  placeholder='请选择监测方式' >
                    {
                      monitorTypeArr.map(data => <Option key={`${data.value}`} value={`${data.value}`}>{data.title}</Option>)
                    }
                  </Select>
                </FormItem>
              </Col>
            </Row>
            {
              isCycle ?
                <Row style={{ marginTop: '20px' }}>
                  <Col span={24}>
                    <FormItem label={'任务周期'}  {...formItemLayout}>
                      <Select style={{ width: 250 }}  {...periodProps}  placeholder='请选择任务周期' >
                        {
                          periodArr.map(data => <Option key={`${data.value}`} value={`${data.value}`}>{data.title}</Option>)
                        }
                      </Select>
                    </FormItem>
                  </Col>
                </Row> :
              null
            }
            <Row style={{ marginTop: '20px' }}>
              <Col span={24}>
                <FormItem label={'描述'}  {...formItemLayout}   placeholder='请输入描述'>
                  <Input className='amos-grid-form-input' width={250} {...remarkProps} />
                </FormItem>
              </Col>
            </Row>
          </Form>
        </div>
        <div>
          <Tabs defaultActiveKey='监测对象'>
            <TabPane tab={<span><Icon type='android' />监测对象</span>} key='监测对象'>
              <div style={{ width: '100%',height: '100%', overflow: 'auto' }}>
                <Transfer
                  dataSource={mockData}
                  showSearch
                  listStyle={{
                    width: 250,
                    height: 300,
                    color: '#666'
                  }}
                  operations={[ '添加', '移除' ]}
                  targetKeys={targetKeys}
                  onChange={this.handleChange}
                  render={item => `${item.title}`}
                />
              </div>
            </TabPane>
          </Tabs>
        </div>
        <Row style={{ textAlign: 'center',marginTop: '3rem' }} >
          <Button type='primary' onClick={this.handleSubmit} >确定</Button>
          <Button type='primary' onClick={this.handleCancel} style={{ marginLeft: '10px' }} >取消</Button>
        </Row>
      </div>
    );
  }
}

AddEditRule.propTypes = {
  form: PropTypes.any,
  cancel: PropTypes.func,
  monitorRuleInfo: PropTypes.any,
  reload: PropTypes.func,
  flag: PropTypes.any,
  typeChange: PropTypes.func,
  isCycle: PropTypes.any
};

AddEditRule.defaultProps = {
  monitorRuleInfo: { monitorType: '' }
};
export default createForm(AddEditRule);
