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

import { dispatch } from '../../../../model';
import { showMessage, showNotifaction } from '../../../../util';

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

  const [form] = Form.useForm();
  const [waiting, setWaiting] = useState(false);

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

  const save = async () => {
    try {
      const rows = await form.validateFields();
      setWaiting(true);
      dispatch({
        type: 'datamodel.startFlow',
        payload: {
          data: {
            modelInfoList: items,
            sendReviewExplain: rows.desc,
          }
        },
        callback: data => { 
          if (data?.allSuccess) {
            showMessage('success', '送审成功')
          } else if (data?.alertMsg) {
            showNotifaction('送审提示', data?.alertMsg, 5);
          }
           
          LocalStorage.set('modelChange', !(LocalStorage.get('modelChange')||false));
          let event = new Event('storage');
          event.key = 'modelChange';
          window?.dispatchEvent(event);
          
          close(true)
        },
        error: () => {
          setWaiting(false);
        }
      })

    } catch (errInfo) {

    }
  }

  const close = (val) => {
    setWaiting(false);
    form.resetFields();
    onCancel?.(val)
  }

  const footer = React.useMemo(() => {
    return [
      <Button key={'cancel'}
        onClick={() => close()}
      >取消</Button>,
      <Button key={'save'} type='primary'
        disabled={waiting}
        onClick={() => save()}
      >保存</Button>
    ]
  }, [close, save, waiting])

  return (
    <Modal 
      destroyOnClose
      visible={visible}
      title='模型送审'
      width={520}
      footer={footer}
      onCancel={() => { close() }}
    >
      <Spin spinning={waiting}>
        <Form {...formItemLayout} form={form}>
          <Form.Item 
            label="送审简述" 
            name="desc" 
            rules={[{ required: true, message: '请填写送审简述' }]}
          >
            <Input.TextArea rows={6} />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
}

export default StartFlowModal;