import React, { useState, useEffect, useRef } from 'react'
import { Form, Select, Button, Space, message } from 'antd'
import TaskForm from './TaskForm'
import TaskChartEditor from './TaskChartEditor'
import styled from 'styled-components'
import { useNavigate, useLocation } from 'react-router'
import {
  getJmHomeworkList,
  createJmJob,
  getJmJobInfo,
  updateJmJobInfo,
} from '../services'

const TaskCreater = styled.div`
  margin: 20px;
  background: #fff;
  height: 100%;
  padding: 15px 25px;
  .tasktype_label {
    padding-left: 12px;
    border-left: 3px solid #1881da;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #4a4a4a;
    line-height: 20px;
    letter-spacing: 1px;
  }
  .tasktype_form {
    margin-top: 20px;
  }
  .tasktype_btns {
    margin: 20px 20px 0px;
  }
`

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

const FormItem = Form.Item
const { Option } = Select

const TaskCreaterView = () => {
  // 路由导航
  const navigate = useNavigate()
  const { state } = useLocation()

  const [taskType, setTaskType] = useState(null)
  const [graphRef, setGraphRef] = useState(null)
  const [jmWorkList, setJmWorkList] = useState([])
  const [taskInfo, setTaskInfo] = useState(null)

  const [taskTypeForm] = Form.useForm()
  const [taskForm] = Form.useForm()

  const cronRef = useRef()

  useEffect(() => {
    if (state) {
      fetchJmJobInfo(state.id)
    }
  }, [state])

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

  const fetchJmJobInfo = async id => {
    const { data } = await getJmJobInfo(id)
    if (data.code === 200) {
      const { type } = data.data
      taskTypeForm.setFieldValue('taskType', type)
      setTaskType(type === '单作业离线任务' ? 'singleTask' : 'multitasking')
      setTaskInfo(data.data)
    }
  }

  const onTaskTypeChange = value => {
    setTaskType(value)
  }

  const onGraphRef = ref => {
    setGraphRef(ref)
  }

  const fetchJmWorkList = async () => {
    const { data } = await getJmHomeworkList('test')
    if (data.code === 200) {
      setJmWorkList(data.data)
    } else {
      message.error(data.msg)
    }
  }

  const onSubmit = () => {
    const taskFormData = taskForm.getFieldsValue()
    taskTypeForm
      .validateFields()
      .then(() => {
        taskForm
          .validateFields()
          .then(async () => {
            let nodes = []
            let edges = []
            let type = ''
            if (taskType === 'singleTask') {
              type = '单作业离线任务'
              nodes = [
                {
                  id: 1,
                  homework_id: taskFormData.job,
                  homework_name: jmWorkList.find(
                    item => item.id === taskFormData.job
                  ).name,
                  start_point: 1,
                },
              ]
            } else {
              type = '多作业离线任务'
              const cells = handleNodes()
              nodes = cells.nodes
              edges = cells.edges
            }
            const params = {
              name: taskFormData.taskName,
              type,
              tag: taskFormData.taskTag,
              cron_type: taskFormData.executionCycle,
              user_id: 'test',
              user_name: 'test',
              project_id: 'test',
              nodes,
              edges,
            }
            if (taskType === 'multitasking') {
              params['json_str'] = JSON.stringify(
                graphRef?.state.taskGraph.toJSON()
              )
            }
            const cron_data = cronRef.current?.getCronData
            if (taskFormData.executionCycle === 2) {
              params['cron_expression'] = cron_data
            }

            // 单位非空判断
            if (
              taskFormData.executionCycle === 1 ||
              cron_data?.minute ||
              cron_data?.hour ||
              cron_data?.week ||
              cron_data?.month ||
              cron_data?.cron_expression
            ) {
              let res = {}
              if (state !== null) {
                params['id'] = state.id
                res = await updateJmJobInfo(params)
              } else {
                res = await createJmJob(params)
              }

              if (res.data.code === 200) {
                navigate(-1)
              } else {
                message.error(res.data.msg)
              }
            } else {
              message.error('定时规则数据有误')
            }
          })
          .catch(err => {
            message.error('请检查表单数据是否完整')
          })
      })
      .catch(err => {
        message.error('请检查表单数据是否完整')
      })
  }

  const handleNodes = () => {
    const cells = graphRef?.state.taskGraph.getCells()
    const nodes = []
    const edges = []
    cells.forEach(cell => {
      if (cell.shape === 'task-node') {
        nodes.push({
          id: cell.id,
          homework_id: cell.data.homework_id,
          homework_name: cell.data.label,
          // start_point: cell.data.type === 'work' ? 1 : 0,
        })
      } else {
        edges.push({ source: cell.source.cell, target: cell.target.cell })
      }
    })
    return { nodes, edges }
  }

  return (
    <TaskCreater>
      <div className="tasktype_label">配置任务类型：</div>
      <Form {...layout} form={taskTypeForm} className="tasktype_form">
        <FormItem
          name="taskType"
          label="选择任务类型"
          rules={[{ required: true, message: '请选择任务类型!' }]}>
          <Select
            placeholder="选择任务类型"
            onChange={onTaskTypeChange}
            allowClear>
            <Option value="singleTask">单作业离线任务</Option>
            <Option value="multitasking">多作业离线任务</Option>
          </Select>
        </FormItem>
      </Form>
      <div className="tasktype_label">配置任务信息：</div>
      <TaskForm
        taskForm={taskForm}
        taskType={taskType}
        jmWorkList={jmWorkList}
        taskInfo={taskInfo}
        ref={cronRef}
      />
      {taskType === 'multitasking' && (
        <div className="tasktype_label">作业编排：</div>
      )}
      {taskType === 'multitasking' && (
        <TaskChartEditor
          onRef={onGraphRef}
          jmWorkList={jmWorkList}
          json={taskInfo?.json_str}
        />
      )}
      <Space className="tasktype_btns">
        <Button onClick={() => navigate(-1)}>取消</Button>
        <Button onClick={onSubmit}>提交</Button>
      </Space>
    </TaskCreater>
  )
}

export default TaskCreaterView
