import { getApiLoading } from '@/common/libraries/apiLoading'
import { Apis } from '@/gen/Apis'
import useModel from './model'
import { useWeAppAuthStore } from '@/common'
const auth = useWeAppAuthStore()
import { showToast } from '@/common/libraries/naviHelper'
import {
  shareToExternalMoments,
  shareToExternalContactTask,
  shareToExternalChatTask
} from '@/common/libraries/sendWxWork'

const onUploadMedia = async (data: any) => {
  // let res = await Apis.Customer.CustomerMoments.UploadMedia(data)
  // return res?.data
}

const uploadAttachmentsSequentially = async (
  attachments: Array<{ url: string }>,
  type = 'image'
): Promise<Array<any>> => {
  const result: Array<any> = []
  // 显示加载提示

  try {
    // 使用for...of循环保证按顺序阻塞执行
    for (const res of attachments) {
      uni.showLoading({
        title: '正在准备素材...',
        mask: true
      })
      let json: any = await Apis.Customer.CustomerMoments.UploadMedia({
        type: type,
        path: res?.url
      })
      result.push({ msgtype: type, [type]: { mediaid: json?.data?.media_id } })
      console.log(json, 'data')
    }
  } catch (error) {
    console.error('上传素材失败:', error)
    showToast('上传素材失败')
    throw error // 抛出错误让调用者处理
  } finally {
    // 隐藏加载提示
    uni.hideLoading()
  }
  return result
}

export default {
  getCustomerMomentsShow(id: number) {
    getApiLoading(Apis.Customer.CustomerMoments.Show, { id }).then(res => {
      if (res?.data?.customer_moment_tasks?.length) {
        useModel.status.value = res?.data?.customer_moment_tasks[0]?.status
      }
      useModel.showData.value = res.data
      console.log(res)
    })
  },
  async handleMomentCorpSend() {
    if (auth?.data?.environment === 'wxwork') {
      if (useModel?.showData?.value?.channel === 'MomentCorp') {
        //发朋友圈
        if (useModel?.showData?.value?.content_type === 'Link') {
          shareToExternalMoments(
            {
              content: useModel?.showData?.value?.content,
              attachments: [
                {
                  msgtype: 'link', // 消息类型，必填
                  link: {
                    title: useModel?.showData?.value?.title, // H5消息标题
                    imgUrl: useModel?.showData?.value?.cover_image?.[0]?.url, // H5消息封面图片URL
                    url: useModel?.showData?.value?.skip_url // H5消息页面url 必填
                  }
                }
              ]
            },
            useModel?.formData?.value
          )
          return false
        }

        if (useModel?.showData?.value?.content_type === 'Image') {
          uni.showLoading({
            title: '准备资料中...',
            mask: true
          })
          let attachments_media: any = []
          useModel?.showData?.value?.attachments_media?.map((res: any) => {
            attachments_media?.push({
              msgtype: 'image', // 消息类型，必填
              image: {
                mediaid: res?.media_id // 图片的media_id，必填
              }
            })
          })
          shareToExternalMoments(
            {
              content: useModel?.showData?.value?.content,
              attachments: attachments_media
            },
            useModel?.formData?.value
          )
          setTimeout(() => {
            uni.hideLoading()
          }, 1000)
          return false
        }

        if (useModel?.showData?.value?.content_type === 'Video') {
          uni.showLoading({
            title: '准备资料中...',
            mask: true
          })
          let attachments_media: any = []
          useModel?.showData?.value?.attachments_media?.map((res: any) => {
            attachments_media?.push({
              msgtype: 'video', // 消息类型，必填
              video: {
                mediaid: res?.media_id // 图片的media_id，必填
              }
            })
          })
          shareToExternalMoments(
            {
              content: useModel?.showData?.value?.content,
              attachments: attachments_media
            },
            useModel?.formData?.value
          )
          setTimeout(() => {
            uni.hideLoading()
          }, 1000)
          return false
        }
      }
    } else {
      showToast('请在企业微信中操作!')
    }
  },
  async handleCustomerDirectCorpSend() {
    if (auth?.data?.environment === 'wxwork') {
      //任务发送1对1群发客户
      if (useModel?.showData?.value?.content_type === 'MiniProgram') {
        shareToExternalContactTask(
          {
            content: useModel?.showData?.value?.content,
            attachments: [
              {
                msgtype: 'miniprogram', // 消息类型，必填
                miniprogram: {
                  appid: useModel?.showData?.value?.mini_program_app_id,
                  title: useModel?.showData?.value?.title, // 消息标题
                  imgUrl: useModel?.showData?.value?.cover_image?.[0]?.url, // H5消息封面图片URL
                  page: useModel?.showData?.value?.skip_url // 消息页面url 必填
                }
              }
            ]
          },
          useModel?.formData?.value
        )
      }
      if (useModel?.showData?.value?.content_type === 'Link') {
        shareToExternalContactTask(
          {
            content: useModel?.showData?.value?.content,
            attachments: [
              {
                msgtype: 'link', // 消息类型，必填
                link: {
                  title: useModel?.showData?.value?.title, // H5消息标题
                  imgUrl: useModel?.showData?.value?.cover_image?.[0]?.url, // H5消息封面图片URL
                  url: useModel?.showData?.value?.skip_url // H5消息页面url 必填
                }
              }
            ]
          },
          useModel?.formData?.value
        )
      }
      if (useModel?.showData?.value?.content_type === 'Image') {
        uni.showLoading({
          title: '准备资料中...',
          mask: true
        })
        let attachments_media: any = []
        useModel?.showData?.value?.attachments_media?.map((res: any) => {
          attachments_media?.push({
            msgtype: 'image', // 消息类型，必填
            image: {
              mediaid: res?.media_id // 图片的media_id，必填
            }
          })
        })
        shareToExternalContactTask(
          {
            content: useModel?.showData?.value?.content,
            attachments: attachments_media
          },
          useModel?.formData?.value
        )
        setTimeout(() => {
          uni.hideLoading()
        }, 1000)
        return false
      }
      if (useModel?.showData?.value?.content_type === 'Video') {
        uni.showLoading({
          title: '准备资料中...',
          mask: true
        })
        let attachments_media: any = []
        useModel?.showData?.value?.attachments_media?.map((res: any) => {
          attachments_media?.push({
            msgtype: 'video', // 消息类型，必填
            video: {
              mediaid: res?.media_id // 图片的media_id，必填
            }
          })
        })
        shareToExternalContactTask(
          {
            content: useModel?.showData?.value?.content,
            attachments: attachments_media
          },
          useModel?.formData?.value
        )
        setTimeout(() => {
          uni.hideLoading()
        }, 1000)
        return false
      }
    } else {
      showToast('请在企业微信中操作!')
    }
  },
  async handleCustomerGroupCorpSend() {
    //群发助手发送客户群
    if (auth?.data?.environment === 'wxwork') {
      if (useModel?.showData?.value?.content_type === 'MiniProgram') {
        shareToExternalChatTask(
          {
            content: useModel?.showData?.value?.content,
            attachments: [
              {
                msgtype: 'miniprogram', // 消息类型，必填
                miniprogram: {
                  appid: useModel?.showData?.value?.mini_program_app_id,
                  title: useModel?.showData?.value?.title, // 消息标题
                  imgUrl: useModel?.showData?.value?.cover_image?.[0]?.url, // H5消息封面图片URL
                  page: useModel?.showData?.value?.skip_url // 消息页面url 必填
                }
              }
            ]
          },
          useModel?.formData?.value
        )
      }
      if (useModel?.showData?.value?.content_type === 'Link') {
        shareToExternalChatTask(
          {
            content: useModel?.showData?.value?.content,
            attachments: [
              {
                msgtype: 'link', // 消息类型，必填
                link: {
                  title: useModel?.showData?.value?.title, // H5消息标题
                  imgUrl: useModel?.showData?.value?.cover_image?.[0]?.url, // H5消息封面图片URL
                  url: useModel?.showData?.value?.skip_url // H5消息页面url 必填
                }
              }
            ]
          },
          useModel?.formData?.value
        )
      }
      if (useModel?.showData?.value?.content_type === 'Image') {
        uni.showLoading({
          title: '准备资料中...',
          mask: true
        })
        let attachments_media: any = []
        useModel?.showData?.value?.attachments_media?.map((res: any) => {
          attachments_media?.push({
            msgtype: 'image', // 消息类型，必填
            image: {
              mediaid: res?.media_id // 图片的media_id，必填
            }
          })
        })
        shareToExternalChatTask(
          {
            content: useModel?.showData?.value?.content,
            attachments: attachments_media
          },
          useModel?.formData?.value
        )
        setTimeout(() => {
          uni.hideLoading()
        }, 1000)
        return false
      }
      if (useModel?.showData?.value?.content_type === 'Video') {
        uni.showLoading({
          title: '准备资料中...',
          mask: true
        })
        let attachments_media: any = []
        useModel?.showData?.value?.attachments_media?.map((res: any) => {
          attachments_media?.push({
            msgtype: 'video', // 消息类型，必填
            video: {
              mediaid: res?.media_id // media_id，必填
            }
          })
        })
        shareToExternalChatTask(
          {
            content: useModel?.showData?.value?.content,
            attachments: attachments_media
          },
          useModel?.formData?.value
        )
        setTimeout(() => {
          uni.hideLoading()
        }, 1000)
        return false
      }
    } else {
      showToast('请在企业微信中操作!')
    }
  }
}
