import React, { useEffect, useState } from 'react';
import { InboxOutlined } from '@ant-design/icons';
import { Button, Modal, Upload, message } from 'antd';
import ConfirmDetailModal from '@/pages/pms/partPlan/PlanShipping/components/ConfirmDetailModal';
import usePagination from '@/hooks/usePagination';
import { getStoragePage } from '@/pages/pms/storage/StorageManage/api';
import { getPageListApi, Item } from '@/pages/pms/partPlan/PlanSupplier/api';
import SelectRow from '@/pages/pms/comonents/SelectRow';
import useInitail from "@/hooks/useInitail";
import { getShopApi } from '@/pages/pms/storage/partShop/api';

const Dragger = Upload.Dragger;

interface Props {
  getList: () => any
  importVisible: boolean
  brands: any[]
  setImportVisible: (v: boolean) => any
}

export default function UploadExcel({ getList, importVisible, setImportVisible, brands }: Props) {
  const [delay, setDelay] = useState(true);
  const [fileList, setFileList] = useState<any[]>([]);
  const { list: storages } = usePagination<PartStorageSpace.PageVO>(getStoragePage, {pageSize: 1000});
  const { list: suppliers, setParams, innerParams } = usePagination<Item>(getPageListApi, { pageSize: 500, supplierType: 10 }, {delay});
  const { data: shops } = useInitail<PmsStoragePartShop.Option[], {}>(getShopApi, [], {});
  const [param, setParam] = useState({ brandId: null, storageId: null, supplierId: null, settleShopId: null});
  const [visibleDetail, setVisibleDetail] = useState(false);
  const [uploadResult, setUploadResult] = useState<any>();

  useEffect(() => {
    if (!importVisible) {
      setUploadResult(null);
      setParam({ brandId: null, storageId: null, supplierId: null, settleShopId: null });
      setFileList([]);
    }
  }, [importVisible]);

  useEffect(() => {
    if (!visibleDetail) {
      setImportVisible(false);
    }
  }, [visibleDetail]);

  function beforeUpload(file: any) {
    const isLt2M = file.size / 1024 / 1024 < 20;
    if (!isLt2M) {
      message.error('文件不能超过20MB!');
    }
    return isLt2M;
  }

  function handleChange(info: any) {
    const { file: { status, response }, fileList } = info;
    if (status !== 'uploading' && response) {
      const { success, result, data } = response;
      if (status === 'done' && success) {
        message.success(`${info.file.name} 上传成功`);
        // 调用上传接口
        setUploadResult(data);
        getList();
      } else if (response && !success) {
        message.error(`${info.file.name} 上传失败: ${result}`);
      }
    }
    setFileList(fileList.splice(-1));
  }
  const uploadProps = {
    accept: '.xls, .xlsx',
    name: 'file',
    fileList,
    multiple: false,
    data: param,
    action: `/api/pms/app/part/shipping/save`,
    onChange: (file: any) => handleChange(file),
    beforeUpload: (info: any) => beforeUpload(info)
  };
  return (
    <Modal
      visible={importVisible}
      maskClosable={false}
      title={uploadResult ? '导入结果' : '文件导入'}
      onCancel={() => { setImportVisible(false); setUploadResult(null); }}
      footer={
        <Button onClick={() => { setImportVisible(false); setUploadResult(null); }}>取消</Button>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column'}}>
        <SelectRow
          title="品牌"
          value={param.brandId}
          data={brands}
          id="id"
          name="name"
          onChange={brandId => {
            setParam({...param, brandId});
            setParams({ ...innerParams, brandId, current: 1 }, true);
            setDelay(false);
          }}
        />
        <SelectRow
          title="供应商"
          value={param.supplierId}
          data={suppliers}
          id="supplierId"
          name="supplierName"
          onChange={supplierId => setParam({ ...param, supplierId })}
        />
        <SelectRow
          title="库房"
          value={param.storageId}
          data={storages}
          id="id"
          name="storageName"
          onChange={storageId => setParam({ ...param, storageId })}
        />
        <SelectRow
          title="结算门店"
          value={param.settleShopId}
          data={shops}
          id="id"
          name="name"
          onChange={settleShopId => setParam({ ...param, settleShopId })}
        />
      </div>
      {!uploadResult ? !!param.brandId && !!param.storageId && !!param.supplierId && (
        <div>
          <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>失败条数：<span style={{ color: 'red' }}>{uploadResult.failedCount}</span>条</p>
          {uploadResult.filePath ? (<a href={uploadResult.filePath} target="_blank" rel="noopener noreferrer">下载错误文件</a>) : null}
          {!!uploadResult.data && !!uploadResult.successCount && (
            <div style={{marginTop: 10}}>
              <p>供应商：{uploadResult.data?.supplierName || '--'}</p>
              <p>发运单号：{uploadResult.data?.shippingNo || '--'}</p>
              <p>发运品种：{uploadResult.data?.cnt || 0}种</p>
              <p>本次导入金额：{uploadResult.data?.importAmount || 0}元</p>
              <a onClick={() => { setVisibleDetail(true); }}>去确认</a>
            </div>
          )}
        </div>
      )}
      <ConfirmDetailModal
        visible={visibleDetail}
        item={uploadResult?.data || {}}
        confirm
        onCancel={() => setVisibleDetail(false)}
        fetchList={() => { setUploadResult(null); getList(); }}
      />
    </Modal>
  );
}
