import React, { useEffect, useState } from 'react';
import { Button, Form, Input, Modal, Upload, Select, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { getSecondBusinessId } from '../service';

interface CreateDocumentProps {
  //新增文档标题参数
  title: string;
  //控制弹出参数
  modalVisible: boolean;
  //返回参数
  onCancel: () => void;
  //成功回参
  onOk: (value: any) => any;
  //存档目录数据传入
  archiveData?: any;
  //修改行数据传入
  values: any
}

const layout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 12 },
};

const validateMessages = {
  required: '请填写${label}',
};

const CreateDocument: React.FC<CreateDocumentProps> = (props) => {
  const { modalVisible, onCancel, title,archiveData ,onOk , values} = props;
  //上传文件id存储
  const [uploadId, setUploadId] = useState<any>();
  //上传文件列表
  const [fileListData, setFileListData] = useState<any[]>([]);
  const { Option } = Select;
  const { TextArea } = Input;
  const [form] = Form.useForm();

  useEffect(() => {
    if(values == null || values == undefined) {
      setFileListData([])
        form.setFieldsValue({
          archiveFileType:'',
          archiveId:null,
          archiveExplain:'',
          archiveRoundsId:'',
          id:''
        })
    } else {
      if(values.ossFileList == null) {
        setFileListData([])
      } else {
        let value: { name: string; businessId: string; url: string; uid: string; }[] = []
        let data = values.ossFileList
        data.forEach((ele: any) => {
          let obj = {
            name: "",
            businessId: "",
            url:"",
            uid:""
          }
          obj.name = ele.filename
          obj.businessId = ele.bid
          obj.url = `http://125.32.114.204:8760/api/core-service-ebtp-updownload/v1/attachment/download/oid/${ele.id}`
          obj.uid = ele.id
          value.push(obj)
        });
        setFileListData([...value])
      }

      form.setFieldsValue({
        archiveFileType:values.archiveFileType,
        archiveId:values.archiveId,
        archiveExplain:values.archiveExplain,
        archiveRoundsId:values.archiveRoundsId,
        id:values.id
      })
    }
  }, [values,modalVisible])

  const onFinish = async (values: any) => {
    let data = values
    data.businessFileId = fileListData[0].businessId
    const success = await onOk(data)
    if(success) {
      setFileListData([])
    }

  };
  const onSubmit = () => {
    if(fileListData.length == 0) {
      message.info("请选择文档")
    } else {
      form.submit()
    }
  }


  //上传文件业务id获取
  const getUploadBusinessId = async () => {
      await getSecondBusinessId().then((res) => {
        setUploadId(res.id);
      });
  };

  //上传文件数量控制
  const handleChange = (info: { fileList: any }) => {
    let fileList = [...info.fileList];
    let count = 0
    // 1. 限制上传文件的数量
    // 只显示最近上传的一个文件，旧的会被新的替换
    fileList = fileList.slice(-1);
    // 2.从response中读取并显示文件链接
    fileList = fileList.map((file) => {
      if (file.response) {
        // 组件将显示文件和url链接
        message.success("上传成功")
        count = 1
        file.url = `http://125.32.114.204:8760/api/core-service-ebtp-updownload/v1/attachment/download/oid/${file.response.oid}`;
        file.oid = file.response.oid;
        file.businessId = uploadId
      }
      return file;
    });
    if(count == 1) {
      setFileListData(fileList);
    }
  };
  //上传文件大小控制
  const beforeUpload = (file: any) => {
    //文件大小字节数自己算的
    if(file.size > 52428800) {
      message.info("上传文件大于50M，请重新上传")
      return false
    }
    return true
  }
  //上传文件参数配置
  const uploadProps = {
    action: '/api/core-service-ebtp-updownload/v1/attachment/upload',
    onChange: handleChange,
    beforeUpload: beforeUpload,
    data: {
      businessId: uploadId,
    },
  };

  return (
    <Modal
      destroyOnClose
      title={title}
      visible={modalVisible}
      onCancel={() => {
        setFileListData([])
        onCancel()
      }}
      onOk={() => onSubmit()}
      okText="保存"
      cancelText="取消"
      width={800}
    >
      <Form
        {...layout}
        form={form}
        name="nest-messages"
        onFinish={onFinish}
        validateMessages={validateMessages}
        preserve={false}
      >
        <span
          style={{
            float: 'right',
            marginRight: 221,
            marginTop: -22,
            position: 'relative',
            top: 25,
            color: '#808080',
          }}
        >
          最多上传一个文件，每个最大50MB
        </span>
        <Form.Item label="选择文档">
          <Upload {...uploadProps} fileList={fileListData}>
            <Button type="primary" onClick={() => getUploadBusinessId()}>
              <UploadOutlined />
              上传
            </Button>
          </Upload>
        </Form.Item>
        <Form.Item name="archiveFileType" label="文档类型" rules={[{ required: true }]}>
          <Input placeholder="请填写文档类型" />
        </Form.Item>
        <Form.Item name="archiveId" label="存档目录" rules={[{ required: true }]}>
          <Select style={{ width: 200 }} placeholder="请选择" optionFilterProp="children">
            {archiveData.map((ele: any) => (<Option value={ele.archiveLinkId} key={ele.archiveLinkId}>{ele.archiveLinkName}</Option>))}
          </Select>
        </Form.Item>
        <Form.Item name="archiveExplain" label="文档说明" rules={[{ required: true }]}>
          <TextArea rows={6} maxLength={2000} placeholder="请填写文档说明" />
        </Form.Item>
        <Form.Item name="archiveRoundsId" label="archiveRoundsId" hidden>
          <Input />
        </Form.Item>
        <Form.Item name="id" label="id" hidden>
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CreateDocument;
