import { InboxOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import type { RcFile } from 'antd/es/upload/interface';
import { Upload, Table, Button, Spin, message, Empty } from 'antd';
import { datasUploadXlsx, usersUploadXlsx } from '@/services/SearchVehicle/searchVehicle';
import { useState, useEffect } from 'react';
import * as XLSX from 'xlsx';
const { Dragger } = Upload;


export default (props: any) => {
  const [tableData, setTableData] = useState<any>([]);
  const [spinning, setSpinning] = useState<any>(false);
  const [file, setFile] = useState<any>(null);
  const [tableHeader, setTableHeader] = useState<any>([]);
  const [tableTitle, setTableTitle] = useState<any>('');
  const [disabled, setDisabled] = useState<any>(true);
  const propsData: UploadProps = {
    name: 'file',
    multiple: true,
    maxCount: 1,
    listType: 'picture',
    accept: ".xlsx, .xls",
    showUploadList: false,
    onChange(info) {
      uploadFilesChange(info)
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },
    beforeUpload: (file: any) => {

      const formData = new FormData();
      formData.append('file', file as RcFile);
      console.log(formData);

      setFile(formData)

      return false;
    },
    // previewFile(file) {
    //   console.log('Your upload file:', file);
    // },
  };


  useEffect(() => {
    reset()  // 重置
    return () => {
    };
  }, [props]);

  // 重置
  const reset = () => {
    setTableData([])
    setFile(null)
    setTableHeader([])
    setTableTitle('')
    setDisabled(true)
  };


  const uploadFilesChange = (file: any) => {
    // 通过FileReader对象读取文件
    setSpinning(true)

    const fileReader = new FileReader();
    fileReader.onload = (event: any) => {
      try {
        const { result } = event.target;
        let sheet = '' as any
        // 以二进制流方式读取得到整份excel表格对象
        const workbook = XLSX.read(result, { type: 'binary' });
        // 存储获取到的数据
        let data = {} as any;
        // 遍历每张工作表进行读取（这里默认只读取第一张表）
        for (sheet in workbook.Sheets) {
          let tempData = [] as any;
          // esline-disable-next-line
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            // 利用 sheet_to_json 方法将 excel 转成 json 数据
            console.log(sheet);
            setTableTitle(sheet)
            data[sheet] = tempData.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
          }
        }
        const excelData = data[sheet];
        const excelHeader = [];
        console.log(excelData);
        console.log(data);

        // 获取表头
        for (const headerAttr in excelData[0]) {
          const header = {
            title: headerAttr,
            dataIndex: headerAttr,
            key: headerAttr
          };
          excelHeader.push(header);
        }
        // 解析后的变量赋值给state，重新渲染table页面
        // message.success('上传成功')
        setTableData(excelData)
        setTableHeader(excelHeader)
        setDisabled(false)
        setSpinning(false)
        message.success('加载成功');
      } catch (e) {
        // 这里可以抛出文件类型错误不正确的相关提示
        console.log(e);
        // message.error('文件类型不正确');
      }
    };
    // 以二进制方式打开文件
    fileReader.readAsArrayBuffer(file.file);
  }






  const toSubmit = () => {
    setSpinning(true)
    if (props.type) {
      switch (props.type) {
        case 'user':
          if (file) {
            usersUploadXlsx(file).then((res: any) => {
              setSpinning(false)
              message.success('导入成功');
              toBack(true)
            });
          }
          break;

        case 'data':
          if (file) {
            datasUploadXlsx(file).then((res: any) => {
              setSpinning(false)
              message.success('导入成功');
              toBack(true)
            });
          }
          break;

        default:
          break;
      }

    }



  };


  const toBack = (type: any) => {
    props.toBack(type)
  };




  return (
    <Spin tip="Loading..." size="large" spinning={spinning}>
      {/* table主体 */}
      <Dragger {...propsData}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        {props.type === 'data' ? <>
          <p className="ant-upload-text">单击或拖动文件到此区域进行上传和预览</p>
          <p className="ant-upload-hint">支持单次上传,严禁上传公司数据或其他标注栏文件。</p>
          <p className="ant-upload-hint">导入车型功能前需要确保该车型在数据库中存在</p>
        </> : <>
          <p className="ant-upload-text">单击或拖动文件到此区域进行上传和预览</p>
          <p className="ant-upload-hint">导入用户数据</p>
        </>}
      </Dragger>
      <div style={{ textAlign: 'center', marginTop: 20 }}>
        <Button onClick={toSubmit} type='primary' disabled={disabled}>提交</Button>
        <Button onClick={() => { toBack(false) }} type='primary' style={{ marginLeft: 20 }}>返回</Button>
      </div>
      <h3 style={{ color: '#1890ff' }}>{tableTitle}</h3>
      <div style={{ display: tableData.length > 0 ? 'block' : 'none' }} >
        <Table columns={tableHeader}
          dataSource={tableData}
          style={{ marginTop: 20 }}
          pagination={{ pageSize: 5 }}
        />
      </div>
      <Empty style={{ display: tableData.length > 0 ? 'none' : "block" }} />
    </Spin>
  );
};
