import React from 'react'
import {
  Modal,
  Form,
  Radio,
  Button,
  Input,
  Switch,
  Select,
  DatePicker,
  InputNumber
} from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import { IClassification, ISchedule } from '../types'
import {
  ICronExpressionPartition,
  SchedulePeriodUnit
} from 'containers/Schedule/components/types'

const FormItem = Form.Item

interface IScheduleFormModalProps extends FormComponentProps<ISchedule> {
  visible: boolean
  loading: boolean
  formView: ISchedule
  onSave: (view: ISchedule) => void
  onCancel: () => void
}

const getCronExpressionByPartition = (partition: {
  periodUnit: string
  interval: number
}) => {
  const { periodUnit, interval } = partition
  let cronExpression = ''
  switch (periodUnit as SchedulePeriodUnit) {
    case 'Minute':
      cronExpression = `0 0/${interval} * * * *`
      break
    case 'Hour':
      cronExpression = `0 0 0/${interval} * * *`
      break
    case 'Day':
      cronExpression = `0 0 0 1/${interval} * *`
      break
    case 'Week':
      cronExpression = `0 0 0 ? * ${interval}`
      break
    case 'Month':
      cronExpression = `0 0 0 ? 1/${interval} *`
      break
    case 'Year':
      cronExpression = `* * * * * * 0/${interval}`
      break
  }
  return cronExpression
}

class ScheduleFormModal extends React.PureComponent<IScheduleFormModalProps> {
  // @ts-ignore
  private formItemStyle = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 }
  }

  private save = () => {
    const { form, formView, onSave } = this.props
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (err) {
        return
      }
      const copyView: ISchedule = { ...fieldsValue }
      onSave({
        ...fieldsValue,
        cronExpression: getCronExpressionByPartition({
          periodUnit: fieldsValue.periodUnit,
          interval: fieldsValue.interval
        })
      })
    })
  }

  private clearFieldsValue = () => {
    this.props.form.resetFields()
  }

  public render() {
    const { form, visible, loading, formView, onCancel } = this.props
    const { getFieldDecorator } = form

    const modalButtons = [
      <Button key={'back'} size={'large'} onClick={onCancel}>
        取 消
      </Button>,
      <Button
        disabled={loading}
        key={'submit'}
        size={'large'}
        type={'primary'}
        onClick={this.save}
      >
        保 存
      </Button>
    ]

    return (
      <Modal
        title={'调度器'}
        visible={visible}
        footer={modalButtons}
        onCancel={onCancel}
        afterClose={this.clearFieldsValue}
        destroyOnClose
        // width={800}
      >
        <Form>
          <FormItem label={'调度周期'} {...this.formItemStyle} required>
            {getFieldDecorator<ISchedule>('periodUnit', {
              initialValue: formView?.periodUnit,
              rules: [
                {
                  required: true,
                  message: '请输入'
                }
              ]
            })(
              <Radio.Group>
                <Radio value={'Minute'}>分钟</Radio>
                <Radio value={'Hour'}>小时</Radio>
                <Radio value={'Day'}>日</Radio>
                <Radio value={'Week'}>周</Radio>
                <Radio value={'Month'}>月</Radio>
                <Radio value={'Year'}>年</Radio>
              </Radio.Group>
            )}
          </FormItem>
          <FormItem label={'调度间隔'} {...this.formItemStyle} required>
            {getFieldDecorator<ISchedule>('interval', {
              initialValue: formView?.interval,
              rules: [{ required: true, message: '请输入' }]
            })(<InputNumber />)}
          </FormItem>

          <FormItem label={'起止日期'} {...this.formItemStyle} required>
            {getFieldDecorator<ISchedule>('startDate', {
              initialValue: [formView?.startDate, formView.endDate],
              rules: [
                {
                  required: true,
                  message: '请输入'
                }
              ]
            })(
              <DatePicker.RangePicker
                style={{ width: '100%' }}
                format={'YYYY-MM-DD hh:mm:ss'}
              />
            )}
          </FormItem>

          <FormItem label={'是否激活'} {...this.formItemStyle} required>
            {getFieldDecorator<ISchedule>('jobStatus', {
              initialValue: formView?.jobStatus === 'started',
              rules: [
                {
                  required: true,
                  message: '请选择'
                }
              ]
            })(<Switch checkedChildren="开" unCheckedChildren="关" />)}
          </FormItem>
        </Form>
        <p>
          提示：您希望每 {this.props.form.getFieldValue('interval')}{' '}
          {TIME_KEY_VALUE?.[this.props.form.getFieldValue('periodUnit')]}{' '}
          执行一次该任务， 从{' '}
          {this.props.form
            .getFieldValue('startDate')?.[0]
            ?.format('YYYY-MM-DD hh:mm:ss')}{' '}
          时间开始到
          {this.props.form
            .getFieldValue('startDate')?.[1]
            ?.format('YYYY-MM-DD hh:mm:ss')}{' '}
          时间停止周期调度， 并且当前任务状态{' '}
          {this.props.form.getFieldValue('jobStatus') ? '开启' : '关闭'}
        </p>
      </Modal>
    )
  }
}

const TIME_KEY_VALUE = {
  Minute: '分钟',
  Hour: '小时',
  Day: '日',
  Week: '周',
  Month: '月',
  Year: '年'
}

export default Form.create<IScheduleFormModalProps>()(ScheduleFormModal)
