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

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

const FC = (props) => {
  const { visible, onCancel, services } = 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: 'pds.authorize',
        payload: {
          params: {
            reason: values?.desc
          },
          data: services
        },
        callback: () => {
          reset();
          
          showMessage('success', '授权成功!');
          onCancel && onCancel(true);
        },
        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 FC;