import React from 'react'
import { View, Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import uploadApi from '@/services/uploadFiles'
import './upload-from-wx.scss'
import { CoverImageValue } from '.'
import { uploadFileResponseData } from '@/services/uploadFiles'

export interface UploadFromWxProps {
  onAdd: (images: CoverImageValue[], onFileUploaded: Promise<{ id: string, data: uploadFileResponseData }[]>) => void
  maxCount: number
}

export default function UploadFromWx(props: UploadFromWxProps) {
  const {
    onAdd = () => void 0,
    maxCount = 9, // calc from parent
  } = props
  const handleImportFromWx = () => {
    Taro.chooseImage({
      count: maxCount,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
    }).then(async (res) => {
      // TODO: compress image
      // TODO: cropping image to const size
      let count = 0
      const files = res.tempFiles.map(item => ({
        filePath: item.path,
        description: 'test',
        tags: 'test',
        is_public: 1 as unknown as 0 | 1,
        id: (Date.now() + count++).toString(),
      }))
      const onFileUploaded = uploadApi.batchUpload(files)
      onAdd(res.tempFiles.map(item => ({
        id: Date.now().toString(),
        url: item.path,
      })), onFileUploaded) // TODO: add loading state
    })
  }
  return (
    <View onClick={handleImportFromWx}>
      <Text className="upload-from-wx-text">从相册添加</Text>
    </View>
  )
}