import { picUpload } from '@/service/picUpload';
import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { Component, ReactNode } from 'react';
import { AtImagePicker } from 'taro-ui';
import { File } from 'taro-ui/types/image-picker';

const reLaunchInterval = 1000;

interface PicUploaderState {
  files: File[];
}

interface PicUploaderProps {
  source: string;
  id: number;
  superId?: number;
}

export default class PicUploader extends Component<
  PicUploaderProps,
  PicUploaderState
> {
  state = {
    files: [] as File[],
  };
  onUpload() {
    if (this.state.files.length !== 0) {
      for (let file of this.state.files) {
        picUpload(this, file.url);
      }
    }
    if (this.props.source == 'comment') {
      setTimeout(() => {
        Taro.reLaunch({
          url: '/pages/TicketDetail/TicketDetail?id=' + this.props.superId,
        });
      }, reLaunchInterval);
    } else if (this.props.source == 'conclusion') {
      setTimeout(() => {
        Taro.reLaunch({
          url: '/pages/index/index',
        });
      }, reLaunchInterval);
    }
  }
  handlePicChange(files: File[]) {
    this.setState({
      files: files,
    });
    return files;
  }
  render(): ReactNode {
    return (
      <View>
        <AtImagePicker
          showAddBtn={this.state.files.length !== 3}
          count={3}
          files={this.state.files}
          sizeType={['compressed']}
          onChange={this.handlePicChange.bind(this)}
        />
      </View>
    );
  }
}
