import { ref, nextTick, onUnmounted, getCurrentInstance } from 'vue'
import { useWeAppAuthStore } from '@/common'
import { onPullDownRefresh, onLoad, onPageScroll, onShow } from '@dcloudio/uni-app'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import useModel from './model'
import { upload } from '@/common/libraries/upload'

const auth = useWeAppAuthStore()

// 配置dayjs
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

export default {
  GoToPage(url: string){
    uni.navigateTo({
      url
    })
  },
  customRequest: async (
    url: string,
    data: any,
    type?: 'POST' | 'OPTIONS' | 'GET' | 'HEAD' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'
  ) => {
    const selected_house: any = auth?.data?.selected_house
    console.log('selected_house:', selected_house)
    const response = await uni.request({
      url: `${useModel?.API_BASE_URL}/api/${url}`,
      method: type || 'POST',
      data: { ...data, tenant_company_id: selected_house?.companies_id },
      header: {
        'Content-Type': 'application/json'
      }
    })
    return response
  },
  getQuickQuestions: async () => {
    try {
      const selected_house: any = auth?.data?.selected_house

      const response = await uni.request({
        url: `${useModel?.API_BASE_URL}/api/public/quick-questions?platform=property&company_id=${selected_house?.companies_id}&project_id=${selected_house?.asset_projects_id}`,
        method: 'GET'
      })
      if (response.statusCode === 200) {
        const result = response.data as any
        return result
      } else {
        return []
      }
    } catch (error) {
      return []
    }
  },
  chooseImage: async () => {
    const maxImages = 9
    if (useModel?.selectedImages?.value.length >= maxImages) {
      uni.showToast({
        title: '最多选择9张图片',
        icon: 'none'
      })
      return
    }

    try {
      const remainingCount = maxImages - useModel?.selectedImages?.value.length
      const uploadResult = await upload(remainingCount, 2, ['image'])

      if (uploadResult && Array.isArray(uploadResult) && uploadResult.length > 0) {
        const imageUrls = uploadResult.map((item: any) => item.url)
        useModel.selectedImages.value.push(...imageUrls)

        uni.showToast({
          title: '图片上传成功',
          icon: 'success'
        })
      }
    } catch (error) {
      console.error('选择图片失败:', error)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  },
  removeImage: (index: number) => {
    useModel.selectedImages.value.splice(index, 1)
  },
  previewImage: (currentImage: string, images: string[]) => {
    uni.previewImage({
      current: currentImage,
      urls: images
    })
  },
  copyMessage: (content: string) => {
    if (!content) {
      uni.showToast({
        title: '暂无内容可复制',
        icon: 'none'
      })
      return
    }

    uni.setClipboardData({
      data: content,
      success: () => {
        uni.showToast({
          title: '复制成功',
          icon: 'success'
        })
      },
      fail: () => {
        uni.showToast({
          title: '复制失败',
          icon: 'none'
        })
      }
    })
  },
  formatMessageContent: (content: string) => {
    if (!content || typeof content !== 'string') {
      return ['']
    }
    return content.split('\n').filter(line => line.trim() !== '')
  },
  formatTime: (timeStr: string) => {
    if (!timeStr) return ''

    try {
      const date = dayjs(timeStr)

      // 检查日期是否有效
      if (!date.isValid()) {
        return ''
      }

      // 使用相对时间显示
      return date.fromNow()
    } catch (e) {
      console.error('时间格式化错误:', e)
      return ''
    }
  }
}
