import {
  closeToast,
  Icon,
  Image,
  showLoadingToast,
  showToast,
  Uploader,
  UploaderInstance
} from 'vant'
import { defineComponent, ref } from 'vue'
import styles from './index.module.less'
import ColCropper from '../o-cropper'
import { useCustomFieldValue } from '@vant/use'
import { postMessage } from '@/helpers/native-message'
import umiRequest from 'umi-request'
import iconUploader from '@common/images/icon_uploader.png'
import request from '@/helpers/request'
import { getOssUploadUrl, state } from '@/state'
import { getUploadSign, onOnlyFileUpload } from '@/helpers/oss-file-upload'

export default defineComponent({
  name: 'col-upload',
  props: {
    modelValue: String,
    tips: {
      type: String,
      default: '点击上传'
    },
    deletable: {
      type: Boolean,
      default: true
    },
    native: {
      // 是否原生上传
      type: Boolean,
      default: false
    },
    cropper: {
      // 是否进行裁切
      type: Boolean,
      default: false
    },
    options: {
      // 裁切需要参数
      type: Object,
      default: {}
    },
    uploadSize: {
      // 上传图片大小
      type: Number,
      default: 5
    },
    onUploadChange: {
      type: Function,
      default: (url: string) => {}
    },
    bucket: {
      type: String,
      default: 'gyt'
    },
    path: {
      // 创建的目录
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    nativeUpload() {
      if (this.disabled) return
      postMessage(
        {
          api: 'chooseFile',
          content: { type: 'img', max: 1, bucket: this.bucket, path: this.path }
        },
        (res: any) => {
          console.log(res, 'fileUrl')
          this.$emit('update:modelValue', res.fileUrl)
        }
      )
    },
    beforeRead(file: any) {
      console.log(file, 'beforeRead')
      const isLt2M = file.size / 1024 / 1024 < this.uploadSize
      if (!isLt2M) {
        showToast(`上传文件大小不能超过 ${this.uploadSize}MB`)
        return false
      }
      return true
    },
    beforeDelete(file: any, detail: { index: any }) {
      // this.dataModel.splice(detail.index, 1)
      return true
    },
    async afterRead(file: any, detail: any) {
      try {
        file.status = 'uploading'
        file.message = '上传中...'
        await this.uploadFile(file.file)
      } catch (error) {
        //
        console.log(error, '2323')

        closeToast()
      }
    },
    onClose(e: any) {
      this.$emit('update:modelValue', null)
      this.onUploadChange()
      e.stopPropagation()
    },
    async getFile(file: any) {
      try {
        await this.uploadFile(file)
      } catch {
        //
      }
    },
    async uploadFile(file: any) {
      // 上传文件
      try {
        // 获取签名
        if (state.platformType === 'SCHOOL') {
          state.platformApi = '/api-school'
        } else if (state.platformType === 'TEACHER') {
          state.platformApi = '/api-teacher'
        } else if (state.platformType === 'STUDENT') {
          state.platformApi = '/api-student'
        }
        // const signUrl = state.platformApi + '/open/getUploadSign'
        // const tempName = file.name || ''
        // console.log(this.path)
        // const fileName = this.path + '/' + (tempName && tempName.replace(/ /gi, '_'))
        // const key = new Date().getTime() + fileName
        // console.log(file)
        const tempName = file.name || ''
        const fileName = this.path
          ? this.path + '/' + (tempName && tempName.replace(/ /gi, '_'))
          : tempName && tempName.replace(/ /gi, '_')

        const key = new Date().getTime() + fileName

        // const res = await request.post(signUrl, {
        //   data: {
        //     filename: fileName,
        //     bucketName: this.bucket,
        //     postData: {
        //       filename: fileName,
        //       acl: 'public-read',
        //       key: key,
        //       unknowValueField: []
        //     }
        //   }
        // })
        const { data } = await getUploadSign({
          filename: key,
          bucketName: this.bucket,
          postData: {
            filename: key,
            acl: 'public-read',
            key: key,
            unknowValueField: []
          }
        })
        showLoadingToast({
          message: '加载中...',
          forbidClick: true,
          loadingType: 'spinner',
          duration: 0
        })
        const obj = {
          policy: data.policy,
          signature: data.signature,
          key: key,
          KSSAccessKeyId: data.kssAccessKeyId,
          acl: 'public-read',
          name: key,
          file
        }
        const uploadUrl = await onOnlyFileUpload(getOssUploadUrl(this.bucket), obj)
        closeToast()
        this.$emit('update:modelValue', uploadUrl)
        this.onUploadChange(uploadUrl)
      } catch (error) {
        console.log(error, 'uploadFile')
      }
    },
    startUpload() {
      ;(this as any).$refs.uploaderRef?.startChiose()
    }
  },

  render() {
    useCustomFieldValue(() => this.modelValue)

    return (
      <div class={[styles['uploader-section'], 'oUpload']}>
        {this.modelValue && this.deletable ? (
          <Icon name="cross" onClick={this.onClose} class={styles['img-close']} />
        ) : null}
        {this.cropper && !this.native ? (
          <div class={styles['col-uploader']}>
            {this.modelValue ? (
              <Image fit="cover" position="center" class={styles.uploadImg} src={this.modelValue} />
            ) : (
              <div class={styles.uploader}>
                <Icon name={iconUploader} size="32" />
                <p class={styles.uploaderText}>{this.tips}</p>
              </div>
            )}
            <ColCropper ref="uploaderRef" option={this.options} getFile={this.getFile} />
          </div>
        ) : this.native ? (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              height: '100%'
            }}
            onClick={this.nativeUpload}
          >
            {this.modelValue ? (
              <Image fit="cover" position="center" class={styles.uploadImg} src={this.modelValue} />
            ) : (
              <div class={styles.uploader}>
                <Icon name={iconUploader} size="32" />
                <p class={styles.uploaderText}>{this.tips}</p>
              </div>
            )}
          </div>
        ) : (
          <Uploader
            afterRead={this.afterRead}
            beforeRead={this.beforeRead}
            beforeDelete={this.beforeDelete}
            disabled={this.disabled}
            v-slots={{
              default: () =>
                this.modelValue ? (
                  <Image
                    fit="cover"
                    position="center"
                    class={styles.uploadImg}
                    src={this.modelValue}
                  />
                ) : (
                  <div class={styles.uploader}>
                    <Icon name={iconUploader} size="32" />
                    <p class={styles.uploaderText}>{this.tips}</p>
                  </div>
                )
            }}
          />
        )}
      </div>
    )
  }
})
