<script setup lang="ts">
import { computed, ref } from 'vue';
import { showToast, Toast } from 'vant';

import type { IQuestion } from '@/types/question';

const isPreview = defineModel('isPreview', { default: false, type: Boolean, required: false });
// 题目
const question = defineModel<IQuestion<IFileUploadConfig>>('element', {
  required: true
});

const props = defineProps<{
  index: number | String;
  active: boolean;
}>();
const { config } = question.value;

// 答案
const answer = ref<FileList | []>([]);
/**
 * 文件限制, 跟上层接口适配
 * @property {number} max - 最大文件大小
 * @property {number} min - 最小文件大小
 */
const fileLimit = computed(() => {
  return {
    // 默认4MB
    maxFileSize: (config!.max_size ?? 9999) * 1024 * 1024,
    minFileSize: (config!.min_size ?? 0) * 1024 * 1024,
    maxFileCount: config!.max_number ?? 9999,
    minFileCount: config!.min_number ?? 1,
    format: [] // ['jpg', 'jpeg', 'png', 'gif']
  };
});

/**
 * 上传文件
 * @description 上传文件
 */
function handleFileUpload() {
  const fileInput = document.createElement('input');
  fileInput.type = 'file';
  // 文件类型限制
  fileInput.accept = fileLimit.value.format.join(',');
  // 是否限制多选
  fileInput.multiple = fileLimit.value.minFileCount <= 1;
  fileInput.click();

  fileInput.addEventListener('change', handleFileChange);

  function handleFileChange(event: Event) {
    const files = (event.target as HTMLInputElement).files;
    if (files) {
      // 检测文件数量
      if (files.length > 1 && fileLimit.value.minFileCount <= 1) {
        showToast('一次只能上传一个文件');
        return;
      }
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        // console.log(file.size);

        // 文件限制
        if (file.size > fileLimit.value.maxFileSize) {
          showToast(`文件太大，超过${fileLimit.value.maxFileSize / 1024 / 1024}MB`);
          return;
        } else if (file.size < fileLimit.value.minFileSize) {
          showToast(`文件太小，小于${fileLimit.value.minFileSize / 1024 / 1024}MB`);
          return;
        }
      }

      // 上传文件

      // 生成答案
      question.value.answer = files;
    }
  }
}

const errorMessage = defineModel('errorMessage', {
  type: String,
  default: ''
});

const emit = defineEmits(['update:element']);
const emitValue = () => {
  emit('update:element', question.value);
};
</script>

<template>
  <van-cell-group>
    <van-field
      v-model="question.stem"
      :label="question.stem"
      :required="question?.config?.is_required === 1"
      label-align="top"
      input-align="center"
      class="contenteditable-question-title"
    >
      <template #left-icon> {{ question.title }}.</template>
      <!-- 使用 title 插槽来自定义标题 -->
      <template #label>
        <contenteditable
          v-model="question.stem"
          :active="active"
          @blur="emitValue"
          className="contenteditable-label"
          :errorMessage="errorMessage"
        ></contenteditable>
      </template>

      <template #input>
        <div class="file-upload-label" @click="handleFileUpload">
          <van-icon class-prefix="mobilefont" name="upload" />
          <span class="ml10">{{ answer.length > 0 ? '文件已上传' : '文件上传' }}</span>
        </div>
      </template>
    </van-field>
  </van-cell-group>
</template>

<style lang="scss" scoped>
.file-upload-label {
  //display: flex;
  //flex-direction: column;
  //align-items: center;
  //justify-content: center;

  //width: 100%;
  //height: 50px;
  margin: 45px 0;
  padding: 8px 12px;
  border: 1px dashed #979797;
  border-radius: 8px;
  color: #666;

  //gap: 10px;
  font-size: 14px;
  text-align: center;
}
</style>
