import React, { useState } from 'react';
import Taro from '@tarojs/taro';
import { Image, View } from '@tarojs/components';
const plusIcon = 'https://wanmi-b2b-x-site.oss-cn-shanghai.aliyuncs.com/pandora-ui/assets/components/images/upload-image/icon-plus.png';
const closeIcon = 'https://wanmi-b2b-x-site.oss-cn-shanghai.aliyuncs.com/pandora-ui/assets/components/images/upload-image/icon-close.png';
const loadingIcon = 'https://wanmi-b2b-x-site.oss-cn-shanghai.aliyuncs.com/pandora-ui/assets/components/images/upload-image/icon-loading.gif';
import uploadUtils from './upload-utils';

interface IUploadImageProps {
  /** 最大尺寸 */
  maxSize?: number;
  /** 上传请求url */
  url: string;
  /** 默认文件列表 */
  defaultList?: string[];
  /** 最大文件数 */
  maxNum?: number;
  /** 是否展示说明 */
  isShowDesc?: boolean;
  /** 允许上传文件格式 **/
  allowTypes?: string[];
  /** 上传后回调 */
  onChange?: (fileList: string[]) => void;
}

type uploadRes = {
  context: [string];
};
const env = Taro.getEnv();
const token = 'Bearer ' + Taro.getStorageSync('authInfo:token');

/**
 * 文件上传组件
 */
const UploadImage: React.FC<IUploadImageProps> = ({
  url = '',
  maxSize = 5,
  defaultList = [],
  maxNum = 3,
  isShowDesc = true,
  allowTypes = ['.jpg', '.jpeg', '.png', '.gif'],
  onChange = (_fileList: string[]) => {},
}) => {
  const [fileList, setFileList] = useState<string[]>(defaultList);
  const [loading, setLoading] = useState<boolean>(false);
  /** 点击选择图片 */
  const chooseFiles = async (): Promise<uploadRes> => {
    return new Promise(async (resolve, reject) => {
      if (env === Taro.ENV_TYPE.WEAPP) {
        Taro.chooseImage({
          success: async (response) => {
            setLoading(true);
            uploadUtils
              .uploadFile(
                response,
                resolve,
                reject,
                maxSize,
                url,
                token,
                allowTypes,
              )
              .then((result) => result)
              .catch((err) => err);
          },
        });
      } else {
        uploadUtils.h5Upload(
          resolve,
          reject,
          maxSize,
          url,
          token,
          allowTypes,
          () => setLoading(true),
        );
      }
    });
  };

  /** 点击上传事件 */
  const onClick = async () => {
    const { context } = await chooseFiles().then((response) => {
      setLoading(false);
      return response;
    });
    const newList = [...fileList, context[0]];
    onChange(newList);
    setFileList(newList);
  };

  /** 删除事件 */
  const remove = (fileUrl: string) => {
    fileList.splice(fileList.indexOf(fileUrl), 1);
    onChange([...fileList]);
    setFileList([...fileList]);
  };

  return (
    <View className='wm-upload-image'>
      {fileList?.length > 0 &&
        fileList.map((file, index) => {
          return (
            <View key={index} className='image-box'>
              <Image className='image' src={file} />
              <View className='close-box'>
                <Image
                  src={closeIcon}
                  className='close-icon'
                  onClick={() => {
                    remove(file);
                  }}
                />
              </View>
            </View>
          );
        })}
      {maxNum > fileList?.length && (
        <View className='image-box' onClick={() => onClick()}>
          <Image className='icon' src={loading ? loadingIcon : plusIcon} />
        </View>
      )}
      {isShowDesc && (
        <View className='upload-desc'>
          {allowTypes?.length > 0 && `仅支持${allowTypes.join(',')}文件，`}
          最多上传{maxNum || 1}张，大小不超过
          {maxSize || 5}M
        </View>
      )}
    </View>
  );
};

export default UploadImage;
