<template>
  <el-upload class="avatar-uploader" name="file" method="post" :show-file-list="false" :multiple="false"
    :auto-upload="false" :on-change="act_handleChange" :before-upload="act_beforeUpload" :file-list="fileList"
    accept="video/*">
    <!-- 视频播放 -->
    <video style="height: 300px" v-if="imageUrl" :src="imageUrl" class="avatar" controls @error="act_handleError" />

    <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>
</template>

<script setup>
/************************************************
 *                   引入文件                   *
 ************************************************/
import { ref, reactive, onMounted, defineProps, watch } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from "axios";

/************************************************
 * 全局变量
 *
 * 格式: g_ + 事件名     例如: getAppDataList
 ************************************************/
// 父组件传递过来的函数
const g_props = defineProps({
  handleUploadSuccess: Function,
  URL: String,
});

// 上传数据
const g_uploadData = {
  directory: "VRONE-VIDEO",
};

// 图片地址
const imageUrl = ref(g_props.URL ? g_props.URL.indexOf("http") == 0 ? g_props.URL : `http://${g_props.URL}` : "");
const fileList = ref([]);
const selectedFile = ref(null);
// 文件是否改变
const isFileChanged = ref(false);

/************************************************
 * 生命周期函数
 ************************************************/
// 挂载完成
onMounted(() => { });

/************************************************
 * 事件处理
 *
 * 格式: act_ + 事件名     例如: getAppDataList
 ************************************************/

// 失败触发
const act_handleError = () => {
  imageUrl.value = "";
};

// 选择文件
const act_handleChange = (file, fileList) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    imageUrl.value = e.target.result;
  };
  reader.readAsDataURL(file.raw);
  selectedFile.value = file.raw;
  isFileChanged.value = true;
};

const act_beforeUpload = (file) => {
  console.debug("act_beforeUpload:", file)
  const isLt2M = file.size / 1024 / 1024 < 9;
  if (!isLt2M) {
    ElMessageBox.alert('上传视频大小不能超过 9MB!', '错误提示');
  }
  return isLt2M; // 返回false会阻止上传
}

// 保存并上传文件
const act_uploadFiles = () => {
  return new Promise((resolve, reject) => {
    if (!selectedFile.value) {
      ElMessage.error("请选择文件");
      reject("请选择文件！");
      return;
    }

    if (selectedFile.value.size / 1024 / 1024 > 9) {
      ElMessage.error('上传视频大小不能超过 9MB!');
      reject('上传视频大小不能超过 9MB!');
      return;
    }

    const formData = new FormData();
    formData.append("file", selectedFile.value);
    formData.append("directory", g_uploadData.directory);

    axios
      .post("http://106.55.102.172:8010/user/upload", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
      .then((response) => {
        if (response.data.code == 200) {
          g_props.handleUploadSuccess(response.data.data, "video");
          resolve();
        } else {
          reject(new Error("上传失败"));
        }
      })
      .catch((error) => {
        console.error("上传失败", error);
        reject(error);
      });
  });
};

// 暴露方法供父组件调用
defineExpose({
  act_uploadFiles,
  isFileChanged,
});

/************************************************
 * 获取数据
 *
 * 格式: get_ + 事件名     例如: get_AppDataList
 ************************************************/
</script>

<style scoped>
.avatar-uploader {
  flex: 1;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

::v-deep .el-upload {
  max-height: 300px;
  border: 1px solid rgb(204 204 204);
  border-radius: 8px;
  overflow: hidden;
}

::v-deep .avatar {
  width: 100%;
}
</style>