import React, { useState } from 'react';
import { InboxOutlined } from '@ant-design/icons';
import { Button, Modal, Upload, message, Switch } from 'antd';
import { useStore } from "@/pages/pms/storage/partShop";
import {importStockFix, shopImport} from './api';
import _ from 'lodash';
import type { UploadFile, UploadProps } from 'antd/es/upload/interface';

interface Props{
  stock?:boolean
}
const apiObj: {[key: number]: any} = {
  1: importStockFix,
  2: shopImport
};
const Dragger = Upload.Dragger;
export default function UploadExcel(props: Props) {
  const { importVisible, setImportVisible, override, setOverride } = useStore();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploadResult, setUploadResult] = useState<any>();
  const [confirmLoading, setConfirmLoading] = useState(false);
  const {stock} = props;

  function beforeUpload(file: any) {
    setFileList([...fileList, file]);
    if (override == null) {
      message.error('请选择是否覆盖数据');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 20;
    if (!isLt2M) {
      message.error('文件不能超过20MB!');
      return false;
    }
    return false;
  }

  function submit() {
    if (override == null) {
      message.error('请选择是否覆盖数据');
      return;
    }
    setConfirmLoading(true);
    const type = stock ? 1 : 2;
    apiObj[type]({file: fileList[0], override}).then((res) => {
      setConfirmLoading(false);
      setUploadResult(res.data)
      message.success('导入成功');
    }).catch((e: any) => {
      setConfirmLoading(false);
      message.error(e.message);
    });
  }
  const uploadProps: UploadProps = {
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload,
    fileList,
  };

  return (
    <Modal
      visible={importVisible}
      maskClosable={false}
      title={uploadResult ? '导入结果' : stock ? '调运库存导入': '文件导入'}
      onCancel={() => { setImportVisible(false); setUploadResult(null); }}
      footer={
        <div>
          <Button
            loading={confirmLoading}
            onClick={() => {
              setImportVisible(false);
              setUploadResult(null);
            }}
          >
            取消
          </Button>
          <Button type="primary" onClick={_.throttle(submit, 3000)} disabled={!fileList.length} loading={confirmLoading}>确定</Button>
        </div>
      }
    >
      {!uploadResult ? (
        <div>
          <div style={{marginBottom: 20}}>
            <span style={{marginRight: 20, color: '#333', fontSize: 14}}>是否覆盖数据：</span>
            <Switch defaultChecked={override} onChange={(checked) => setOverride(checked)} />
          </div>
          {stock ? (
            <Dragger {...uploadProps}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">将文件拖到此处上传</p>
            </Dragger>
          ) : (
            <Dragger {...uploadProps}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">将文件拖到此处上传</p>
            </Dragger>
          )}
        </div>
      ) : (
        <div>
          <p>数据总条数：{uploadResult.totalCount}条</p>
          <p>成功条数：{uploadResult.successCount}条</p>
          <p>失败条数：{uploadResult.failedCount}条</p>
          {uploadResult.filePath ? (<a href={uploadResult.filePath} target="_blank" rel="noopener noreferrer">下载错误文件</a>):null}
        </div>
        )}
    </Modal>
  );
}
