import React from 'react';
import Taro from '@tarojs/taro';
import { View, Image, Video } from '@tarojs/components';
import { Loading } from '@antmjs/vantui';
import { uploadFiles } from '@/utils/request';
import icon from '@/assets/icons/uploader.png';
import closeIcon from '@/assets/icons/close.png';
import style from './style.modules.less';

export default (props) => {
  // value 为数组
  // 单个元素结构为 { url, fileType }
  const { value, disabled = false, onChange } = props;
  const [loading, setLoading] = React.useState(false);

  const onAdd = (e) => {
    e.preventDefault();
    e.stopPropagation();

    if (disabled) return;

    setLoading(true);
    Taro.chooseMedia({
      maxDuration: 60,
      sizeType: 'compressed',
      success: (res) => {
        const { tempFiles } = res;
        uploadFiles(tempFiles).then(resp => {
          setLoading(false);          
          onChange((value || []).concat(resp));
        }).catch((err) => {
          console.error(err);
          setLoading(false);
        })
      },
      fail: (err) => {
        console.error(err);
        setLoading(false);
      }
    })
  }

  const onDelete = (item) => {
    const newVal = value.filter(x => x.url != item.url);
    onChange(newVal);
  }

  const onPreview = (inx) => {
    Taro.previewMedia({
      sources: value.map(x => ({ url: x.url, type: x.fileType })),
      current: inx,
    })
  }

  return (
    <View className={style['uploader-wrapper']}>
      <View className={style['uploader-box']}>
        {
          !disabled && (
            <View className={style['uploader-add']}>
              <Image src={icon} onClick={onAdd} />
              {
                loading && (
                  <View>
                    <Loading color="#fff" />
                  </View>
                )
              }
            </View>
          )
        }
        {
          (value || []).map((item, inx) => (
            <View key={item.url} className={style['uploader-item']}>
              {
                item.fileType == 'image' ?
                  <Image src={item.url} onClick={() => onPreview(inx)} /> :
                  <Video src={item.url} controls={false} onClick={() => onPreview(inx)} />
              }
              {
                !disabled && (
                  <View onClick={() => onDelete(item)}>
                    <Image src={closeIcon} />
                  </View>
                )
              }
            </View>
          ))
        }
      </View>
    </View>
  )
}
