<script setup>
import { ElMessage, genFileId } from 'element-plus'
import { ref, useAttrs, watch } from 'vue'
// import { REQUEST } from '~/utils/request';
import { getFullUrl, getPartUrl } from '~/utils/helper'
import { user } from '~/store/index'

const props = defineProps({
  part: String,
  full: String,
  list: Array,
  // kb
  sizeLimit: Number,
  size: String,
  time: String,
  picType: String,
  aliyun: String,
})
const emit = defineEmits([
  'update:part',
  'update:full',
  'update:size',
  'update:time',
  'compile',
  'update:list',
])
const uploadLoading = ref(false);
const token = user.value?.token
const action = `${window.GLOBAL_CONFIG.api}/upload/main/file`

const upload = ref()

const data = {
  token,
  client: 'web',
  api: 'json',
  issubmit: '1',
  site: 'aimk',
  urltype: '1',
  aliyun_oss: props.aliyun
}
const attrs = useAttrs()

const List_part = ref(props.part)
const List_full = ref(props.full)
// const List_size = ref(props.size ? parseFloat(props.size) : 0)
const List_size = ref(0)
const List_time = ref(props.time ?? new Date().toLocaleString())
const playTime = ref(0)

const FILE_LIST = ref([])
function init() {
  FILE_LIST.value = []
  if (
    List_part.value !== undefined
    && List_part.value !== ''
    && List_part.value !== null
  ) {
    FILE_LIST.value = List_part.value.split(';').map((part_url, idx) => ({
      part_url: getPartUrl(part_url),
      url: getFullUrl(part_url),
      // _status: 1,
      // uid: Date.now() - idx,
      name: part_url.split('/').pop(),
    }))
  }
  if (
    List_full.value !== undefined
    && List_full.value !== ''
    && List_full.value !== null
  ) {
    FILE_LIST.value = List_full.value.split(';').map((item, idx) => {
      const [part_url, name, filesize] = item.split('|')
      return {
        part_url: getPartUrl(part_url),
        url: getFullUrl(part_url),
        // _status: 1,
        name,
        filesize,
        // uid: Date.now() - idx
      }
    })
  }
  console.log('* init :>> ', FILE_LIST.value)
}
init()

watch(
  () => [props.part, props.full],
  (n, o) => {
    List_part.value = props.part
    List_full.value = props.full
    init()
  },
)
/**
 * const STATUS_MAP = {
 *   0: 'READY',
 *   1: 'SUCCESS',
 *   2: 'FAIL'
 * }
 */
const isPicture = ref(props.picType)
function beforeUpload(file) {
  const url = URL.createObjectURL(file)
  const audioElement = new Audio(url)
  audioElement.addEventListener('loadedmetadata', () => {
    playTime.value = audioElement.duration // playTime就是当前视频长度
  })

  if (props.sizeLimit) {
    const isLtSize = file.size / 1024 < props.sizeLimit
    if (['png', 'jpg', 'jpeg'].includes(file.name?.split('.').at(-1)))
      isPicture.value = 'picture'

    if (
      ['mp4', 'ppt', 'pptx', 'xls', 'xlsx'].includes(
        file.name?.split('.').at(-1),
      )
    )
      isPicture.value = 'text'

    if (!isLtSize)
      ElMessage.warning(`上传文件大小不能超过 ${props.sizeLimit}KB!`)

    return isLtSize
  }
}

function handleSuccess() {
  console.log(
    'handleSuccess :>> ',
    FILE_LIST.value.map(e => e.status),
    FILE_LIST.value,
  )
  if (FILE_LIST.value.every(item => item.status === 'success')) {
    const part = []
    const full = []
    FILE_LIST.value.forEach((item) => {
      if (playTime.value)
        item.playTime = playTime.value

      if (item.percentage === 100) {
        const { url: part_url, file_name, filesize } = item.response.data
        part.push(part_url)
        full.push(`${part_url}|${file_name}|${filesize}`)
        List_size.value += item.size ?? 0
      }
      else {
        part.push(item.part_url)
        full.push(`${item.url}|${item.name}|${item.filesize}`)
        List_size.value += item.size ?? 0
      }
    })
    emit('update:list', part)

    List_full.value = full.join(';')
    List_part.value = part.join(';')
    List_time.value = new Date().toLocaleString()
  }
}

function onRemove(file, fileList) {
  FILE_LIST.value = fileList
  handleSuccess()
}
function onExceed(files) {
  // ElMessage.warning(`最多允许上传${attrs.limit}个文件`);
  upload.value?.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value?.handleStart(file)
  upload.value?.submit()
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
function handlePictureCardPreview(uploadFile) {
  if (['png', 'jpg', 'jpeg'].includes(uploadFile.url?.split('.').at(-1))) {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
  }
}

/// <summary>
/// 格式化文件大小的JS方法
/// </summary>
/// <param name="filesize">文件的大小,传入的是一个bytes为单位的参数</param>
/// <returns>格式化后的值</returns>
function renderSize(filesize) {
  // const unitArr = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
  // const index = Math.floor(Math.log(filesize) / Math.log(1024));
  // const size = (filesize / Math.pow(1024, index)).toFixed(2);
  // return size + unitArr[index];
  return (filesize / 1024).toString()
}

watch(
  () => List_part.value,
  () => {
    emit('update:part', List_part.value)
    emit('update:full', List_full.value)
    emit('update:size', renderSize(List_size.value))
    emit('update:time', List_time.value)
    emit('compile', FILE_LIST.value)
    console.log('compile')
  },
)
</script>

<template>
  <!-- :on-preview="handlePictureCardPreview" -->
  <el-upload ref="upload" v-loading="uploadLoading" v-model:file-list="FILE_LIST" :action="action" :data="data" name="filedata" :on-success="handleSuccess" :on-remove="onRemove" :list-type="isPicture" :on-exceed="onExceed" :before-upload="beforeUpload" :on-preview="handlePictureCardPreview" v-bind="attrs" class="w-full">
    <template #default>
      <slot>
        <el-button type="primary">
          点击上传
        </el-button>
      </slot>
    </template>
    <template #tip>
      <slot name="tip" />
    </template>
    <template #file>
      <slot name="file" />
    </template>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image">
  </el-dialog>
</template>
