import { Icon, Image, Toast, Uploader } from "vant";
import { defineComponent } from "vue";
import styles from "./index.module.less";

import iconUploader from '@common/images/icon_uploader.png';
import request from "@/helpers/request";

export default defineComponent({
  name: 'col-upload',
  props: {
    value: String,
    tips: {
      type: String,
      default: '点击上传'
    },
    deletable: {
      type: Boolean,
      default: true
    }
  },
  mounted() {
    // console.log(this.value, 'uploader');
  },
  methods: {
    beforeRead(file: any) {
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
          Toast('上传文件大小不能超过 5MB')
          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 = '上传中...';
        let formData = new FormData();
        formData.append('file', file.file);
        let res = await request.post('/api-teacher/uploadFile', {
          data: formData
        })
        this.$emit('update:value', res.data.url);
      } catch (error) {
        //
      }
    },
    onClose(e: any) {
      this.$emit('update:value', null);
      e.stopPropagation();
    },
  },
  render() {
    return (
      <div class={styles['uploader-section']}>
        {/* @ts-ignore */}
        <Uploader afterRead={this.afterRead} beforeRead={this.beforeRead} beforeDelete={this.beforeDelete}
          v-slots={{
            default: () => (this.value ? <div class={styles['img-section']} onClick={this.onClose}>
              { this.deletable ? <Icon name="cross" class={styles["img-close"]} /> : null }
              <Image fit="cover" class={styles.uploadImg} src={this.value} />
            </div> : <div class={styles.uploader}>
            <Icon name={iconUploader} size="32" />
            <p class={styles.uploaderText}>{this.tips}</p>
          </div> )
          }}
        />
      </div>
    )
  }
})