import React, { useEffect, useState } from 'react'
import {
  Modal,
  Form,
  Radio,
  Button,
  Switch,
  message,
  DatePicker,
  InputNumber,
  Spin
} from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import { IQualityTask, ISchedule } from '../types'
import { SchedulePeriodUnit } from 'containers/Schedule/components/types'
import request from 'app/utils/request'
import api from 'app/utils/api'
import moment from 'moment'

const FormItem = Form.Item

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

interface State {
  view: IQualityTask
}

const getIntervalFromCronExpression = (cronExpression = '') => {
  const regs = [
    new RegExp(/0 \*\/(\S*) \* \* \* \?/), // Minute `0 */12 * * * ?`.match(/0 \*\/(\S*) \* \* \* \?/)[1]
    new RegExp(/0 0 0\/(\S*) \* \* \?/), // Hour `0 0 0/12 * * ?`.match(/0 0 0\/(\S*) \* \* \?/)[1]
    new RegExp(/0 0 0 1\/(\S*) \* \?/), // Day `0 0 0 1/12 * ?`.match(/0 0 0 1\/(\S*) \* \?/)[1]
    new RegExp(/0 0 0 \? \* (\S*)/), // Week `0 0 0 ? * 12`.match(/0 0 0 \? \* (\S*)/)[1]
    new RegExp(/0 0 0 1 1\/(\S*) \? \*/), // Month `0 0 0 1 1/12 ? *`.match(/0 0 0 1 1\/(\S*) \? \*/)[1]
    new RegExp(/0 0 0 1 1 \? 1\/(\S*)/) // Year `0 0 0 1 1 ? 1/12`.match(/0 0 0 1 1 \? 1\/(\S*)/)[1]
  ]

  return regs
    .map((o) => cronExpression?.match(o)?.[1])
    .filter((o) => o)
    .join()
}

const getCronExpressionByPartition = (partition: {
  periodUnit: SchedulePeriodUnit
  interval: number
}) => {
  const { periodUnit, interval } = partition
  let cronExpression = ''
  switch (periodUnit) {
    case 'Minute':
      cronExpression = `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 1/${interval} ? *`
      break
    case 'Year':
      cronExpression = `0 0 0 1 1 ? 1/${interval}`
      break
  }
  return cronExpression
}

const formItemStyle = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 }
}

const ScheduleFormModal = (props: IScheduleFormModalProps) => {
  const { loading, onCancel, form, formView, onSave, visible } = props
  const { getFieldDecorator } = form

  const [view, setView] = useState<ISchedule>({})

  const [viewLoading, setViewLoading] = useState(false)

  const clearFieldsValue = () => {
    form.resetFields()
  }

  const handleSave = () => {
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (err) {
        return
      }
      const copyView: ISchedule = { ...fieldsValue }
      onSave({
        ...fieldsValue,
        cronExpression: getCronExpressionByPartition({
          periodUnit: fieldsValue.periodUnit,
          interval: fieldsValue.interval
        })
      })
    })
  }

  const getDispatchInfo = async() => {
    try {
      setViewLoading(true)

      const result = await request({
        url: api.getDispatch + formView?.id,
        method: 'get',
        headers: {
          ContentType: 'application/json'
        },
        data: {
          id: formView?.id
        }
      })

      // @ts-ignore
      if (result?.header?.code === 200) {
        setView({
          // @ts-ignore
          ...(result?.payload ?? {}),
          interval: getIntervalFromCronExpression(
            // @ts-ignore
            result?.payload?.cronExpression ?? ''
          )
        })
      }
    } catch (err) {
      if (err?.response?.data?.header?.msg) {
        message.error({ content: err?.response?.data?.header?.msg })
      }
      console.log(err)
    } finally {
      setViewLoading(false)
    }
  }

  useEffect(() => {
    if (visible) {
      getDispatchInfo()
    }
  }, [formView?.id, visible])

  const modalButtons = [
    <Button key="back" size="large" onClick={onCancel}>
      取 消
    </Button>,
    <Button
      disabled={loading}
      key="submit"
      size="large"
      type="primary"
      onClick={handleSave}
    >
      保 存
    </Button>
  ]
  return (
    <Modal
      title="调度器"
      visible={visible}
      footer={modalButtons}
      onCancel={onCancel}
      afterClose={clearFieldsValue}
      destroyOnClose
      // width={800}
    >
      <Spin spinning={viewLoading}>
        <Form>
          <FormItem label="调度周期" {...formItemStyle} required>
            {getFieldDecorator<ISchedule>('periodUnit', {
              initialValue: view?.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="调度间隔" {...formItemStyle} required>
            {getFieldDecorator<ISchedule>('interval', {
              initialValue: view?.interval,
              rules: [{ required: true, message: '请输入' }]
            })(<InputNumber />)}
          </FormItem>

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

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

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

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