import React, { useState } from "react";
import { ImgUploaderProps } from "../../data/Props";
import { Uploader, ImagePreview } from "@nutui/nutui-react";
import { CommonTitle } from "../title/CommonTitle";
import UploaderStyle from "./uploader.module.css";
import { FileItem } from "@nutui/nutui-react/dist/types/packages/uploader/file-item";
import "@nutui/nutui-react/dist/style.css";
import { UploadIcon } from "./Widgets";
import { compressImgs } from "./UploadHelper";

export const ImgUploader: React.FC<ImgUploaderProps> = (props) => {
  const uploadUrl = "https://file-dd.jd.com/file/uploadImg.action";
  let curStatus = "";
  const operateFileList: FileItem[] = [];
  const [showPreview, setShowPreview] = useState<number>(0);
  const [previewImgs, setPreviewImgs] = useState<{ src: string }[]>([]);

  const onUploadFailed = (resp: any) => {
    onStatusChange(resp.files);
  };

  const onUploadSuccess = (resp: any) => {
    onStatusChange(resp.files);
    onResult(resp.files);
  };

  const onImgDelete = (delItem: FileItem, items: FileItem[]) => {
    onStatusChange(items, delItem);
    onResult(items);
  };

  const showImgPreview = (_file: FileItem, index: number) => {
    setShowPreview(index + 1);
  };

  const hideImgPreview = () => {
    setShowPreview(0);
  };

  const onResult = (items: FileItem[]) => {
    let result: string[] = [];
    items.forEach((fileItem) => {
      if (fileItem.status === "success") {
        if (fileItem.responseText) {
          const resp = JSON.parse(fileItem.responseText);
          if (resp && resp.code === 200 && resp.path) {
            result.push(resp.path);
          }
        }
      }
    });

    props.onResult?.(result);
  };

  const onStatusChange = (items: FileItem[], delItem?: FileItem) => {
    let newStatus = "finish";
    for (let index = 0; index < items.length; index++) {
      const fileItem = items[index];
      if (fileItem.uid !== delItem?.uid && fileItem.status === "uploading") {
        newStatus = "uploading";
        break;
      }
    }

    if (curStatus !== newStatus) {
      curStatus = newStatus;
      props.onUploadStatusChange?.(curStatus);
    }

    setPreviewImgs(
      items.flatMap((item) => {
        return { src: item.url ?? "" };
      })
    );
  };

  return (
    <>
      <div style={props.styles}>
        {props?.title ? (
          <CommonTitle title={props.title} must={props.must}></CommonTitle>
        ) : null}
        <div className={UploaderStyle.container}>
          <Uploader
            className={UploaderStyle.uploader}
            accept="image/*"
            url={uploadUrl}
            name="upload"
            data={props.uploadData}
            defaultValue={operateFileList}
            uploadIcon={UploadIcon}
            maxCount={props.limit}
            deletable={true}
            fit="cover"
            multiple={true}
            timeout={30000}
            beforeUpload={props.enableCompress ? compressImgs : undefined}
            onSuccess={onUploadSuccess}
            onFailure={onUploadFailed}
            onDelete={onImgDelete}
            onFileItemClick={showImgPreview}
          ></Uploader>
          {props.limit ? (
            <div className={UploaderStyle.tip}>图片最多上传{props.limit}张</div>
          ) : null}
        </div>
      </div>
      <ImagePreview
        images={previewImgs}
        visible={showPreview > 0}
        defaultValue={showPreview}
        onClose={hideImgPreview}
        closeOnContentClick={true}
      ></ImagePreview>
    </>
  );
};
