<template>
  <div class="upload-component">
    <wd-upload
      v-model:file-list="fileList"
      image-mode="aspectFill"
      :upload-method="
        createCustomUpload({
          attmodel,
          attpath,
          modelStats,
        })
      "
      :rules="[{ required, message }]"
      :limit="limit"
      :before-upload="beforeUpload"
      @remove="handleRemove"
    ></wd-upload>
    <div class="tips mt-2" v-if="tips">
      <wd-text type="warning" :text="tips"></wd-text>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { useUserStore } from '@/store/user'
import { useMessage } from 'wot-design-uni'
import { uploadFile } from '@/hooks/useUpload'

// 定义类型
interface FileItem {
  url: string
  id: string
}

const props = defineProps({
  // 外部传入的文件列表
  modelValue: {
    type: Array,
    default: () => [],
  },
  // 存放文件ID的数组
  fileIds: {
    type: Array as () => FileItem[],
    default: () => [],
  },
  // attlsh 关联的ID
  attlsh: {
    type: String,
    default: '',
  },
  // 上传配置
  attmodel: {
    type: String,
    required: true,
  },
  // 上传路径
  attpath: {
    type: String,
    required: true,
  },
  // 存放文件ID的数组
  modelStats: {
    type: String,
    required: true,
  },
  // 验证配置
  required: {
    type: Boolean,
    default: true,
  },
  // 验证提示
  message: {
    type: String,
    default: '请上传文件',
  },
  // 上传数量限制
  limit: {
    type: Number,
    default: 1,
  },
  // 提示信息
  tips: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['update:modelValue', 'update:fileIds'])

const userStore = useUserStore()
const messageService = useMessage() // 重命名变量以避免冲突
const fileList = ref([])

// 监听外部传入的文件列表变化
watch(
  () => props.modelValue,
  (newVal) => {
    fileList.value = newVal
  },
  { deep: true },
)

// 监听组件内部文件列表变化
watch(
  () => fileList.value,
  (newVal) => {
    emit('update:modelValue', newVal)
  },
  { deep: true },
)

// 上传前验证
function beforeUpload({ files, resolve }) {
  // 判断是否完善了个人信息
  // if (!userStore.isAuthComplete) {
  //   handleAuthComplete()
  //   return
  // }
  resolve(true)
}

// 创建自定义上传方法
function createCustomUpload({ attmodel, attpath, modelStats }) {
  return async function (file, formData, options) {
    const requestFromData: {
      attmodel: string
      attpath: string
      attlsh?: string
    } = {
      attmodel,
      attpath,
    }

    if (props.attlsh) {
      requestFromData.attlsh = props.attlsh
    }

    const loading = ref(false)
    const error = ref(false)
    const data = ref<any>()

    await uploadFile({
      tempFilePath: file.url,
      formData: requestFromData,
      data,
      error,
      loading,
    })

    if (!error.value) {
      options.onSuccess('', file, formData)
      // {"Status":0,"Data":"2025041016044040627399","Message":"执行成功","OtherData":"https://dzapi.kdboss.cn/upfile/orders_invoice/20250410/2025041016044040731543.png"}
      const dataObject = JSON.parse(data.value)
      const newFileIds = [...props.fileIds]
      newFileIds.push({
        url: file.url,
        id: dataObject.Data,
      })
      emit('update:fileIds', newFileIds)
    }
  }
}

// 删除文件时，删除ids数组数据
function handleRemove({ file }) {
  const newFileIds = props.fileIds.filter((item: FileItem) => item.url !== file.url)
  emit('update:fileIds', newFileIds)
}

// // 完善资料提示
// function handleAuthComplete() {
//   messageService
//     .confirm({
//       msg: '您还未完善个人信息, 请先完善信息',
//       title: '提示',
//       confirmButtonText: '去完善',
//       cancelButtonText: '继续浏览',
//     })
//     .then(() => {
//       uni.navigateTo({
//         url: '/pages-sub/user/index',
//       })
//     })
//     .catch(() => {
//       // ...
//     })
// }
</script>

<style lang="scss" scoped>
.upload-component {
  width: 100%;
}
</style>
