<template>
  <view class="con-body">
    <view class="con-bg">
      <!-- 头部 -->
      <customHeader ref="customHeaderRef" :title="'签到打卡'" :leftFlag="true" :rightFlag="false"></customHeader>

      <!-- 高度来避免头部遮挡 -->
      <view class="top-height"></view>

      <!-- 正文内容 -->
      <view class="white-bg">
        <image src="../../../../static/images/business/btn-qd.png" class="btn-image" @click="handleCheckIn"/>
<!--        <image src="../../../../static/images/business/btn-dk.png" class="btn-image" @click="handleClockIn"/>-->
        <image src="../../../../static/images/business/btn-dk.png" class="btn-image" @click="handleClick"/>
        <view class="check-desc">
          业务人员可通过
          <text class="font-orange">签到</text>
          或
          <text
              class="font-blue">打卡
          </text>
          进行行为记录，该时间会和走访报告中的时间进行关联，便于查看。
        </view>
      </view>
    </view>
    <closeable-modal v-model="modalVisible"
                     title="确认在此处打卡？"
                     :content="form.addressForStart"
                     closeTip="轻触空白处关闭"
                     cancelText="出差"
                     confirmText="未出差"
                     contentAlign="center"
                     @confirm="handleConfirm"
                     @cancel="handleCancel"/>

    <!-- 打卡遮罩层 -->
    <!-- <view class="check-con" v-if="checkFlag">
        <view class="check-in">
            <view class="check-tip">打卡</view>
            <view class="check-title">确定要在此处打卡吗？</view>
            <view class="check-location">
                <uni-icons type="location-filled" size="30" color="#0395E0"></uni-icons> 亚洲金融大厦
            </view>
            <view class="check-address">北京市朝阳区天辰东路1号院</view>
            <view class="check-footer">
                <button class="btn-default" type="default" @click="handleCancel" size="mini">取 消</button>
                <button class="btn-primary" type="primary" @click="handleSubmit" size="mini">确 定</button>
            </view>
        </view>
    </view> -->

  </view>
</template>

<script setup>
import {ref, onMounted, reactive} from 'vue'
import customHeader from '@/components/customHeader.vue'
import {addStartMapForClockIn, businessTripClockIn} from '../../../../api/crm/activity/map';
import CloseableModal from "@/components/closeableModal.vue";
import {MapApiConfig} from "../../../../constants/mapApiConstants";

let form = reactive({
  addressForStart: null,
  addressForEnd: null,
  createId: null,
  staffName: null,
  visistCode: null,
  visistId: null,
  remark: null,
  mapId: null
})
// 签到
let handleCheckIn = () => {
  uni.navigateTo({
    url: './addRearkSignIn'
  })
}
// 打卡
// let handleClockIn = () => {
//   uni.getLocation({
//     type: 'wgs84',
//     success: (res) => {
//       const latiude = res.latitude;
//       const longitude = res.longitude;
//       //进行解析
//       inverseGeocoding(latiude, longitude);
//     },
//     fail: function (err) {
//       console.log("获取地址失败" + err)
//     }
//   })
// }
let modalVisible = ref(false);
let handleClick = () => {
  uni.getLocation({
    type: 'wgs84',
    success: (res) => {
      const latitude = res.latitude;
      const longitude = res.longitude;
      console.log('纬度:',latitude,'，经度:', longitude);
      inverseGeocoding(latitude, longitude);
    },
    fail: function (err) {
      console.log("获取地址失败" + err)
    }
  })


}
// 反馈提示
const feedback = (res, callback)=>{
  if(res.code===200){
    if(callback) callback();
    uni.showToast({
      title: MapApiConfig.OTHER.typeName === form.addressForStart ? MapApiConfig.OTHER.typeName : res.msg,
      icon: 'success'
    })
    setTimeout(()=>{
      uni.navigateBack(1);
    }, 500)
  }
  else{
    uni.showToast({
      icon: 'none',
      title: res.msg
    })
  }
}
// 出差
const handleCancel = () => {
  businessTripClockIn(form).then(res=>{
   feedback(res,()=>console.log('出差打卡成功'));
  }).catch(e=>{
    console.log(e);
  })
}
// 打卡
let handleConfirm = () => {
  addStartMapForClockIn(form).then(res=>{
   feedback(res, ()=>console.log('打卡成功'));
  }).catch(e=>{
    console.log(e)
  })
}

// 判定是否在范围内
function isWithinRange(lat, lon, centerLat, centerLon, rangeKm) {
  const distance = haversineDistance(centerLat, centerLon, lat, lon);
  return distance <= rangeKm;
}

function haversineDistance(lat1, lon1, lat2, lon2, radius = 6371) {
  const dLat = degToRad(lat2 - lat1);
  const dLon = degToRad(lon2 - lon1);
  const a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(degToRad(lat1)) * Math.cos(degToRad(lat2)) *
      Math.sin(dLon / 2) * Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return radius * c; // 距离，单位：公里
}

// 角度转弧度
function degToRad(deg) {
  return deg * (Math.PI / 180);
}

//解析地址
function inverseGeocoding(latitude, longitude) {
  uni.showLoading();
    const apiURL = MapApiConfig.URL;
    const params = {
        lat: latitude,
        lng: longitude,
        radius: 1000,
        pageSize: 1,
        currentPage: 1,
        //classify: 220100
    };
    const token = MapApiConfig.token;
    uni.request({
        url: apiURL,
        method: 'GET',
        data: params,
        header: {
            'Authorization': 'Bearer ' + token
        },
        success: (res) => {
          modalVisible.value=true;
            console.log(res, "经纬度解析成功")
            if (res.statusCode === 200 && res.data.status === 200) {
                let resdata = res.data.data.rows[0].address
                if (resdata == null) {
                    console.log(resdata.srcLat)
                    if (isWithinRange(latitude1, longitude1, latiude, longitude, 1)) {
                        form.addressForStart = MapApiConfig.XI_AN_BAN.typeName;
                        form.path = MapApiConfig.XI_AN_BAN.longitude + ',' + MapApiConfig.XI_AN_BAN.latitude ;
                    }
                }
                else {
                    form.addressForStart = resdata;
                    form.path = longitude + ',' + latitude; // 经度，纬度
                }
            } else {
                form.addressForStart = MapApiConfig.OTHER.typeName;
                form.path = longitude + ',' + latitude; // 经度，纬度
            }
            uni.hideLoading();
        },
        fail(e) {
            console.log("获取位置失败", e)
          uni.hideLoading();
        },
    })


}

</script>

<style scoped>
.white-bg {
  width: 650rpx;
  margin: 0;
  border-radius: 8px 8px 0 0;
  padding: 50rpx;
  /* #ifdef APP-PLUS */
  height: calc(100vh - 125px);
  /* #endif */
  /* #ifndef APP-PLUS */
  height: calc(100vh - 98px);
  /* #endif */


}

.btn-image {
  width: 340rpx;
  height: 340rpx;
  margin: 30rpx auto 60rpx;
  display: block;
}

.check-desc {
  background-color: #F5F5F5;
  padding: 40rpx 50rpx;
  font-size: 28rpx;
  border-radius: 10px;
  margin-top: 100rpx;
}

.check-desc .font-orange {
  color: #F5813A;
  font-size: 32rpx;
  font-weight: bold;
}

.check-desc .font-blue {
  color: #2CBAEF;
  font-size: 32rpx;
  font-weight: bold;
}

/* 弹窗处理 */
.check-con {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

/* 遮罩层内容样式 */
.check-in {
  background-color: #fff;
  padding: 40rpx 30rpx 60rpx;
  border-radius: 10px;
  /* width: 620rpx; */
  width: 560rpx;
  position: absolute;
  top: 48%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.check-in .check-tip {
  font-weight: bold;
}

.check-in .check-title {
  font-size: 32rpx;
  padding: 20rpx 0;
}

.check-in .check-location {
  color: #0395E0;
  font-size: 42rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 30rpx 0;
}

.check-in .check-location .uniui-location-filled {
  font-weight: normal;
  margin-right: 20rpx;
}

.check-in .check-address {
  color: #919191;
  font-size: 32rpx;
  margin-bottom: 80rpx;
}

.check-in .check-footer {
  display: flex;
}

.check-in .check-footer .btn-default,
.check-in .check-footer .btn-primary {
  background-color: #fff;
  border: 1px solid #05A3F4;
  color: #05A3F4;
  border-radius: 25px;
  padding: 0rpx 80rpx;
  font-size: 34rpx;
  /* margin-left: 0;
  margin-right: 20rpx; */
}

.check-in .check-footer .btn-primary {
  background-color: #05A3F4;
  border: 1px solid #05A3F4;
  color: #fff;
  /* padding: 0rpx 60rpx; */
}
</style>
