import * as PropTypes from 'prop-types';
import * as React from 'react';
import weui from '../../../utils/weui';
import classNames from '../../../utils/classnames';
import { getCloudInstance } from '../../../utils/tcb';
import { useGetSet } from 'react-use';
/**
 * H5端
 */
export function UploaderH5({
  title,
  maxUploadCount,
  className,
  id,
  events,
  layout,
  value,
  single = false,
  onChange,
  style,
}) {
  const cls = classNames({
    'weda-ui': true,
    'weui-cells': true,
    'weui-cells_form': true,
    [className]: className,
  });

  let initialValue = []
    .concat(value)
    .filter((d) => typeof d === 'string' && d !== '');
  if (single) {
    maxUploadCount = 1;
    initialValue = initialValue[0] ? [initialValue[0]] : [];
  }
  const [uploadCount, setUploadConut] = useGetSet(0);
  const [fileIDList, setfileIDList] = React.useState(initialValue);
  React.useEffect(() => {
    events.change && events.change({ value: fileIDList });
    if (single) {
      const file = fileIDList[0] || '';
      file && onChange && onChange(file);
    } else {
      onChange && onChange(fileIDList);
    }
  }, [fileIDList]);
  React.useEffect(() => {
    const opts = {
      url: 'http://localhost:8081',
      auto: true,
      type: 'file',
      fileVal: 'fileVal',
      compress: {
        width: 1600,
        height: 1600,
        quality: 0.8,
      },
      onBeforeQueued: function (files) {
        // `this` 是轮询到的文件, `files` 是所有文件

        if (
          ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'].indexOf(
            this.type
          ) < 0
        ) {
          weui.alert('请上传图片');
          return false; // 阻止文件添加
        }
        if (this.size > 10 * 1024 * 1024) {
          weui.alert('请上传不超过10M的图片');
          return false;
        }

        if (files.length > maxUploadCount) {
          // 防止一下子选择过多文件
          weui.alert(`最多只能上传${maxUploadCount}张图片，请重新选择`);
          return false;
        }
        if (uploadCount() + 1 > maxUploadCount) {
          weui.alert(`最多只能上传${maxUploadCount}张图片`);
          return false;
        }

        setUploadConut(c => c + 1);

      },
      onQueued: function () {

        const file = this;
        getCloudInstance().then(async (tcb) => {
          try {
            const fileType = file.type.split('/')?.[1];
            const cloudPath = `temp/uploader-${Date.now()}.${fileType}`;
            const { fileID } = await tcb.uploadFile({
              cloudPath,
              filePath: file,
            });
            fileID && setfileIDList((list) => [...list, fileID]);
            fileID && events.success && events.success({ value: fileID, file });
            const r = opts.onSuccess(file, );
            if(!r) {
              
              const $el = document.querySelector(`#${id}`);
              const $file = $el.querySelector(`[data-id="${file.id}"]`);
              $file.classList.remove('weui-uploader__file_status');
              $file.querySelector('.weui-uploader__file-content').remove();
            }
          } catch (err) {
            opts.onError(file, err);
          }
        });
      },
      onBeforeSend: function () {
        // $.extend(data, { test: 1 }); // 可以扩展此对象来控制上传参数
        // $.extend(headers, { Origin: 'http://127.0.0.1' }); // 可以扩展此对象来控制上传头部

        return false; // 阻止文件上传
      },
      onProgress: function () {
        // console.log(this, percent);
        // return true; // 阻止默认行为，不使用默认的进度显示
      },
      onSuccess: function (ret) {
        events.success && events.success(ret);
        return false;
      },
      onError: function (err) {
        events.error && events.error(err);
        return false;
      },
    };
    weui.uploader(`#${id}`, opts);
  }, []);

  return (
    <div className={cls} id={id} style={style}>
      <div className="weui-cell">
        <div className="weui-cell__bd">
          <div className={classNames("weui-uploader", layout)}>
            <div className={classNames("weui-uploader__hd", layout)}>
              <p className="weui-uploader__title">{title}</p>
              <div className="weui-uploader__info">
                <span id="uploadCount">{uploadCount()}</span>
                {`/${maxUploadCount}`}
              </div>
            </div>
            <div className="weui-uploader__bd">
              <ul className="weui-uploader__files" id="uploaderFiles"></ul>
              <div className="weui-uploader__input-box">
                <input
                  id="uploaderInput"
                  className="weui-uploader__input"
                  type="file"
                  accept="image/*"
                  multiple=""
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

UploaderH5.propTypes = {
  id: PropTypes.string,
  title: PropTypes.string,
  className: PropTypes.string, // 传入类
  maxUploadCount: PropTypes.number, // 【上传图片最大数量】
  events: PropTypes.objectOf(PropTypes.func), // 事件
  style: PropTypes.object,
  layout: PropTypes.oneOf(['horizontal', 'vertical']),
  value: PropTypes.oneOfType([PropTypes.array, PropTypes.string]), // 初始值，该参数需配合 formily 使用
  single: PropTypes.bool, // 单张上传还是多张上传，对应 onChange 参数为字符串还是字符串数组，value 在处理过程统一转为字符串数组
  onChange: PropTypes.objectOf(PropTypes.func), // 值变化，该参数需配合 formily 使用
};
