import Taro from '@tarojs/taro'
import { AtImagePicker } from 'taro-ui'
import { View, Text, Image } from '@tarojs/components'
import classnames from 'classnames'
import { CustomLabel, ItemExtra } from '../index'
import { getItem, setItem, uuid } from '../../util'
import { getSignature } from '../../service/global'
import './index.scss'

interface InputProps {
  itemExtra?: string
  name: string
  placeholder?: string
  term: string
  value?: any
  defaultValue?: any
  onChange?: (value) => void
  editable?: boolean
  help?: string
  required?: boolean
  multiple?: boolean
  onView?: boolean
  listItemChildren?: boolean
}

const Picture: React.FC<InputProps> = ({
  itemExtra,
  multiple,
  editable,
  term,
  value = [],
  onChange,
  help,
  required,
  defaultValue,
  onView,
  listItemChildren
}) => {

  const pictureOnChange = async (newfiles, type) => {
    if (editable || editable === undefined) {
      if (type === 'add') {
        let OSSData = getItem('OSSData')
        const expire = (OSSData && OSSData.expire * 1000) || 0;
        if (expire < Date.now()) {
          getSignature().then(OSSDataRes => {
            if (OSSDataRes.signature) {
              setItem({ key: 'OSSData', data: OSSDataRes })
              upload(OSSDataRes, newfiles)
            }
          })
        } else {
          upload(OSSData, newfiles)
        }
      } else {
        onChange && onChange(newfiles)
      }
    }
  }

  const upload = (OSSData, newfiles) => {
    const tempFiles = newfiles.splice(value.length, newfiles.length).map(item => {
      const suffix = item.url.substring(item.url.length - 8)
      const uid = uuid()
      const fileName = uid + suffix
      const key = OSSData.dir + fileName
      return {
        ...item,
        key,
        fileName
      }
    })

    let count = tempFiles.length

    tempFiles.map((currentFile) => {
      Taro.showLoading({
        title: '图片上传中',
        mask: true
      })
      const formData = {
        key: currentFile.key,
        OSSAccessKeyId: OSSData.accessId,
        policy: OSSData.policy,
        Signature: OSSData.signature,
        'Content-Disposition': `inline;filename*=UTF-8''${currentFile.fileName}`,
        success_action_status: '200',
      }
      if (Taro.getEnv() === 'WEAPP') {
        Taro.uploadFile({
          url: OSSData.host,
          filePath: currentFile.url,
          name: 'file',
          formData,
          success: (res) => {
            if (res.statusCode === 200) {
              count -= 1
              if (count === 0) {
                const newValue = value.concat(tempFiles.map(item => {
                  return {
                    ...item,
                    url: `${OSSData.host}/${item.key}`
                  }
                }))
                onChange && onChange(newValue)
                Taro.hideLoading()
              }
            } else {
              console.log('upload fail', res)
              Taro.showToast({
                title: '上传图片失败',
                icon: 'none'
              })
            }
            Taro.hideLoading()
          },
          fail: (err) => {
            console.log('upload fail', err)
            Taro.hideLoading()
            Taro.showToast({
              title: '上传图片失败',
              icon: 'none'
            })
          }
        })
      } else {
        let hformData = new FormData();
        hformData.append('key', formData.key);
        hformData.append('OSSAccessKeyId', formData.OSSAccessKeyId);
        hformData.append('policy', formData.policy);
        hformData.append('Signature', formData.Signature);
        hformData.append('Content-Disposition', `inline;filename*=UTF-8''${encodeURI(currentFile.file.originalFileObj.name)}`);
        hformData.append('success_action_status', '200');
        hformData.append('file', currentFile.file.originalFileObj);
        Taro.request({
          url: OSSData.host,
          method: 'POST',
          mode: 'cors',
          data: hformData,
          dataType: 'string',
          success: (res) => {
            if (res.statusCode === 200) {
              count -= 1
              if (count === 0) {
                const newValue = value.concat(tempFiles.map(item => {
                  return {
                    ...item,
                    url: `${OSSData.host}/${item.key}`
                  }
                }))
                onChange && onChange(newValue)
                Taro.hideLoading()
              }
            } else {
              Taro.hideLoading()
              Taro.showToast({
                title: '上传图片失败',
                icon: 'none'
              })
            }
          },
          fail: (err) => {
            console.log('fail', err)
            Taro.hideLoading()
            Taro.showToast({
              title: '上传图片失败',
              icon: 'none'
            })
          },
        })
      }
    })
  }


  const onFail = (mes) => {
    console.log(mes)
  }

  const preview = (index, file) => {
    const showValue = (value !== undefined ? value : defaultValue) || []
    Taro.previewImage({ current: file.url, urls: showValue.map(image => image.url) })
  }

  const showValue = (value !== undefined ? value : defaultValue) || []

  const containerCLs = classnames(['picture-container', listItemChildren ? 'item-container' : 'item-container-margin'])

  return (
    <View className={containerCLs}>
      <CustomLabel term={term} help={help} required={onView ? false : required} style={{ height: '20px' }} />
      {(itemExtra && !onView) &&
        <View className='picture-extar-wrap'>
          <ItemExtra text={itemExtra} />
        </View>}
      {(editable === false || (editable === undefined && onView)) ? <View className='image-wrap'>
        {showValue.map((pic, index) => {
          return (
            <Image key={pic.uid || index} className='image-item' src={pic.url} onClick={() => preview(index, pic)} />
          )
        })}
      </View> :
        <View className='image-picker-wrap'>
          <AtImagePicker
            multiple={multiple}
            files={showValue}
            onChange={pictureOnChange}
            onFail={onFail}
            onImageClick={preview}
          />
        </View>}
    </View>
  )
}

export default Picture
