<script setup lang="ts">
import {
  ElUpload,
  ElForm,
  ElFormItem,
  ElRadioGroup,
  ElRadio,
  ElTreeSelect,
  ElInput,
  ElMessage
} from 'element-plus'
import type { UploadInstance } from 'element-plus'
import { reactive, ref, watch } from 'vue'
import { Dialog } from '@/components/Dialog'
import { useValidator } from '@/hooks/web/useValidator'
import { getFileType, upOnlineFile } from '@/api/system/file'
import { REQUEST_BASE } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
const userStore = useUserStoreWithOut()

const modelValue = defineModel<boolean>()
const props = defineProps({
  fileType: {
    type: Number,
    default: 1
  }
})

const { required } = useValidator()

const emit = defineEmits(['confirm'])

const rules = reactive({
  label: [required()],
  value: [required()]
})

const getFileTypeList = () => {
  getFileType({
    file_type: props.fileType
  }).then((res) => {
    fileTypeList.value = [
      {
        label: props.fileType == 1 ? '全部图片' : '全部视频',
        value: 0,
        children: []
      }
    ]
    fileTypeList.value.push(
      ...res.data.list.map(function functionMap(item) {
        return {
          label: item.name,
          value: item.id,
          children: item.children ? item.children.map(functionMap) : []
        }
      })
    )
  })
}
watch(
  () => props.fileType,
  () => {
    getFileTypeList()
  },
  { immediate: true }
)
watch(modelValue, () => {
  form.fileList = []
})

const fileTypeList = ref<any[]>([])
const form = reactive({
  pid: 0, //上传分类id
  images: '', //上传图片链接地址
  type: '1', //保存类型1文件2链接地址
  fileList: []
})
const uploadImage = ref<UploadInstance>()
const uploadVideo = ref<UploadInstance>()
const saveLoading = ref(false)
const uploadFileNum = ref(0)
// 判断是否为图片链接的函数
const isImageUrl = (url: string): boolean => {
  if (!url) return false
  
  // 检查是否为有效的URL格式
  try {
    new URL(url)
  } catch {
    return false
  }
  
  // 常见的图片扩展名
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg', '.ico']
  
  // 检查URL路径是否以图片扩展名结尾（不区分大小写）
  const lowerCaseUrl = url.toLowerCase()
  return imageExtensions.some(ext => lowerCaseUrl.includes(ext))
}
// 判断是否为视频链接的函数
const isVideoUrl = (url: string): boolean => {
  if (!url) return false
  
  // 检查是否为有效的URL格式
  try {
    new URL(url)
  } catch {
    return false
  }
  
  // 常见的视频扩展名
  const videoExtensions = ['.mp4', '.avi', '.mov', '.wmv', '.flv', '.mkv', '.webm', '.mpeg', '.mpg']
  
  // 检查URL路径是否以视频扩展名结尾（不区分大小写）
  const lowerCaseUrl = url.toLowerCase()
  return videoExtensions.some(ext => lowerCaseUrl.includes(ext))
}
const confirm = async () => {
  console.log(form.fileList, 'form.fileList')
  saveLoading.value = true
  // 判断是否本地上传
  if (form.type == '1') {
    if (props.fileType == 1) {
      uploadImage.value!.submit()
    } else if (props.fileType == 2) {
      uploadVideo.value!.submit()
    }
    return
  }
  if (form.type == '2') {
    if (props.fileType === 1 && !isImageUrl(form.images)) {
      ElMessage.error('请输入有效的图片链接地址')
      saveLoading.value = false
      return
    }
    if (props.fileType === 2 && !isVideoUrl(form.images)) {
      ElMessage.error('请输入有效的视频链接地址')
      saveLoading.value = false
      return
    }
    const re = await upOnlineFile({ pid: form.pid, images: form.images })
    if (re) {
      uploadFileNum.value = 0
      modelValue.value = false
      ElMessage.success('提交成功')
      saveLoading.value = false
      form.fileList = []
      emit('confirm')
    } else {
      saveLoading.value = false
    }
    return
  }

  // const elFormExpose = await getElFormExpose()
  // if (!elFormExpose) return
  // const valid = await elFormExpose?.validate().catch((err) => {
  //   console.log(err)
  // })
  // if (valid) {
  //   const formData = await getFormData()
  //   formData.id = Date.now()
  //   emit('confirm', formData)
  //   setValues({
  //     label: '',
  //     value: ''
  //   })
  //   modelValue.value = false
  // }
}
const successUpLoad = () => {
  uploadFileNum.value++
  if (uploadFileNum.value == form.fileList.length) {
    saveLoading.value = false
    uploadFileNum.value = 0
    form.fileList = []
    modelValue.value = false
    ElMessage.success('上传成功')
    emit('confirm')
  }
}
</script>

<template>
  <Dialog v-model="modelValue" :title="fileType == 1 ? '上传图片' : '上传视频'" width="600px">
    <template #default>
      <ElForm
        :rules="rules"
        :model="form"
        label-width="auto"
        v-loading="saveLoading"
        element-loading-text="上传中..."
        style="max-width: 600px"
      >
        <el-form-item label="上传方式:">
          <el-radio-group v-model="form.type">
            <el-radio value="1">本地上传</el-radio>
            <el-radio value="2">网络上传</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传至分组:">
          <el-tree-select
            v-model="form.pid"
            :data="fileTypeList"
            check-strictly
            no-data-text="暂无数据"
            :placeholder="fileType == 1 ? '全部图片' : '全部视频'"
            :render-after-expand="false"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="链接地址:" v-if="form.type == '2'">
          <ElInput v-model="form.images" placeholder="请输入链接地址" />
        </el-form-item>
        <el-form-item label="上传图片:" v-show="form.type == '1' && fileType == 1">
          <ElUpload
            ref="uploadImage"
            class="mt-10px"
            @success="successUpLoad"
            multiple
            :action="`${REQUEST_BASE}/file/upload/0`"
            listType="picture-card"
            v-model:file-list="form.fileList"
            accept="image/jpeg,image/png,image/gif,image/jpg,ico"
            :auto-upload="false"
            :data="{
              pid: form.pid
            }"
            :headers="{
              'Authori-Zation': userStore.getTokenKey + userStore.getToken
            }"
          >
            <Icon :size="40" icon="vi-ep:plus" />
            <template #tip>
              <div class="el-upload__tip"
                >建议上传图片最大宽度750px，不超过2MB；仅支持jpeg、png格式，可拖拽调整上传顺序</div
              >
            </template>
          </ElUpload>
        </el-form-item>
        <el-form-item label="上传视频:" v-if="form.type == '1' && fileType == 2">
          <ElUpload
            ref="uploadVideo"
            :action="`${REQUEST_BASE}/file/upload/0`"
            multiple
            v-model:file-list="form.fileList"
            @success="successUpLoad"
            accept="audio/mpeg,.wma,.wav, video/mp4"
            :auto-upload="false"
            :data="{
              pid: form.pid
            }"
            :headers="{
              'Authori-Zation': userStore.getTokenKey + userStore.getToken
            }"
          >
            <BaseButton>上传视频</BaseButton>
            <template #tip>
              <div class="el-upload__tip">仅支持mp4、mpeg格式</div>
            </template>
          </ElUpload>
        </el-form-item>
      </ElForm>
    </template>
    <template #footer>
      <div>
        <BaseButton @click="() => (modelValue = false)">取消</BaseButton>
        <BaseButton type="primary" :loading="saveLoading" @click="confirm">确认</BaseButton>
      </div>
    </template>
  </Dialog>
</template>
<style lang="less" scoped>
:deep(.el-upload-list) {
  &.el-upload-list--picture-card {
    .el-upload-list__item {
      width: 80px;
      height: 80px;
    }
    .el-upload--picture-card {
      width: 80px;
      height: 80px;
    }
  }
}
</style>
