import React, { useState } from 'react';
import { Form, Input, Slider, Row, Col, Button, Modal, message } from 'antd';
import Panel from '@/pages/Smart/components/Panel';

const ControlParamsForm = ({ form, process, edit, onSave, loading, current, changeProcess }) => {
  const [name, setName] = useState('');
  const [visible, setVisible] = useState(false);
  const control = current?.control || {};
  const { getFieldDecorator, setFieldsValue } = form;

  const params = process.control;

  const renderFormItems = () => {
    return params.map((param, index) => {
      let key = param.name;
      return (
        <Row span={12} key={index}>
          <Form.Item label={key}>
            {getFieldDecorator(key, {
              initialValue: control[key],
            })(
              <Input
                disabled={!edit}
                onChange={e => handleChangeProcess(key, e.target.value)}
                addonAfter={param.unit}
              />
            )}

            {edit &&
              getFieldDecorator(key, {
                initialValue: control[key],
              })(
                <Slider
                  min={0}
                  max={param.max}
                  step={param.max < 1 ? 0.01 : 1}
                  onChange={value => handleChangeProcess(key, value)}
                />
              )}
          </Form.Item>
        </Row>
      );
    });
  };

  const handleChangeProcess = (key, value) => {
    let data = form.getFieldsValue();
    let params = process.control.find(item => item.name == key);
    params.value = value;

    changeProcess({ ...process });
  };

  const onShowModal = () => {
    if (!current?.id) {
      message.error('请先保存基础参数');
      return;
    }
    setVisible(true);
  };

  return (
    <Panel
      title="控制参数"
      btns={
        edit && (
          <Button loading={loading} onClick={onShowModal} type="primary">
            新增
          </Button>
        )
      }
    >
      <Form labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
        <div>{renderFormItems()}</div>
      </Form>
      <Modal
        destroyOnClose
        confirmLoading={loading}
        visible={visible}
        title={`创建目标工况`}
        onCancel={() => {
          setVisible(false);
        }}
        onOk={() => {
          onSave(name);
          setVisible(false);
          setName('');
        }}
      >
        <Form labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
          <Form.Item label="名称">
            <Input
              placeholder="请输入目标工况名称"
              value={name}
              onChange={e => setName(e.target.value)}
            />
          </Form.Item>
        </Form>
      </Modal>
    </Panel>
  );
};

export default Form.create()(ControlParamsForm);
