<script setup>
import dayjs from 'dayjs'
import { useFetch } from 'hooks/use-fetch'
import { useUserStore } from 'store/user'
import { getSignInListApi, postSignInApi } from '@/api/elevator'

const checkInTime = ref('')
checkInTime.value = dayjs().format('HH:mm:ss')
let timer = null
timer = setInterval(() => {
  checkInTime.value = dayjs().format('HH:mm:ss')
}, 1000)

const checkInHandler = () => {
  uni.getLocation({
    type: 'gcj02',
    isHighAccuracy: true,
    success: ({ latitude, longitude }) => {
      uni.chooseLocation({
        latitude,
        longitude,
        success: ({ address }) => {
          showModal.value = true
          userPosition.value = {
            ...userPosition.value,
            address
          }
        },
        fail: (err) => {
          console.log('err：', err)
          uni.$u.toast('获取位置信息失败')
        }
      })
    }
  })
}

const userStore = useUserStore()
const { getUserInfo } = storeToRefs(userStore)
const userInfo = computed(() => getUserInfo.value)
const userPosition = ref({})
const showModal = ref(false)
const checkInContent = ref('')
const confirm = async () => {
  const { nickName } = userStore.getUserInfo
  const { latitude, longitude, address } = userPosition.value
  const params = {
    userName: nickName,
    signTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    address,
    lat: latitude,
    lng: longitude,
    remark: checkInContent.value
  }
  await postSignInApi(params)
  uni.$u.toast('签到成功')
  checkInContent.value = ''
  dataList.value = []
  getList()
  showModal.value = false
}
const cancel = () => {
  showModal.value = false
}
const close = () => {
  showModal.value = false
}

const dataList = ref([])
const hasMore = ref(true)
const query = ref({
  pageNum: 1,
  pageSize: 10,
  startTime: `${dayjs().format('YYYY-MM-DD')} 00:00:00`,
  endTime: `${dayjs().format('YYYY-MM-DD')} 23:59:59`
})
const { result, fetchApi } = useFetch({
  apiFn: getSignInListApi,
  isList: true
})
const getList = async () => {
  await fetchApi({
    ...options.value,
    ...query.value
  })
  dataList.value.push(...result.value.rows)
  const { rows } = result.value
  if (rows.length < query.value.pageSize) {
    hasMore.value = false
  }
}
const options = ref({})
onLoad(async (e) => {
  dataList.value = []
  options.value = e
  uni.getLocation({
    type: 'wgs84',
    isHighAccuracy: true,
    success: (res) => {
      userPosition.value = res
    }
  })
})
onMounted(async () => {
  await getList()
})

onReachBottom(() => {
  const { rows } = result.value
  if (rows.length < query.value.pageSize) {
    hasMore.value = false
    return
  } else {
    query.value.pageNum++
    getList()
  }
})

onBeforeUnmount(() => {
  clearInterval(timer)
  timer = null
})

onUnmounted(() => {
  clearInterval(timer)
  timer = null
})
</script>

<template>
  <view>
    <view w-full f-s-c px-28>
      <UserAvatar />
      <view ml-12>
        <view text-28>{{ userInfo.nickName }}</view>
        <view text-24 text-gray>{{ userInfo.deptName }}</view>
      </view>
    </view>

    <!-- 签到 -->
    <view f-c-c w-full h-500>
      <view
        w-250
        h-250
        bg="#50A9E9"
        text-white
        f-c-c
        flex-col
        rounded-full
        shadow-cyan
        @tap="checkInHandler"
      >
        <view text-36>签到</view>
        <view text-24>{{ checkInTime }}</view>
      </view>
    </view>

    <view mt-30>
      <up-cell
        v-for="(item, index) in dataList"
        :key="index"
        :title="item.signTime"
      >
        <template #label>
          <view mt-8>
            <view f-s-c mt-4 text-28 text="#999999">
              <up-icon name="map-fill" :size="24" :color="`${'#999999'}`" />
              <text text-28 font-400 ml-4>{{ item.address }}</text>
            </view>
            <view mt-4>备注：{{ item.remark }}</view>
          </view>
        </template>
      </up-cell>

      <up-loadmore
        v-if="!hasMore && dataList.length"
        :line="true"
        status="nomore"
      />
    </view>
  </view>

  <!-- 退出提示 -->
  <up-modal
    title="签到"
    :show="showModal"
    show-cancel-button
    close-on-click-overlay
    @confirm="confirm"
    @cancel="cancel"
    @close="close"
  >
    <up-input v-model="checkInContent" placeholder="请输入签到内容" />
  </up-modal>
</template>
