import { ref } from "vue";
import { uploadFile } from '@/api/file';
import { loading as showLoading, hideLoading, toast } from '@/utils/widget'

const BusinessType = {
  order: 'consult_order', // 咨询订单
  chat: 'chat_message', // 聊天消息
  other: 'other' // 其他
}

/**
 * 图片上传hook
 * @param {*} maxCount 
 * @returns 
 */
export default function useImageUpload(type, maxCount = 1) {
  const images = ref([])
  const businessType = BusinessType[type] || '';
  const tempPaths = [];

  if (!businessType) {
    toast('无效的businessType')
  }

  function add() {
    if (!businessType) {
      toast(`无效的businessType`)
      return
    }
    if (images.value.length > maxCount) {
      toast('最多上传' + maxCount + '张图片')
      return
    }
    uni.chooseMedia({
      count: maxCount - images.value.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],
      success: (res) => {
        const tempFilePaths = res.tempFiles.map(item => item.tempFilePath);
        images.value = [...images.value, ...tempFilePaths];
        tempPaths.push(...tempFilePaths);
      }
    })
  }

  function remove(index) {
    images.value.splice(index, 1)
  }

  async function uploadImages() {
    const uploadPaths = images.value.filter(i => tempPaths.includes(i));
    showLoading('正在上传图片...')
    const res = await Promise.all(uploadPaths.map(uploadImage));
    let failCount = 0;
    uploadPaths.forEach((path, idx) => {
      const index = images.value.findIndex(i => i === path && path);
      const url = typeof res[idx] === 'string' && res[idx].trim() ? res[idx] : '';
	  if(url && index >= 0) {
		  images.value[index] = url;
	  } else if(!url) {
		 failCount++;
	  }
    })
    hideLoading()
    toast(failCount ? `${failCount}张图片上传失败` : '图片上传成功')
    return failCount === 0
  }

  async function uploadImage(path) {
    const res = await uploadFile(path, businessType);
    return res ? res.previewUrl : '';
  }

  return { images, add, remove, uploadImage, uploadImages }
}