import React, { Component } from "react";
import { connect } from "dva";
import moment from "moment";
import {
  Form,
  Input,
  Checkbox,
  Button,
  Row,
  Steps,
  DatePicker,
  Tag,
  message,
  notification,
  Col
} from "antd";
import {
  taskSaveStepOneDetail,
  taskGetStepOneDetail,
} from "../../../services/api";
// import "../Task.less";
import {formItemLayout1,minSubmitFormLayout} from '../../../constants/formItemLayout';
import $perModal from '../../../utils/modal/perModal';
const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const dateFormat = "YYYY-MM-DD";
@connect(state => ({
  profile: state.profile
}))

@Form.create()
export default class CreateTaskInformation extends Component {
  state = {
    taskStatus: '', //驻勤状态
    chargePerId: '',//选中的负责人的id
    comTaskId: this.props.dataSource.comTaskId || this.props.comTaskId || "",
    param: {
      chargePerName: '',//负责人名称
      taskName: "",
      taskLevel: "",
      serviceType: [],
      taskNature: "",
      urgentLevel: "",
      taskStatus: null,
      startDate: moment().format('YYYY-MM-DD') + " 00:00:00",
      endDate: moment().format('YYYY-MM-DD') + " 00:00:00",
    },
    startDate: moment().format('YYYY-MM-DD'),
    endDate: moment().format('YYYY-MM-DD'),
  };

  componentWillMount() {
    // this.taskGetTaskById();
  }
  componentWillReceiveProps(nextProps) {
    if (this.state.comTaskId !== nextProps.dataSource.comTaskId) {
      this.setState({
        comTaskId: nextProps.dataSource.comTaskId
      }, () => {
        if (this.state.comTaskId) {
          this.taskGetTaskById()
        } else {
          this._reset()
        }
      })
    }
  }

  componentDidMount() {
    if (this.state.comTaskId) {
      this.taskGetTaskById()
    }
  }
  _reset() {
    this.props.form.resetFields();
    this.setState({
      param: {
        chargePerName: '',//负责人名称
        taskName: "",
        taskLevel: "",
        serviceType: [],
        taskNature: "",
        urgentLevel: "",
        taskStatus: null,
        startDate: moment().format('YYYY-MM-DD') + " 00:00:00",
        endDate: moment().format('YYYY-MM-DD') + " 00:00:00",
      }
    })
  }
  /* 基础信息 */
  taskGetTaskById = () => {

    let comTaskId = this.state.comTaskId;
    if (comTaskId == '') {
      return;
    }
    // 获取页面详情
    taskGetStepOneDetail({ comTaskId }).then(
      data => {
        // data.data.serviceType = data.data.serviceType.split(',');
        const param = { ...this.state.param };
        for (const key in data.data) {
          if (data.data.hasOwnProperty(key) === true) {
            param[key] = data.data[key];
          }
        }
        this.setState({
          param, taskStatus: data.data.taskStatus,
          startDate: param.startDate,
          endDate: param.endDate,
          chargePerId: data.data.chargePerId,
          taskContent: data.data.taskContent
        })
      },
      err => {
        console.log(err, "taskGetStepOneDetail-err");
      }
    );
  };
  handleSubmit = e => {
    e.preventDefault();

    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (this.state.comTaskId != '') {
          values.comTaskId = this.state.comTaskId;
        }
        values.chargePerId = this.state.chargePerId
        // values.taskNature = '1';
        // values.urgentLevel = '1';
        // values.serviceType = '1010009';
        // values.taskLevel = '1';

        // 时间处理
        if (values.startDate.valueOf() >= values.endDate.valueOf()) {
          return message.error("结束时间不能小于开始时间");
        }
        values.startDate = values.startDate.format(dateFormat);
        values.endDate = values.endDate.format(dateFormat);
        this.taskManagementAddTaskStepOne(values);
      }
    });
  };
  //创建驻勤第一个步骤
  taskManagementAddTaskStepOne = (postdata) => {
    taskSaveStepOneDetail(postdata).then(
      data => {
        this.props.updateTable && this.props.updateTable();
        const comTaskId = this.state.comTaskId === '' ? data.data : this.state.comTaskId;
        if (this.props.onClose) {
          notification.success({
            // message: data.msg
            message: '保存成功'
          });
          this.props.form.resetFields();
          this.props.onClose();
        } else {
          this.props.switchStep && this.props.switchStep(1, comTaskId, this.state.taskStatus);
        }
      },
      err => {
        console.log(err, "taskSaveStepOneDetail-err");
      }
    );
  };



  //返回上一个页面
  returnLastPage = () => {
    this.props.history.push('/taskmanager/tasklist')
  }

  render() {
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { startDate, endDate } = this.state.param;
    return (
      <div className="CreateTask">
        {
          // 改成弹窗以后只显示基础信息 通过onClose字段判断是否展示步骤
          !this.props.onClose &&
          <div className="Steps">
            <Steps current={0}>
              <Step title="基本信息" />
              <Step title="出勤设置" />
              <Step title="发布设置" />
            </Steps>
          </div>
        }

        <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
          <FormItem {...formItemLayout1} label="考勤组名称">
            {getFieldDecorator("taskName", {
              initialValue: this.state.param.taskName,
              rules: [
                {
                  pattern: /^.{1,50}$/,
                  required: true,
                  message: "请输入少于50个字"
                }
              ]
            })(<Input placeholder="请输入" />)}
          </FormItem>
          <FormItem {...formItemLayout1} label="负责人">
            {getFieldDecorator("chargePerName", {
              initialValue: this.state.param.chargePerName,
              rules: [{ required: true, message: "请选择负责人" }]
            })(
              <Input placeholder="请输入" onClick={
                () => {
                  console.log(this.state.chargePerId)
                  $perModal({
                    value: this.state.chargePerId + '',
                    type: 'radio',
                    fetchType: 'task',
                    onOk: (values, close) => {
                      close();
                      if (values[0]) {
                        this.props.form.setFieldsValue({ chargePerName: values[0].name });
                        this.setState({
                          chargePerId: values[0].perId
                        });
                      }
                    }
                  });
                }
              } />
            )}
          </FormItem>
          <FormItem {...formItemLayout1} label="生效日期" extra={this.state.comTaskId ? <span style={{ color: 'orange' }}>若设为永久生效，终止日期将以9999-12-31进行录入。</span> : ''}>
            <Row>
              <Col span={12}>{getFieldDecorator("startDate", {
                initialValue: moment(startDate, dateFormat),
                rules: [{ required: true, message: "请选择开始日期" }]
              })(
                <DatePicker
                  // disabled={ifEdit}
                  placeholder="开始日期"
                  style={{ width: "100%" }}
                  format={dateFormat}
                  disabledDate={current => {
                    if (this.state.comTaskId) {
                      return current && current > moment(startDate).startOf('day');
                    }
                    return false;
                  }}
                />
              )}
              </Col>
              <Col span={12} style={{ textAlign: 'right' }}>
                <Checkbox
                  checked={moment(this.props.form.getFieldValue('endDate')).format('YYYY-MM-DD').indexOf('9999') > -1}
                  onChange={(e) => {
                    if (e.target.checked) {
                      this.props.form.setFieldsValue({ endDate: moment('9999/12/31', dateFormat) });
                    } else {
                      this.props.form.setFieldsValue({ endDate: moment(endDate, dateFormat) });
                    }
                  }}>设为永久生效</Checkbox>
              </Col>
            </Row>
          </FormItem>
          <FormItem {...formItemLayout1} label="终止日期" >
            {getFieldDecorator("endDate", {
              initialValue: moment(endDate, dateFormat),
              rules: [{ required: true, message: "请选择结束日期" }]
            })(
              <DatePicker
                disabled={moment(this.props.form.getFieldValue('endDate')).format('YYYY-MM-DD').indexOf('9999') > -1}
                placeholder="结束日期"
                style={{ width: "100%" }}
                format={dateFormat}
                disabledDate={current => {
                  // return (current && current < moment(endDate, dateFormat));
                }}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout1} label="说明">
            {getFieldDecorator("taskContent", {
              initialValue: this.state.param.taskContent,
              // rules: [{ required: true, message: "请选择" }]
            })(
              <TextArea placeholder="请输入备注" />
            )}
          </FormItem>
          {/* {
            !this.props.onClose &&
            <FormItem {...minSubmitFormLayout} style={{ marginTop: 32 }}>
              <Button loading={submitting} onClick={this.returnLastPage}>取消</Button>
              <Button type="primary" style={{ marginLeft: 8 }} htmlType="submit">下一步</Button>
            </FormItem>
          }
          {
            this.props.onClose && */}
          <FormItem {...minSubmitFormLayout} style={{ marginTop: 32 }}>
            <Button type="primary" htmlType="submit" disabled={this.state.taskStatus == 4 || this.state.taskStatus == 7 || this.state.taskStatus == 2}>保存</Button>
            <Button loading={submitting} style={{ marginLeft: 8 }} onClick={this.props.onClose}>取消</Button>
          </FormItem>
          {/* } */}
        </Form>

      </div>
    );
  }
}
