<template>
  <el-upload
    ref="uploadRef"
    class="upload-demo w-full"
    :action="'/api/copyright/upload?file_type=' + suffixName"
    :auto-upload="false"
    :headers="{
      Authorization: 'Bearer ' + getLoginCode(),
    }"
    name="file_data"
    accept=".png,.jpg,.jpeg,.gif,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.mp3,.wma,.wav,.amr,.m4a,.wmv,.asf,.asx,.rm,.rmvb,.mpg,.mpeg,.mp4,.3gp,.mov,.m4v,.avi,.mkv,.flv,.vob"
    :limit="1"
    :file-list="(modelValue && [modelValue]) || []"
    @change="handleFileChange"
    @remove="handleFileRemove"
    :before-upload="beforeUpload"
    :on-success="handleSuccess"
    :on-error="handleError"
  >
    <template #trigger>
      <div
        class="uploadbox flex items-center justify-center"
        :class="{
          ' cursor-not-allowed': !!modelValue,
        }"
      >
        <div>
          <Icon
            icon-name="iconshangchuan"
            style="color: #c3c3c3; font-size: 56px"
          ></Icon>
          <div style="font-size: 14px; font-weight: 500; color: #787d85">
            上传文件
          </div>
        </div>
      </div>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import { ElUpload, UploadFile, UploadProps, useFormItem } from "element-plus";
import type { UploadInstance } from "element-plus";
import { ref } from "vue";
import Icon from "@/components/Icon/index.vue";
import { getSuffixName } from "@/utils/file";
import { copyrightUploadFile } from "@/service/copyrightService";
import { getLoginCode } from "cqk-sy-ui";

const suffixName = ref("");
const uploadRef = ref<UploadInstance>();
const list = ref([]);
const props = defineProps<{
  modelValue?: UploadFile;
}>();

const { formItem } = useFormItem();

const emit = defineEmits(["update:modelValue"]);

const handleFileChange = async (uploadFile: UploadFile) => {
  const ret = await copyrightUploadFile(uploadFile.raw!);
  emit("update:modelValue", {
    ...ret.data,
    name: uploadFile.name,
  });
  formItem?.validate("change");
};
const handleFileRemove = () => {
  console.log("remove");
  emit("update:modelValue", undefined);
  formItem?.validate("change");
};

const beforeUpload: UploadProps["beforeUpload"] = (rawFile) => {
  suffixName.value = getSuffixName(rawFile.name);
};

const handleSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile,
  uploadFiles
) => {
  console.log(response);
};

const handleError: UploadProps["onError"] = (res) => {
  console.log(res, "show res in error");
};
</script>

<style lang="scss" scoped>
.upload-demo {
  :deep(.el-upload-list__item-name) {
    font-size: 14px;
    font-weight: 400;
    color: var(--sy-blue);
  }
}
.uploadbox {
  width: 249px;
  height: 139px;
  background: #f7f7f7;
  border-radius: 10px;
  border: 1px solid #e2e2e2;
}
</style>
