import React, { useState } from 'react';
import { Modal, Form, Input } from 'antd';
import LocalStorage from 'local-storage';

import { dispatchLatest } from '../../../../model';
import { showNotifaction } from '../../../../util';

const StartFlowModal = (props) => {
  const { visible, onCancel, ids } = props;

  const [ form ] = Form.useForm();
  const [ confirmLoading, setConfirmLoading ] = useState(false);

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 20 },
    },
  };

  const handleOk = async () => {

    try {
      const values = await form.validateFields();

      setConfirmLoading(true);

      dispatchLatest({
        type: 'user.fetchSessionInfo',
        callback: session => {
          dispatchLatest({
            type: 'datamodel.startFlow',
            payload: {
              params: {
                user: session?.userName,
                modelIds: ids.join(','),
                flowDesc: values?.desc
              }
            },
            callback: data => {
              reset();
              
              if ((data||'') !== '') {
                showNotifaction('送审提示', data, 5);
              }
              
              LocalStorage.set('modelChange', !(LocalStorage.get('modelChange')||false));
              let event = new Event('storage');
              event.key = 'modelChange';
              window?.dispatchEvent(event);
              
              onCancel && onCancel(true);
            },
            error: () => {
              setConfirmLoading(false);
            }
          })
        },
        error: () => {
          setConfirmLoading(false);
        }
      })

    } catch (errInfo) {

    }
  }

  const reset = () => {
    setConfirmLoading(false);
    form.resetFields();
  }

  return (
    <Modal 
      forceRender
      visible={visible}
      title='模型送审'
      width={520}
      confirmLoading={confirmLoading}
      onCancel={() => {
        reset();
        onCancel && onCancel();
      }}
      onOk={handleOk}
    >
    <Form 
      {...formItemLayout}
      form={form}
    >
      <Form.Item 
        label="送审内容" 
        name="desc" 
        rules={[{ required: true, message: '请填写送审内容' }]}
      >
        <Input.TextArea rows={6} />
      </Form.Item>
    </Form>
    </Modal>
  );
}

export default StartFlowModal;