import Taro from '@tarojs/taro'
import { View, Image } from '@tarojs/components'

import classNames from 'classnames'
import PropTypes, { InferProps } from 'prop-types'
import CtsComponent from '../../common/component'
import { CtsUploadFileProps } from 'types/upload-file'

let error = `${Taro['common'].imgUrlTeam}error.png`
let pdf = `${Taro['common'].imgUrlTeam}pdf.png`

/**
 * 上传文件组件
 */
export default class CtsUploadFile extends CtsComponent<CtsUploadFileProps> {
  // static options = {
  //   addGlobalClass: true
  // }

  public static defaultProps: CtsUploadFileProps
  public static propTypes: InferProps<CtsUploadFileProps>

  public constructor(props: CtsUploadFileProps) {
    super(props)
    this.state = {}
  }

  // 选择文件/图片
  private chooseFile(): void {
    const { type } = this.props
    if (type === 'image') {
      // 选择图片，并上传
      this.chooseImg()
    } else {
      // 上传pdf或word文件
      this.uploadFile()
    }
  }

  // 选择图片，并上传
  private chooseImg(): void {
    let that = this
    const { list, max, isAlbum, isCamera } = this.props

    // 选择图片的来源
    let sourceType: any[] = [...(isAlbum ? ['album'] : []), ...(isCamera ? ['camera'] : [])]
    // console.log('选择图片的来源', sourceType)

    // 最多可选择的图片张数
    let count: number = max - list.length

    Taro.chooseImage({
      sizeType: ['compressed'],
      sourceType,
      count,
      success(res) {
        console.log('chooseImage: ', res)

        let promises: any[] = []
        for (let item of res.tempFiles) {

          // 图片不能大于2M
          if (item.size > 2 * 1024 * 1024) {
            Taro.showToast({ title: '图片不能大于2M', icon: 'none' })
            break
          }

          // 只能上传jpg,jpeg,png的图片
          let type = item.path.split('.')[item.path.split('.').length - 1]
          if (!/^jpg|jpeg|png$/.test(type)) {
            Taro.showToast({ title: '只能上传jpg,jpeg,png的图片', icon: 'none' })
            break
          }

          promises.push(that.getFileUrl(item.path))
        }
        console.log(promises, promises.length)
        Promise.all(promises).then(res2 => {
          console.log('图片列表', res2)
          that.props.onChange([...list, ...res2])
        }).catch(err => {
          console.error('获取文件信息失败', err)
        })
      }
    })
  }

  // 上传文件，并获取远程路径
  private getFileUrl(file: string): any {
    const { bizCode } = this.props
    return new Promise((resolve, reject) => {
      const params = { file, sysCode: 'ggb', bizCode }
      Taro['common'].uploadFile(params).then(res => {
        console.log('远程图片路径：', res.data)
        resolve(res.data)
      })
    })
  }

  // 上传pdf或word文件
  private uploadFile() {
    let that = this
    const { list, max, type } = this.props

    // 最多可选择的图片张数
    let count: number = max - list.length

    Taro.chooseMessageFile({
      count,
      type: 'file',
      success(res) {
        console.log('chooseMessageFile: ', res)

        let promises: any[] = []
        for (let item of res.tempFiles) {

          // 图片不能大于2M
          // if (item.size > 2 * 1024 * 1024) {
          //   Taro.showToast({ title: '图片不能大于2M', icon: 'none' })
          //   break
          // }

          // 只能上传pdf或word文件
          let typeSuffix = item.path.split('.')[item.path.split('.').length - 1]
          if (typeSuffix !== type) {
            Taro.showToast({ title: `只能上传${type}的文件`, icon: 'none' })
            break
          }

          promises.push(that.getFileUrl(item.path))
        }
        console.log(promises, promises.length)
        Promise.all(promises).then(res2 => {
          console.log('文件列表', res2)
          that.props.onChange([...list, ...res2])
        }).catch(err => {
          console.error('获取文件信息失败', err)
        })
      },
      fail(err) {
        console.log(err)
      }
    })
  }

  // 获取文件信息
  // getFileInfo(filePath) {
  //   const { bizCode } = this.props
  //   return new Promise((resolve, reject) => {
  //     Taro.getFileInfo({
  //       filePath,
  //       success(res1) {
  //         console.log(res1)
  //         let size = res1.size

  //         // 图片不能超过2M
  //         if (size > 2 * 1024 * 1024) {
  //           Taro.showToast({ title: '图片不能大于2M', icon: 'none' })
  //           reject()
  //           return
  //         }

  //         const params = { file: filePath, sysCode: 'ggb', bizCode }
  //         Taro['common'].uploadFile(params).then(res => {
  //           console.log('远程图片路径：', res.data)
  //           resolve(res.data)
  //         })
  //       }
  //     })
  //   })
  // }

  // 删除文件
  private deleteFile(index: number): void {
    let { list } = this.props
    list.splice(index, 1)
    this.props.onChange(list)
  }

  render() {
    let { className, list, max, isDetail, type } = this.props

    return (
      <View className={classNames('cts-upload-file', className)}>
        {
          list.map((item, index) => {
            return <View className='upload-img-item' key={String(index)}>
              {
                !isDetail &&
                <Image className='delete' src={error} mode="widthFix" onClick={this.deleteFile.bind(this, index)}></Image>
              }

              <Image className='img' src={type === 'image' ? item : pdf} mode="scaleToFill" onClick={() => { type === 'image' ? Taro['common'].previewImage(item, list) : Taro['common'].previewFile(item) }}></Image>
            </View>
          })
        }
        {
          !isDetail && list.length < max &&
          <View className='upload-img-item' onClick={this.chooseFile.bind(this)}>
            <View className='iconfont iconRectangle'></View>
            <View className='item-text'>添加</View>
          </View>
        }
      </View>
    )
  }
}

CtsUploadFile.defaultProps = {
  list: [],
  max: 1,
  isAlbum: true,
  isCamera: true,
  bizCode: '',
  isDetail: false,
  type: 'image',
  onChange() { }
}

CtsUploadFile.propTypes = {
  list: PropTypes.array,
  max: PropTypes.number,
  isAlbum: PropTypes.bool,
  isCamera: PropTypes.bool,
  bizCode: PropTypes.string,
  isDetail: PropTypes.bool,
  type: PropTypes.oneOf(['image', 'pdf', 'docx']),
  onChange: PropTypes.func
}