<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import useUserStore from '@/store/modules/user'
import { parseTime } from '@/common/utils/ruoyi'
import { attCheck } from '@/api/clockIn'

// 类型定义
interface Position {
  latitude: number
  longitude: number
  address?: string
}

// 状态管理
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const loading = ref(false)
const showSuccess = ref(false)
const checkTime = ref('')
const mapContext = ref<any>(null)

// 定位数据
const position = reactive<Position>({
  latitude: 0,
  longitude: 0,
  address: ''
})

// 表单数据
const form:any = reactive({
  userName: userInfo.value.nickName,
  employeesCode: userInfo.value.userCode,
  checkTime: Date.now(),
  longitude: '',
  latitude: '',
  addrName: '',
  actualAddr: '',
  outSide: '1',
  imgUrl: '',
  remark: ''
})

// 定时更新打卡时间
let timer: number
onMounted(() => {
  timer = setInterval(() => {
    form.checkTime = Date.now()
  }, 1000)
})

onUnmounted(() => {
  clearInterval(timer)
})

// 初始化地图上下文
onLoad(() => {
  mapContext.value = uni.createMapContext('map', this)
  getCurrentLocation()
})

// 获取当前位置
const getCurrentLocation = async () => {
  return new Promise<void>((resolve, reject) => {
    uni.getLocation({
      type: 'gcj02',
      success: (res) => {
        position.latitude = res.latitude
        position.longitude = res.longitude
        form.longitude = res.longitude.toString()
        form.latitude = res.latitude.toString()
        
        // 使用地图上下文获取中心点地址
        mapContext.value.getCenterLocation({
          success: (centerRes: any) => {
            
            position.address = centerRes.address || `位置: ${res.latitude.toFixed(6)}, ${res.longitude.toFixed(6)}`
            form.actualAddr = position.address

              console.log('centerRes',centerRes)
             uni.request({
              url: 'https://apis.map.qq.com/ws/geocoder/v1/',
              data: {
                location: `${position.latitude},${position.longitude}`,
                key: 'MHZBZ-XNLKC-TUT2D-AS7RQ-ODXIF-OBF6I'
              },
                success: (res) => {
                  const address = res.data.result.address;
                  position.address = address
                  form.actualAddr = address
                }
              });



            resolve()
          },
          fail: () => {
            console.log('123123123')
            position.address = `位置: ${res.latitude.toFixed(6)}, ${res.longitude.toFixed(6)}`
            form.actualAddr = position.address
            resolve()
          }
        })
      },
      fail: (err) => {
        console.error('获取位置失败', err)
        uni.showToast({
          title: '获取位置失败',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

// 拍照上传
const takePhoto = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['camera'],
    success: (res) => {
      uni.uploadFile({
        header: { 'Content-Type': 'multipart/form-data','Authorization': 'Bearer ' + userStore.accessToken},
        url: 'https://demo.docmis.cn:21143/dl-prod-api/file/upload',
        filePath: res.tempFilePaths[0],
        name: 'file',
        success: (uploadRes) => {
         
          const data = JSON.parse(uploadRes.data)
           console.log('111',data)
          form.imgUrl = data.data.url
        },
        fail: () => {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }
      })
    }
  })
}

// 提交打卡
const submitCheckIn = async () => {
  if (!form.imgUrl) {
    uni.showToast({
      title: '请先拍照',
      icon: 'none'
    })
    return
  }

  try {
    uni.showLoading({
      title: '提交中...',
    })
    
    checkTime.value = parseTime(new Date())
    await attCheck({
      ...form,
      actualAddr: position.address || ''
    })
    
    showSuccess.value = true
    popupRef.value.open('center')
  } catch (error) {
    console.error('打卡失败:', error)
    uni.showToast({
      title: '打卡失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 关闭成功弹窗
const closeSuccess = () => {
  showSuccess.value = false
  popupRef.value.close()
  uni.navigateBack()
}

const markers = ref([
  {
    id: 1,
    latitude: position.latitude,
    longitude: position.longitude,
    iconPath: '/static/image/marker.png',
    width: 30,
    height: 30,
    anchor: { x: 0.5, y: 1 }
  }
])
const popupRef: any = ref(null)
</script>

<template>
  <view class="container">
    <!-- 地图容器 -->
    <map
      id="map"
      class="map"
      :latitude="position.latitude"
      :longitude="position.longitude"
      :markers="markers"
      :show-location="true"
    />
    
    <!-- 底部表单 -->
    <view class="form-container">
      <uv-form labelWidth="140" ref="formRef" :model="form">
        <uv-cell-group>
          <!-- 位置显示 -->
          <uv-form-item label="当前位置" prop="addressCode" borderBottom>
            <uv-input v-model="position.address" readonly border="none"/>
          </uv-form-item>
          
          <!-- 拍照区域 -->
          <uv-form-item label="拍照证明" borderBottom required prop="imgUrl">
            <image
              v-if="form.imgUrl"
              :src="form.imgUrl"
              style="width: 100rpx;height: 100rpx;"
              @click="takePhoto"
            />
            <uv-button
              v-else
              type="primary"
              plain
              icon="camera"
              @click="takePhoto"
            >
              点击拍照
            </uv-button>
          </uv-form-item>
          
          <!-- 备注 -->
          <uv-form-item label="备注信息">
            <uv-textarea 
              v-model="form.remark"
              placeholder="可选填备注信息"
              maxlength="200"
              count
              border="none" 
            />
          </uv-form-item>
        </uv-cell-group>
        
        <!-- 提交按钮 -->
        <uv-button
          type="primary"
          block
          :loading="loading"
          @click="submitCheckIn"
        >
          {{ parseTime(form.checkTime, '{h}:{i}:{s}') }} 外勤打卡
        </uv-button>
      </uv-form>
    </view>
    
    <!-- 打卡成功弹窗 -->
    <uv-popup ref="popupRef" v-model="showSuccess" round="10">
      <view class="success-popup">
        <image
          src="/static/image/check/checkSuccessIcon.png"
          class="success-icon"
        />
        <div class="checkTime">{{ parseTime(form.checkTime, '{h}:{i}:{s}') }}</div>
        <div class="tipeText">外勤打卡成功</div>
         <div style="margin-top: 50rpx;margin-bottom: 50rpx;" >
            <uv-button type="primary" @click="closeSuccess">我知道了</uv-button>
        </div>
       
      </view>
    </uv-popup>
  </view>
</template>

<style scoped>
.container {
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.map {
  width: 100%;
  height: 60vh;
}

.form-container {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}
.success-popup{
  display: flex;
  flex-direction: column;
  align-items: center;
}
.success-icon{
  height: 400rpx;
  width: 500rpx;
}
.checkTime{
  margin-top: 42rpx;
  font-size: 50rpx;
  font-weight: 600;
  line-height: 50rpx;
  color: rgba(71, 115, 252, 1);
}
.tipeText{
  margin-top: 44rpx;
  font-size: 36rpx;
  font-weight: 500;
  line-height: 36rpx;
  color: rgba(71, 115, 252, 1);
}
</style>