import React, { useState, useEffect, useRef, forwardRef } from 'react'
import styled from 'styled-components'
import {
  Form,
  Select,
  Input,
  Radio,
  Space,
  message,
  Divider,
  Button,
} from 'antd'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons'
import { getTagList, deleteTag } from '../services'
import CronSelect from '../../../component/CronSelect'

const FormWrapper = styled.div`
  .singletask_form {
    margin-top: 20px;
  }
  .form_executionCycle {
    margin-left: 10px;
  }
`

const FormItem = Form.Item

const { Option } = Select

const RadioGroup = Radio.Group

const layout = {
  labelCol: {
    span: 2,
  },
  wrapperCol: {
    span: 10,
  },
}

const TaskForm = ({ taskForm, taskType, taskInfo, jmWorkList }, ref) => {
  const [radioValue, setRadioValue] = useState(null)
  const [tagOptions, setTagOptions] = useState([])
  const [jmWorkOptions, setJmWorkOptions] = useState([])
  const [tag, setTag] = useState(null)
  const [cronData, setCronData] = useState(null)
  const inputRef = useRef(null)

  const onNameChange = event => {
    setTag(event.target.value)
  }

  const addTagItem = e => {
    if (tag) {
      e.preventDefault()
      if (!tagOptions.find(item => item === tag)) {
        setTagOptions([...tagOptions, tag])
        taskForm.setFieldValue('taskTag', tag)
        setTag(null)
        setTimeout(() => {
          inputRef.current?.focus()
        }, 0)
      } else {
        message.error('存在同名标签')
      }
    } else {
      message.error('请输入自定义作业标签名称')
    }
  }

  const onDeleteTag = async val => {
    const { data } = await deleteTag({ type: '任务标签', val })
    if (data.code === 200) {
      taskForm.setFieldValue('taskTag', null)
      message.success('删除成功')
      fetchTagList()
    } else {
      message.error(data.msg)
    }
  }

  const onRadioChange = e => {
    setRadioValue(e.target.value)
  }

  const fetchTagList = async () => {
    const { data } = await getTagList('任务标签')
    if (data.code === 200) {
      setTagOptions(data.data)
    } else {
      message.error(data.msg)
    }
  }

  const handleInitTask = taskInfo => {
    setRadioValue(taskInfo.cron_type)
    if (taskInfo.cron_type === 2) {
      setCronData(taskInfo.cron_expression_dict)
    }
    taskForm.setFieldsValue({
      taskName: taskInfo.name,
      taskTag: taskInfo.tag,
      job: taskInfo.nodes[0].homework_id,
      executionCycle: taskInfo.cron_type,
    })
  }

  //初始化tag列表
  useEffect(() => {
    fetchTagList()
  }, [])

  //初始化作业列表
  useEffect(() => {
    setJmWorkOptions(jmWorkList)
  }, [jmWorkList])

  useEffect(() => {
    if (taskInfo !== null) handleInitTask(taskInfo)
  }, [taskInfo])

  return (
    <FormWrapper>
      <Form {...layout} form={taskForm} className="singletask_form">
        <FormItem
          name="taskName"
          label="任务名称"
          rules={[{ required: true, message: '请输入任务名称!' }]}>
          <Input />
        </FormItem>
        <FormItem
          name="taskTag"
          label="任务标签"
          rules={[{ required: true, message: '请选择任务标签!' }]}>
          <Select
            placeholder="选择任务标签"
            allowClear
            optionLabelProp="label"
            dropdownRender={menu => (
              <>
                {menu}
                <Divider
                  style={{
                    margin: '8px 0',
                  }}
                />
                <Space
                  style={{
                    padding: '0 8px 4px',
                  }}>
                  <Input
                    placeholder="请输入"
                    ref={inputRef}
                    value={tag}
                    onChange={onNameChange}
                  />
                  <Button
                    type="text"
                    icon={<PlusOutlined />}
                    onClick={addTagItem}>
                    添加新分类
                  </Button>
                </Space>
              </>
            )}>
            {tagOptions.map(item => (
              <Option key={item}>
                <Space>
                  <DeleteOutlined onClick={() => onDeleteTag(item)} />
                  <span>{item}</span>
                </Space>
              </Option>
            ))}
          </Select>
        </FormItem>
        {taskType !== 'multitasking' && (
          <FormItem
            name="job"
            label="选择作业"
            rules={[{ required: true, message: '请选择作业!' }]}>
            <Select placeholder="选择作业" allowClear>
              {jmWorkOptions.map(item => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </FormItem>
        )}
        <FormItem
          name="executionCycle"
          label="设置执行周期"
          rules={[{ required: true, message: '请设置执行周期!' }]}>
          <RadioGroup onChange={onRadioChange}>
            <Space direction="vertical">
              <Radio value={1}>只执行一次，下次手动执行</Radio>
              <Radio value={2}>
                执行周期
                {radioValue === 2 ? (
                  <Space className="form_executionCycle">
                    <CronSelect cron_data={cronData} ref={ref} />
                  </Space>
                ) : null}
              </Radio>
            </Space>
          </RadioGroup>
        </FormItem>
      </Form>
    </FormWrapper>
  )
}

export default forwardRef(TaskForm)
