import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, Select, notification, DatePicker, Spin } from 'antd';
import styles from './taskScheduling.less'
// import moment from 'moment';
// import locale from 'antd/es/date-picker/locale/zh_CN';
// import 'moment/locale/zh-cn';

import moment from 'moment'
import locale from 'antd/lib/date-picker/locale/zh_CN'
import 'moment/locale/zh-cn'
moment.locale('zh-cn')
import {
  addTaskOptions, getPredictInfo, getStrategyInfo, updateTaskOptions
} from '@/services/intelligence/api';

const { TextArea } = Input;
const AddModal = props => {
  const { callBackSubmit = () => { }, type, formObj, visible, deviceType } = props;
  const [loading, setLoading] = useState(false);
  const [isloading, setIsLoading] = useState(false);
  const [urlType, setUrlType] = useState('');
  const [scenarioList, setScenarioList] = useState([]);
  const [Intervals, setIntervals] = useState('')
  const [StrategyId, setStrategyId] = useState(0)
  const [form] = Form.useForm();

  const { Item } = Form;
  // 提交
  const onSubmit = () => {
    form.validateFields().then(validate => {
      if (validate) {
        let obj = form.getFieldsValue();
        let apiUrl = type === 'add' ? addTaskOptions : updateTaskOptions
        setLoading(true);
        apiUrl([{
          ...obj, StrategyId
        }]).then(res => {
          setLoading(false);
          if (res.errMsg === '') {
            form.resetFields();
            callBackSubmit();
            prompt('success', `${type === 'add' ? "增加成功" : "编辑成功"}`)
          }
          else {
            prompt('fail', res.errMsg)
          }
        }).catch(err => {
          setLoading(false);
        })
      }
    });
  };
  //提示框
  const prompt = (type, content) => {
    if (type == 'success') {
      notification.success({
        message: '提示',
        duration: 3,
        description: content,
      });
    }
    else {
      notification.error({
        message: '提示',
        duration: 3,
        description: content,
      });
    }
  }


  const onFinish = value => { };
  useEffect(() => {
    switch (type) {
      case 'add':
        setIntervals()
        form.resetFields();
        break;
      case 'edit':
        setUrlType(formObj.TaskType)
        setStrategyId(formObj.AlgorithmId)
        handleTaskType(formObj.TaskType)
        setIntervals(formObj.Interval)
        form.setFieldsValue({ ...formObj, AlgorithmName: formObj.Name });
        break;
      default:
        break;
    }
  }, [visible]);


  //选择任务类型
  const handleTaskType = (value) => {
    switch (value) {
      case '预测':
        setUrlType('predict')
        getPredictInfo().then(res => {
          res.getMe.length && setScenarioList(res.getMe)
        })
        break;
      case '控制':
        setUrlType('control')
        getStrategyInfo().then(res => {
          res.getMe.length && setScenarioList(res.getMe)
        })
        break;
      case 'http':
        setUrlType('url')
        break;
      default:
        setUrlType('predict')
    }

  }
  const inputInterval = (e) => {
    setIntervals(e.target.value)
  }
  const layout = {
    layout: 'horizontal',
    labelCol: {
      span: 5,
    },
    wrapperCol: {
      span: 16,
    },
  };

  const handleChange = (value, option) => {
    setStrategyId(option.id)
  }

  return (

    <Modal
      title={`${type === 'add' ? '任务新增' : '编辑'}`}
      bodyStyle={{ width: '100%', minHeight: '100px' }}
      style={{ top: '150px' }}
      width="700px"
      destroyOnClose
      maskClosable={false}
      cancelText="取消"
      okText="确认"
      {...props}
      onOk={() => onSubmit()}
      confirmLoading={loading}
      forceRender={true}
      getContainer={false}
    >
      <Spin spinning={isloading} delay={300}>
        {visible && (
          <Form form={form} {...layout} onFinish={onFinish}>
            <Item
              label="任务名称"
              name="TaskName"
              rules={[{ required: true, message: '请输入任务名称' }]}
            >
              <Input placeholder="请输入任务名称" allowClear />
            </Item>
            <Item
              label="任务类型"
              name="TaskType"
              rules={[{ required: true, message: '请选择类型' }]}
            >
              <Select onChange={handleTaskType}>
                <Select.Option value='预测'>预测</Select.Option>
                <Select.Option value='控制'>控制</Select.Option>
                <Select.Option value='http'>http</Select.Option>
              </Select>
            </Item>
            {urlType === 'predict' || urlType === 'control' || urlType === '' ? <Item
              label="方案名称"
              name="AlgorithmName"
            >
              <Select onChange={(value, option) => handleChange(value, option)}>
                {scenarioList.length ? scenarioList.map((item, index) => { return <Select.Option key={index} id={item.ID} value={urlType === 'predict' ? item.PredictName : item.StrategyName}>{urlType === 'predict' ? item.PredictName : item.StrategyName}</Select.Option> }) : ''}
              </Select>
            </Item> : <Item
              label="ApiUrl"
              name="ApiUrl"
            >
              <Input placeholder="请输入URL" allowClear />
            </Item>}
            <Item
              label="调度间隔(Cron)"
              name="Interval"
              rules={[{ required: true, message: '请输入间隔' }]}
            >
              <div className={styles.predict}>
                <Input placeholder="请输入间隔" allowClear onChange={(value) => inputInterval(value)} value={Intervals} />
                <a className={styles.corn} target="view_window" href="https://cron.qqe2.com/">cron在线生成</a>
              </div>
            </Item>
            <Item
              label="描述"
              name="Describe"
            >
              <TextArea placeholder="可输入描述信息" rows={4} allowClear />
            </Item>
          </Form>
        )}
      </Spin>

    </Modal>
  );
};
export default AddModal;