import { getApiLoading } from '@/common/libraries/apiLoading'
import { Apis } from '@/gen/Apis'
import useModel from './model'
import { showToastBack, showToast } from '@/common/libraries/naviHelper'
import { useWeAppAuthStore, useWatermarkStore } from '@/common'
import { CalculateDistance } from '@/common/libraries/mapDistance'
const auth = useWeAppAuthStore()
const watermark = useWatermarkStore()
import { isWithinTimeRange } from '@/common/libraries/day'
import { debounce } from '@/common/libraries/tools'

const getShow = (data: any, mapData: any) => {
  getApiLoading(Apis.Attendance.AttendanceSchedules.GetAttendanceShiftPeriod, data).then(res => {
    useModel.showData.value = res?.data
    useModel.distanceNumber.value = CalculateDistance(mapData, res?.data?.project)
    if (res?.data?.checkin_status?.start?.checked) {
      useModel.current.value = 1
    }
    if (res?.data?.checkin_status?.start?.checked && res?.data?.checkin_status?.end?.checked) {
      useModel.current.value = 3
    }
    setTimeout(() => {
      useModel.loading.value = true
    }, 300)
    console.log(useModel.metaData.value, 'useModel.metaData.value')
  })
}

let checkInDebounceTimer: any = null
let isCheckInSubmitting = false

const getLocationMap = (fun?: (res: any) => void) => {
  uni.getLocation({
    type: 'wgs84',
    altitude: true,
    isHighAccuracy: true,
    success(res) {
      console.log(res, '经纬度')
      useModel.currentLocation.value = { latitude: res.latitude, longitude: res.longitude }
      uni.hideLoading()
      return fun?.(res)
    },
    fail(res) {
      uni.hideLoading()
      uni.showModal({
        title: '提示',
        content: '请先允许定位！',
        success: function (res) {
          if (res.confirm) {
            uni.openSetting()
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      console.log(res, '获取经纬度失败')
    }
  })
}

const debouncedUpdateLocation = debounce(function (callback) {
  getLocationMap(callback)
}, 1200)

export default {
  handleUpdateLocation() {
    if (useModel.mapNumber.value > 3) {
      return showToast('操作太频繁！')
    }
    uni.showLoading({
      title: '加载中...',
      mask: true
    })
    debouncedUpdateLocation((res: any) => {
      useModel.mapNumber.value += 1
      uni.hideLoading()
      useModel.distanceNumber.value = CalculateDistance(
        useModel?.currentLocation?.value,
        useModel?.showData?.value?.project
      )
      // getShow(useModel?.formData?.value, res)
    })
  },
  init() {
    let watermarkInfo = watermark?.watermarkInfo?.value
    if (watermarkInfo?.length) {
      // 有水印信息，赋值给formData
      useModel.formData.value.photo = JSON.parse(JSON.stringify(watermarkInfo))
      watermark.watermarkInfo.value = [] // 赋值完成后，清空水印信息
      console.log(watermarkInfo, 'watermarkInfo')
    }
  },
  getLocation(data: any) {
    getLocationMap((res: any) => {
      getShow(data, res)
    })
  },
  onPreviewMedia(url?: string) {
    console.log(url, 'url1')
    if (url) {
      uni.previewMedia({
        sources: [
          {
            url: url,
            type: 'image'
          }
        ],
        current: 0
      })
    }
  },
  handleDelete() {
    useModel.formData.value.photo = []
  },
  handleCheckin() {
    // 防抖：如果正在提交中，直接返回
    if (isCheckInSubmitting) {
      return showToast('请勿重复点击')
    }
    if (
      !isWithinTimeRange(
        `${useModel?.formData?.value?.date} ${
          useModel?.formData?.value?.checkin_type === 'CheckOut'
            ? useModel?.showData?.value?.period?.work_end_time
            : useModel?.showData?.value?.period?.work_start_time
        }`
      )
    ) {
      return showToast('不在打卡时间内！')
    }

    if (
      useModel?.attendanceConfigData?.value?.require_photo &&
      !useModel?.formData?.value?.photo?.length
    ) {
      return showToast('请上传拍照！')
    }

    getLocationMap(() => {
      let distanceNumber = CalculateDistance(
        useModel?.currentLocation?.value,
        useModel?.showData?.value?.project
      )
      useModel.distanceNumber.value = distanceNumber
      if (distanceNumber > useModel?.attendanceConfigData?.value?.check_in_range) {
        return showToast('打卡距离超出范围！')
      }

      // 清除之前的防抖定时器
      if (checkInDebounceTimer) {
        clearTimeout(checkInDebounceTimer)
      }

      // 设置提交状态为 true
      isCheckInSubmitting = true

      // 设置防抖定时器
      checkInDebounceTimer = setTimeout(() => {
        getApiLoading(Apis.Attendance.AttendanceRecords.Checkin, {
          ...useModel.formData.value,
          ...useModel?.currentLocation?.value
        })
          .then(res => {
            getShow(useModel?.formData?.value, useModel?.currentLocation?.value)
            uni.showToast({
              title: '打卡成功',
              icon: 'success'
            })
          })
          .catch(error => {
            // 错误处理
            console.error('打卡失败:', error)
            showToast('打卡失败，请重试')
          })
          .finally(() => {
            // 请求结束后重置提交状态（延迟1秒，防止快速重复点击）
            setTimeout(() => {
              isCheckInSubmitting = false
            }, 1000)
          })
      }, 500) // 500ms防抖延迟
    })
  },
  YesNoCheckinStatus() {
    if (
      useModel?.formData?.value?.checkin_type === 'CheckOut' &&
      !useModel?.showData?.value?.checkin_status?.end?.checked
    ) {
      return true
    }
    if (
      useModel?.formData?.value?.checkin_type === 'CheckIn' &&
      !useModel?.showData?.value?.checkin_status?.start?.checked
    ) {
      return true
    }
    return false
  },
  getAttendanceConfig() {
    getApiLoading(Apis.Attendance.AttendanceSchedules.GetAttendanceConfig, {}).then(res => {
      useModel.attendanceConfigData.value = res?.data
    })
  },
  toUpload() {
    uni.navigateTo({
      url: '/INDEX/watermark_camera/index?source=current'
    })
  }
}
