<template>
  <el-form
    ref="form"
    :model="caseFile"
    label-width="90px"
    class="camera-from dispatch-file-from"
  >
    <el-form-item label="照片：" class="mandatory">
      <el-upload
        class="upload-demo"
        :multiple="true"
        :limit="10"
        :before-upload="upload"
        v-model:file-list="fileList"
        :http-request="httpsApi"
        :on-preview="previewFile"
        :accept="photoFormats"
        :on-remove="handleRemove"
      >
        <el-button type="primary" :disabled="!!file">
          <el-icon><Upload /></el-icon>上传
        </el-button>
        <template v-slot:tip>
          <div class="el-upload__tip">注：可上传{{ size }}以内的{{ photoFormatDesc }}</div>
        </template>
        <template v-slot:file="{ file }">
          <div class="file" @click.stop="previewFile()">
            <div>
              <el-icon><Document /></el-icon>
              <span class="name">{{ file.name }}</span>
            </div>
            <el-icon @click.stop="removeFile(file)"><Close /></el-icon>
          </div>
        </template>
      </el-upload>
    </el-form-item>
    <!-- <el-form-item label="附件标题：" class="mandatory">
      <el-input
        v-model="caseFile.imgInfo"
        placeholder="请输入最多不能超过50字"
        maxlength="50"
        show-word-limit
      ></el-input>
    </el-form-item> -->
  </el-form>
</template>

<script setup lang="ts">
import {
  DrawFormatDesc,
  DrawFormats,
  photoFormats,
  photoFormatDesc,
  FileDrawType,
  OtherFormatDesc,
  OtherFormats,
} from "@/constant/caseFile";
import { uploadFile } from "@/store/system";
import { maxFileSize } from "@/constant/caseFile";
import { useUpload } from "@/hook/upload";
import { saveOrAndSave, CaseImg } from "@/store/case";
import { ElMessage } from "element-plus";
import { computed, ref, watch, watchEffect } from "vue";
import { QuiskExpose } from "@/helper/mount";
import type { UploadProps } from 'element-plus'

const props = defineProps<{
  caseId: number;
  data: CaseImg;
}>();

const defaultUpload = (
  file: File,
  onPercentage: (percentage: number) => void
) => {
  onPercentage(100);
};

const caseFile = ref<CaseImg>({
  caseId: props.caseId,
  id: props.data?.id,
  imgUrl: props.data.imgUrl,
  imgInfo: props.data.imgInfo,
  sort: props.data?.sort || '',
} as any);

const { size, previewFile, file, accept, percentage, format } = useUpload({
  maxSize: maxFileSize,
  formats: DrawFormats,
});

const upload = async (file: File) => {
    const fileType = file.name
      .substring(file.name.lastIndexOf("."))
      .toUpperCase();

    if (!DrawFormats.some((type) => type.toUpperCase() === fileType)) {
      ElMessage.error(`请上传${format.value}`);
      return false;
    } else if (file.size > maxFileSize) {
      ElMessage.error(`请上传${size.value}以内的文件`);
      return false;
    } else {
      console.log('file', file)
      fileList.value.push(file);
      await defaultUpload(
        file,
        (val) => (percentage.value = val)
      );
      if (fileType === ".RAW") {
      }
      percentage.value = undefined;
      return true;
    }
  };
const fileList = ref([])
const formatDesc = computed(() =>
DrawFormatDesc
);
watch(props, newValue => {
  caseFile.value.id = newValue.data.id;
  caseFile.value.imgInfo = newValue.data.imgInfo;
  caseFile.value.imgUrl = newValue.data.imgUrl;
  caseFile.value.sort = newValue.data.sort;
  if(newValue.data.imgUrl){
    file.value = {
    name: newValue.data.imgInfo || '',
    url: newValue.data.imgUrl || '',
  }
  }
},{ immediate: true })
watchEffect(() => {
  if (file.value?.name) {
    caseFile.value.imgInfo = file.value?.name.substring(0, 50);
  }
});
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
const removeFile = (file) => {
  fileList.value = fileList.value.filter((item) => item.raw.url !== file.raw.url);
};
const httpsApi = async ({file})=> {
  console.log('httpsApi', file)
  let fileUrl = await uploadFile(file);

  file.url = fileUrl
  console.log('httpsApi', file, fileUrl)
}

defineExpose<QuiskExpose>({
  async submit() {
    console.log('defineExpose', fileList.value)
    if (!fileList.value.length) {
      ElMessage.error("请上传照片");
      throw "请上传照片";
    }
    console.log('defineExpose', caseFile.value, file.value)
    let imgUrls = fileList.value.map(item => {
      return {
        imgUrl: item.raw && item.raw.url,
        imgInfo: item.name.replace(/\.[^/.]+$/, ""),
        caseId: props.caseId,
      }
    })
    await saveOrAndSave({ imgUrls });
    return caseFile.value;
  },
});
</script>

<style scoped lang="scss">
.upload-demo {
  overflow: hidden;
}

.file {
  display: flex;
  justify-content: space-between;
  align-items: center;
  > div {
    display: flex;
    align-items: center;
  }

  .name {
    margin-left: 10px;
  }
}
</style>
