import React, { Component } from 'react';
import { DatePicker, TreeSelect } from 'amos-antd';
import moment from 'moment';
import { browserHistory } from 'amos-react-router';
import { Form, AmosAlert, Input, Radio, Button, Select } from 'amos-framework';
import { pathMapping } from './../../../routes/customRoutes';
import { newsPersonDataAction, sendNewsAction,newsPersonDataAction1 } from '../../../services/newsService';
import HasPermission from './../../component/toolbar/hasPermission';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Option = Select.Option;
/**
 * 添加消息通知
 *
 * @class NewsAdd
 * @extends {Component}
 */
class NewsAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      form: {
        body: '',
        userId: [],
        isImmediately: true,
        fixedTime: moment().format('YYYY-MM-DD HH:mm:ss')
      },
      userData: [],
      rules: {
        body: [{ required: true, message: '请输入通知内容' }],
        userId: [{ required: true, message: '请选择接收人员' }],
        isImmediately: [{ required: true }]
      }
    };
  }

  componentWillMount = () => {
    newsPersonDataAction1().then(d => {
      d.map(item => {
        const dpetStr = 'department';
        item.id = item.id + dpetStr;
        item.key = item.key + dpetStr;
        item.value = item.value + dpetStr;
        if (item.children.length === 0) {
          item.disabled = true;
        }
        if (item.children.length > 0) {
          item.children.map(t => {
            t.title = t.label;
          });
        }
      });
      this.setState({ userData: d });
    });
  };

  onChange = (key, e) => {
    const { form } = this.state;
    const value = e.target.value;
    form[key] = value;
    this.setState({ form });
  };

  onDateChange = (key, date) => {
    const { form } = this.state;
    form[key] = moment(date).format('YYYY-MM-DD HH:mm:ss');
    this.setState({ form });
  };

  onSelectChange = (key, value) => {
    const { form } = this.state;
    form[key] = value;
    this.setState({ form });
  };

  onTreeSelectChange = (key, value) => {
    
  // let valuesd=value.substr(0,value.indexOf('*'));
    const { form } = this.state;
    let _value = value.filter(item => {
      if (Number.isInteger(item)) {
        return true;
      } else if (item.search('department') === -1){
        return true;
      }
    });
    let _value1 = _value.map(x=>x.substr(0,x.indexOf('*')));
    //let _value1 = _value.map(x=>x);
    form[key] = _value1;
    this.setState({ form });
  };


  
handleExecutorsChange = (executorList, label, extra) => {
    let pro = label.props;
    // pro.children
    const { form } = this.state;
    if (pro.children || pro.type === 'department') {
      form.executor = '';
    } else {
      form.executor = pro.title;
      form.executorId = parseInt(pro.value);
    }
    // if (label.length > 0) {
    //   form.executor = label.join('  ');
    // } else {
    //   form.executor = '';
    // }
    this.setState({ form });
  };


  handleSubmit = e => {
    this.form.validate((valid, dataValues) => {
      if (valid) {
        let param = {};
        let { form } = this.state;
        // form.userId= [parseInt(form.userId)];

       
        Object.assign(param, form);
        if (!form.fixedTime) {
          param.fixedTime = moment().format('YYYY-MM-DD HH:mm:ss');
        }
        console.log('----------------->', param);
        sendNewsAction(param).then(
          data => {
            AmosAlert.success('提示', '保存成功');
            this.handleCancel();
          },
          err => {
            AmosAlert.error('错误', err);
          }
        );
      } else {
        return false;
      }
    });
  };

  handleCancel = e => {
    browserHistory.goBack(pathMapping.news);
  };
  /**
   *
   *
   * @returns
   * @memberof NewsAdd
   */
  render() {
    const { form, userData, rules } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
        className: 'colspan'
      }
    };
    const wrapperCol = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 14, offset: 4 }
      }
    };

    return (
      <div className="plan_edit_div">
        <Form model={form} rules={rules} ref={component => this.form = component}>
          <FormItem label={<span>通知内容</span>} field="body" {...formItemLayout}>
            <TextArea style={{ padding: 5, width: '20rem' }} value={form.body} rows={4}  onChange={e => this.onChange('body', e)} />
          </FormItem>
          <FormItem label={<span>接收人员</span>} field="userId" {...formItemLayout}>
            <TreeSelect
              className="plan_multi-select"
              treeData={userData}
              searchPlaceholder="请选择"
              treeCheckable
              values={form.userId}
              style={{ width: 240, maxHeight: 300, overflow: 'auto' }}
              onChange={e => this.onTreeSelectChange('userId', e)}
            />

            {/* <Select data={userData}
           renderOption={item => <Option value={item.id}>{item.name}</Option>}
           defaultOption={<Option>选择人员</Option>}
           onChange={this.onSelectChange}/> */}



          </FormItem>
          <FormItem label={<span>消息提醒</span>} field="isImmediately" {...formItemLayout}>
            <RadioGroup  value={form.isImmediately ? '1' : '0'} onChange={e => this.onSelectChange('isImmediately', e === '1' ? true : false)}>
              <Radio value="1">立即提醒</Radio>
              <Radio value="0">定时提醒</Radio>
            </RadioGroup>
          </FormItem>
         
          <FormItem label={<span>提醒时间</span>} field="fixedTime" {...formItemLayout}>
            <DatePicker
              disabled={form.isImmediately}
              value={moment(form.fixedTime)}
              allowClear={false}
              className="plan_task_gen_select"
              defaultValue={moment()}
              format="YYYY-MM-DD HH:mm:ss"
              onChange={e => this.onDateChange('fixedTime', e)}
              showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
            />
          </FormItem>
          <FormItem {...wrapperCol}>
            <HasPermission permissionCode="plan">
              <Button onClick={this.handleSubmit}>提交</Button>
            </HasPermission>
            <Button onClick={this.handleCancel}>返回</Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}

export default NewsAdd;
