import React, { useState } from 'react'
import { Modal, Form, Input, Spin, Button } from 'antd'

import { dispatch } from '../../../model'
import { showMessage } from '../../../util'

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

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

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 14 },
    },
  };

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

  const save = async () => {
    try {
      const values = await form.validateFields()
      setWaiting(true)

      dispatch({
        type: 'assetmanage.startProcess',
        payload: {
          params: {
            ...values,
          },
          data: (items??[]).map(item => item.id)
        },
        callback: () => {
          showMessage('success', '申请成功!')
          close(true)
        },
        error: () => {
          setWaiting(false)
        }
      })

    } catch (errInfo) {

    }
  }

  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}
      bodyStyle={{ overflowX: 'auto', maxHeight: '80vh' }}
      footer={footer}
      onCancel={() => { close() }}
    >
      <Spin spinning={waiting}>
        <Form 
          labelAlign='left'
          {...formItemLayout}
          form={form}
        >
          <Form.Item 
            label='申请原因' 
            name='reason' 
            rules={[{ required: true, message: '请填写申请原因' }]}
          >
            <Input.TextArea placeholder='请在申请原因栏中描述用途说明以及必要性' rows={4} />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
}

export default FC