import React, { Component } from 'react';
import moment from 'moment';
import { Form, Input, AmosAlert, Button, Checkbox, InputNumber, Select } from 'amos-framework';
import { TreeSelect, DatePicker } from 'amos-antd';
import PropTypes from 'prop-types';
import { browserHistory } from 'amos-react-router';
import './../../../styles/view/patrol/inputItem.scss';
import CommonTable from '../inputItem/CommonTable';
import { saveTaskAction, queryDeptUserTree } from '../../../services/checkService';
import HasPermission from './../../component/toolbar/hasPermission';

const TextArea = Input.TextArea;
const FormItem = Form.Item;
const Option = Select.Option;

class NewTask extends Component {
  constructor(props) {
    super(props);
    this.state = {
      form: {
        title: '',
        executor: '',
        maxDepth: 2,
        finishTime: '',
        isWarn: '',
        warnTime: '',
        remark: '',
        isPicture: '',
        shotMinNumber: 1,
        shotMaxNumber: 5
      },
      executors: [],
      tableData: [],
      rules: {
        title: [{ required: true, message: '请输入检查项名称' }],
        executor: [{ required: true, message: '请输入执行人' }],
        finishTime: [{ required: true, message: '请输入要求完成时间' }]
      }
    };
  }

  /**
   * 组件初始化调用
   */
  componentWillMount = () => {
    this.loadexecutor();
  };

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


  onChangePicInput = (record, e) => {
    const { tableData } = this.state;
    for (let i = 0; i < tableData.length; i++) {
      if (tableData[i].orderNo === record.orderNo) {
        tableData[i].name = e;
      }
    }
    this.setState(tableData);
  };

  onChangePicCheckBox = (record, checked) => {
    const { tableData } = this.state;
    for (let i = 0; i < tableData.length; i++) {
      if (tableData[i].orderNo === record.orderNo) {
        tableData[i].isMust = checked ? '是' : '否';
      }
    }
    this.setState(tableData);
  };
  onChangeTableValues = values => {
    this.setState({ tableData: values });
  };

  /**
   * 获取表格表头
   */
  getPicTablecolumns = () => {
    return [
      {
        title: '名称',
        dataIndex: 'name',
        render: (text, record) => {
          return !record.edit ? text : <Input onChange={e => this.onChangePicInput(record, e.target.value)} value={text} />;
        }
      },
      {
        title: '是否拍照',
        dataIndex: 'isMust',
        render: (text, record) => {
          return !record.edit ? (
            text ? (
              text
            ) : (
                '否'
              )
          ) : (
              <Checkbox
                onChange={e => this.onChangePicCheckBox(record, e.target.checked)}
                checked={text === undefined || text === '否' ? false : true}
                defaultChecked={text === undefined || text === '否' ? false : true}
              />
            );
        }
      }
    ];
  };

  loadexecutor = () => {
    queryDeptUserTree().then(data => {

      let deptPersons = data.filter(item => item.children !== null);
      deptPersons.map(item => {
        if (item.children.length > 0) {
          item.children.map(t => {
            t.title = t.label;
          });
        }
      });
      this.setState({ executors: deptPersons });
    });
  };

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


  onSelectChange = (value, item) => {
    const { form } = this.state;
    form.executor = item.name;
    form.executorId = parseInt(value);
    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 => {
    e.preventDefault();
    this.form.validate((valid, dataValues) => {
      if (valid) {
        const { form, tableData } = this.state;
        let taskInfo = Object();
        Object.assign(taskInfo, form);
        if (taskInfo.isWarn === true) {
          taskInfo.isWarn = '是';
        } else {
          taskInfo.isWarn = '否';
        }
        if (taskInfo.finishTime.isBefore(moment())) {
          taskInfo.status = 3;
        }
        // let pic = tableData.map(item => {
        //   let obj = new Object();
        //   obj.isMust = item.isMust;
        //   obj.name = item.name;
        //   return obj;
        // });
        taskInfo.finishTime = moment(taskInfo.finishTime).format('YYYY-MM-DD HH:mm:ss');
        if (taskInfo.warnTime !== '') {
          taskInfo.warnTime = moment(taskInfo.warnTime).format('YYYY-MM-DD HH:mm:ss');
        }
        let pic = new Object();
        let config = new Array();
        pic.start = form.shotMinNumber;
        pic.end = form.shotMaxNumber;
        if (form.isPicture === true) {
          pic.isMust = '是';
        } else {
          pic.isMust = '否';
        }
        // pic.isMust = form.isPicture;
        config.push(pic);
        let requestBody = new Object();
        requestBody.taskInfo = taskInfo;
        requestBody.taskInfo.config = config;
        // JSON.stringify(config);
        saveTaskAction(requestBody).then(

          data => {
            if (data === null) {
              AmosAlert.success('提示', '保存成功');
            } else {
              if (data.result === "FAILURE") {
                AmosAlert.error('提示', data.message);

              } else {
                AmosAlert.success('提示', '保存成功');
              }
            }

            browserHistory.goBack('/main/patrol/task');
          },
          err => {
            AmosAlert.error('错误', err);
          }
        );
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  };

  handleCancel = e => {
    browserHistory.goBack('/main/patrol/task');
  };

  render() {
    const { form, rules, executors, tableData } = 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 }
      }
    };
    const tableLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 12, offset: 2 }
      }
    };
    const def = true;
    return (
      <div className="input_item_div">
        <Form model={form} rules={rules} ref={component => this.form = component}>
          <FormItem label={<span>任务标题</span>} field="title" {...formItemLayout}>
            <Input className="input_item_Input" value={form.title} maxLength="50" placeholder="请输入任务标题" onChange={e => this.onChange('title', e.target.value)} />
          </FormItem>
          <FormItem label={<span>说明</span>} field="remark" {...formItemLayout}>
            <TextArea className="input_item_Input" rows={6} disableResize onChange={e => this.onChange('remark', e.target.value)} />
          </FormItem>
          <FormItem label={<span>执行人</span>} field="executor" {...formItemLayout}>

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


            <TreeSelect
              showSearch
              treeData={executors}
              className="input_item_select"
              dropdownStyle={{ height: 150, overflow: 'auto' }}
              onSelect={this.handleExecutorsChange}
              treeIcon={def}
              value={form.executor}
              treeLine={def}
              showCheckedStrategy={TreeSelect.SHOW_CHILD}
              placeholder="执行人选择"
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              treeDefaultExpandAll
            />
          </FormItem>
          <FormItem label={<span>要求完成时间</span>} field="finishTime" {...formItemLayout}>
            <DatePicker
              format="YYYY-MM-DD HH:mm:ss"
              className="input_item_select"
              onChange={(value) => { this.onChange('finishTime', value); }}
              showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
            />
          </FormItem>
          <FormItem label={<span>任务最大转发次数</span>} field="maxDepth" {...formItemLayout}>
            <InputNumber value={form.maxDepth} className="input_item_Input" placeholder="默认输入值" onChange={e => this.onChange('maxDepth', e)} />
          </FormItem>
          <FormItem label={<span>是否需要提醒</span>} field="isWarn" {...formItemLayout}>
            <Checkbox checked={form.isWarn} onChange={e => this.onChange('isWarn', e.target.checked)} />
          </FormItem>
          <FormItem label={<span>提醒时间</span>} field="warnTime" {...formItemLayout}>
            <DatePicker
              className="input_item_select"
              format="YYYY-MM-DD HH:mm:ss"
              onChange={value => {
                this.onChange('warnTime', value);
              }}
              showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
            />
          </FormItem>
          <FormItem label={<span>是否需要拍照</span>} field="isPicture" {...formItemLayout}>
            <Checkbox checked={form.isPicture} onChange={e => this.onChange('isPicture', e.target.checked)} />
          </FormItem>
          <FormItem label={<span>最少拍照数量</span>} field="shotMinNumber" {...formItemLayout}>
            <InputNumber
              min={1}
              value={form.shotMinNumber}
              className="point-info-input"
              placeholder="1"
              onChange={e => this.onInputNumberChange('shotMinNumber', e)}
            />
          </FormItem>
          <FormItem label={<span>最多拍照数量</span>} field="shotMaxNumber" {...formItemLayout}>
            <InputNumber
              min={5}
              value={form.shotMaxNumber}
              className="point-info-input"
              placeholder="5"
              onChange={e => this.onInputNumberChange('shotMaxNumber', e)}
            />
          </FormItem>
          <FormItem {...wrapperCol}>
            <HasPermission permissionCode="task">
              <Button onClick={this.handleSubmit}>提交</Button>
            </HasPermission>
            <Button onClick={this.handleCancel}>返回</Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}

NewTask.propTypes = {};

export default NewTask;
