import React, { useRef, useState, useEffect } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Modal, Button, Tabs, Upload, notification } from 'antd';
import styles from '../style.less';
import { uploadFile, uploadPic } from '../service';
import UploadC from '../../components/upload';

const { Dragger } = Upload;

const { TabPane } = Tabs;
export default props => {
  const { visible, settlementNo } = props;
  const [tabValue, setTabValue] = useState('1');
  const [fileList, setFileList] = useState([]);
  const picUpload = useRef();
  const uploadProps = {
    name: 'file',
    beforeUpload(file) {
      setFileList([file]);
      return false;
    },
    accept: '.xlsx,.xls,.csv',
    showUploadList: true,
    maxCount: 1,
    fileList,
    onRemove() {
      setFileList([]);
    },
  };
  const initPicUpload = () => {
    if (picUpload?.current?.clearFileList) {
      picUpload.current.clearFileList();
    }
  };
  useEffect(() => {
    initPicUpload();
    setFileList([]);
  }, [visible]);
  const uploadPicFn = async () => {
    // 上传图片的接口
    const upLoadFileList = picUpload?.current?.getFileList?.();
    if (!upLoadFileList.length) {
      notification.warning({ message: '请先上传图片' });
      return;
    }
    const data = await uploadPic({
      imgUrl: upLoadFileList.join(','),
      settlementNo,
    });
    if (data.code === '0000') {
      notification.success({ message: '上传成功' });
      initPicUpload();
    }
  };
  const uploadFileFn = async () => {
    if (!fileList.length) {
      notification.warning({ message: '请先上传附件' });
      return;
    }
    const result = await uploadFile(fileList[0], settlementNo);
    if (result.businessCode === '0000') {
      notification.success({ message: '导入成功' });
      setFileList([]);
    }
  };
  const uploadFn = () => {
    if (tabValue === '1') {
      uploadPicFn();
    } else {
      uploadFileFn();
    }
  };
  const changeTab = tabV => {
    setTabValue(tabV);
  };
  return (
    <Modal title="上传发票" visible={visible} footer={null} onCancel={props.onCancel} width="700px">
      <Tabs defaultActiveKey="1" className={styles.tab} onChange={changeTab} activeKey={tabValue}>
        <TabPane tab="上传凭证" key="1">
          <UploadC ref={picUpload} />
        </TabPane>
        <TabPane tab="上传附件" key="2">
          <a
            href="https://kdspstatic.op4po.com/%E5%8F%91%E7%A5%A8%E4%B8%8A%E4%BC%A0%E6%A8%A1%E6%9D%BF.xlsx"
            className={styles.down}
          >
            模板下载
          </a>
          <Dragger {...uploadProps} className={styles.clearfloat}>
            <p>
              <UploadOutlined />
            </p>
            <p>点击上传附件</p>
          </Dragger>
        </TabPane>
      </Tabs>
      <Button type="primary" onClick={uploadFn} className={styles.logBtn}>
        {tabValue === '1' ? '确定上传图片' : '确定上传附件'}
      </Button>
    </Modal>
  );
};
