<template>
  <el-form
    ref="form"
    :model="caseFile"
    label-width="90px"
    class="camera-from dispatch-file-from jm-file-upload"
  >
    <el-form-item label="分类：" class="mandatory">
      <el-cascader
        v-model="caseFile.filesTypeId"
        :how-all-levels="false"
        style="width: 300px;"
        :options="fileOptions"
        :props="{
          checkStrictly: false,
        }"
        clearable
      />
    </el-form-item>
    <el-form-item label="上传类别：" class="mandatory">
      <el-select
        style="width: 300px;"
        v-model="caseFile.filesType"
        placeholder="请选择上传类别"
      >
        <el-option label="本地上传" :value="1" />
        <el-option label="媒体库上传" :value="0" />
      </el-select>
      <!-- <el-cascader
        v-model="caseFile.filesTypeId"
        :how-all-levels="false"
        style="width: 300px;"
        :options="fileOptions"
        :props="{
          checkStrictly: false,
        }"
        clearable
      /> -->
    </el-form-item>
    <el-form-item label="文件：" v-if="caseFile.filesType == 1" class="mandatory uploadFile">
      <el-upload
        class="upload-demo"
        :multiple="false"
        drag
        :limit="1"
        :before-upload="upload"
        :file-list="fileList"
        :http-request="uploadNewFile"
        :on-success="handleSuccess"
        :on-preview="previewFile"
        :on-exceed="handleExceed"
        :accept="accept"
        :before-remove="removeFile"
      >
        <div type="primary" :disabled="!!file">
          <div>点击或拖拽文件上传</div>
          <div class="">{{ size }}以内的{{ formatDesc }}</div>
        </div>
        <template v-slot:file="{ file }: { file: UploadFile }">
          <div class="file" @click.stop="previewFile()">
            <div>
              <el-icon><Document /></el-icon>
              <span class="name">{{ file.name }}</span>
            </div>
            <el-icon @click.stop="removeFile()"><Close /></el-icon>
          </div>
        </template>
      </el-upload>
    </el-form-item>
    
    <el-form-item label="文件：" v-else class="mandatory uploadFile">
      <el-button  type="primary" class="mtk" @click="handleAdd"
      >从媒体库上传</el-button>
    </el-form-item>
    <div style="padding-left: 90px" v-if="caseFile.filesType == 0">
        <viewImg :list="mtkList" edit delete @handleItem="handleItem"/>
      </div>
  </el-form>
</template>

<script setup lang="ts">
import { uploadNewFile, addByMediaLiBrary } from "@/store/case";
import viewImg from "@/components/viewImg/index.vue"
import {
  DrawFormatDesc,
  DrawFormats,
  FileDrawType,
  OtherFormatDesc,
  OtherFormats,
} from "@/constant/caseFile";
import { maxFileSize } from "@/constant/caseFile";
import { useUpload } from "@/hook/upload";
import { CaseFile, addCaseFile } from "@/store/caseFile";
import { ElMessage, UploadFile } from "element-plus";
import { computed, ref, watchEffect, onMounted } from "vue";
import { addCaseScenes } from "./quisk";
import { QuiskExpose } from "@/helper/mount";
import { updateSelectByTreeFileLists } from "@/store/case";

const props = defineProps<{
  caseId: number;
  fileType: number;
  filesTypeName: [string];
  fileInfo?: Object;
}>();
const fileOptions = ref([])
const mtkList = ref([]);
onMounted(async () => {
  let newfileOptions = await updateSelectByTreeFileLists();
  if(props.filesTypeName){
    let newChildren = newfileOptions
    props.filesTypeName.map(ele => {
      newChildren = newChildren.find((item) => item.label == ele).children || []
    })
    fileOptions.value = newChildren
    // fileOptions.value = newfileOptions.find((item) => item.label == props.filesTypeName).children || [];
  } else {
    fileOptions.value = newfileOptions;
  }
  console.log('fileOptions', fileOptions.value, newfileOptions);
});

const caseFile = ref({
  caseId: props.caseId,
  filesTypeId: props.fileType,
  filesTitle: "",
  dictId: '',
  uploadId: '',
  filesType: 1,
});
console.log('caseFile', props.fileInfo);
const { size, fileList, upload, removeFile, previewFile, file, accept } = useUpload({
  maxSize: props.fileInfo?.fileSize || 50 * 1024 * 1024,
  formats: props.fileInfo?.formats || [".jpg", ".jpeg", ".png"],
});

const formatDesc = computed(() => {
  return props.fileInfo?.DrawFormatDesc||'jpg、png、jpeg上传'
});

// 上传请求
const handleSuccess = (option) => {
  console.log('handleSuccess', option);
}
const handleExceed = (option) => {
  ElMessage.error("只能上传1个文件！");
}

const handleAdd = async () => {
  let fileId =  await addCaseScenes({formats: props.fileInfo?.formats || [".jpg", ".jpeg", ".png"]});
  if(fileId == false || fileId && fileId.length == 0 ){
    return
  }
  mtkList.value = fileId.map(ele => {
    return {
      filesUrl: ele.fileUrl,
      ...ele,
     }
  }) || [];
  console.log("handleItem", mtkList.value);
};
const handleItem = (type, item) => {
  console.log("handleItem", type, item);
  if(type == 'delete'){
    mtkList.value = mtkList.value.filter(ele => ele.id != item.id)
  }
};
watchEffect(() => {
  console.log('file', file.value);
  if (file.value?.name) {
    caseFile.value.uploadId = file.value?.response?.data.id
  }
});

defineExpose<QuiskExpose>({
  async submit() {
    let filesTypeId = caseFile.value.filesTypeId && Array.isArray(caseFile.value.filesTypeId)?caseFile.value.filesTypeId.slice(-1):caseFile.value.filesTypeId
    if (!file.value && caseFile.value.filesType == 1 || caseFile.value.filesType == 0 && mtkList.value.length == 0) {
      ElMessage.error("请上传文件");
      throw "请上传文件";
    } else if (!filesTypeId) {
      ElMessage.error("文件分类不能为空！");
      throw "文件分类不能为空！";
    }
    let uploadId = file.value?.response?.data.id,
    uploadIds = mtkList.value.map(ele => ele.uploadId) || [];
    let params = { ...caseFile.value, file: file.value, filesTypeId: filesTypeId[0] };
    if(caseFile.value.filesType == 1) params.uploadId = uploadId;
    if(caseFile.value.filesType == 0) params.uploadIds = uploadIds;
    await addByMediaLiBrary(params);
    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;
  }
}
.jm-file-upload {
  // .mtk {
  //   position: absolute;
  //   right: 0;
  //   top: 0;
  // }
}
</style>
