<!-- 订单详情 -->
<template>
  <view>
    <view class="order-detail">
      <view class="service-info">
        <PositioningMap :address="detaile.address" />
      </view>
      <view class="user-info order-card">
        <view class="handle-user">
          <view class="handle-user-left">
            <img
              src="/static/serverImg/mine/user.png"
              alt=""
              style="width: 96rpx; height: 96rpx; margin-right: 32rpx"
            />
            <view class="handle-user-info">
              <view class="user-name">{{ detaile.name }}</view>
              <view class="user-id" style="display: flex"
                >服务类别：<dict-tag
                  :options="lrr_service_category"
                  :value="detaile.serviceCategory"
              /></view>
            </view>
          </view>
          <view class="user-phone" @click="onPhone(detaile.telephone)">
            <up-icon name="phone" color="#fff" size="25"></up-icon>
          </view>
        </view>

        <view class="handle-adress">
          <up-icon
            name="map"
            color="rgba(156, 163, 175, 1)"
            size="20"
          ></up-icon>
          <view class="adress-text">{{ detaile.address }}</view>
          <up-icon
            name="pushpin"
            color="rgba(221, 94, 69, 1)"
            size="25"
          ></up-icon>
        </view>
        <view>
          <view>服务次数：{{ detaile.singleQuantity }}次</view>
          <view>服务开始时间：{{ detaile.workStartTime }}</view>
          <view>服务结束时间：{{ detaile.workEndTime }}</view>
        </view>
        <view class="handle-remark">
          <view class="remark-title">备注</view>
          <view class="remark-text">{{ detaile.remark || '暂无备注' }}</view>
        </view>
      </view>
    </view>
    <view class="footer-g">
      <view class="handle-start" v-if="orderStatus && serveTimes">
        服务已开始：<text class="handle-time">{{ dateData }}</text>
      </view>
      <Slide ref="verify" @change="change" :sliderText="slideData" />
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { getVolunteerOrderInfo, getTimesByDate, getVolunteerFinishSecondOrder } from '@/api/volunteer.js'
import PositioningMap from '@/pages_classify/components/PositioningMap/index.vue'
import Slide from '@/pages_classify/components/Slide/index.vue'
import { useDict } from '@/utils/dict.js'
import DictTag from '@/components/DictTag/index.vue'
import { wxMakePhoneCall } from '@/utils/wxRequest.js'
import { computed } from 'vue'
const secondOrderId = ref('')
const detaile = ref({})
const verify = ref(null)
const { lrr_service_category } = useDict('lrr_service_category')

const orderStatus = ref(false) //false：未开始服务 true:服务已开始，待上传图片
const onPhone = (phone) => {
  if (phone) {
    wxMakePhoneCall(phone)
  }
}

const dateData = ref('00:00:00')
let timer = null

// 获取当前位置信息
const getCurrentLocation = () => {
  return new Promise((resolve, reject) => {
    // 先检查用户是否授权了位置权限
    uni.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userLocation']) {
          // 如果用户未授权，先请求授权
          uni.authorize({
            scope: 'scope.userLocation',
            success: () => {
              // 授权成功后获取位置
              getLocation(resolve, reject);
            },
            fail: (err) => {
              console.error('位置授权失败:', err);
              uni.showModal({
                title: '提示',
                content: '需要获取您的位置信息，请在设置中打开位置权限',
                confirmText: '去设置',
                success: (res) => {
                  if (res.confirm) {
                    uni.openSetting();
                  }
                }
              });
              reject(err);
            }
          });
        } else {
          // 已授权，直接获取位置
          getLocation(resolve, reject);
        }
      },
      fail: (err) => {
        console.error('获取设置失败:', err);
        reject(err);
      }
    });
  });
}

// 获取位置的具体实现
const getLocation = (resolve, reject) => {
  // 删除开发环境模拟位置的代码，始终获取真实位置
  uni.getLocation({
    type: 'gcj02',
    isHighAccuracy: true, // 高精度
    highAccuracyExpireTime: 3000, // 高精度过期时间
    success: (res) => {
      const { longitude, latitude } = res;
      console.log('当前位置 - 经度:', longitude);
      console.log('当前位置 - 纬度:', latitude);
      resolve({
        longitude,
        latitude
      });
    },
    fail: (err) => {
      console.error('获取位置失败:', err);
      // 获取位置失败时向用户提示
      uni.showToast({
        title: '获取位置失败，请确保已开启位置权限',
        icon: 'none',
        duration: 2000
      });
      reject(err);
    }
  });
}

const slideData = computed(() => {
  //服务已开始，待上传图片
  if (orderStatus.value) {
    return {
      successText: '服务已完成',
      startText: '拖动滑块结束服务',
      successColor: '#f64a1f',
      btnText: '上传照片',
    }
  }
  return {
    successText: '服务已开始',
    startText: '拖动滑块开始服务',
    successColor: '#72c13f',
    btnText: '开始',
  }
})

const getOrderDetail = async () => {
  try {
    uni.showLoading({
      title: '数据加载中...',
    })
    const res = await getVolunteerOrderInfo({
      secondOrderId: secondOrderId.value,
    })

    // Update to match the actual data structure where properties are at the top level
    detaile.value = { ...res.data, serveTimes: res.data.updateTime || null }

    if (res.data.orderStatus === '3') {
      orderStatus.value = true
    }
    if (res.data.updateTime) {
      timer = setInterval(() => {
        const timeDiff = Math.abs(new Date() - new Date(res.data.updateTime))
        const units = {
          day: Math.floor(timeDiff / (1000 * 60 * 60 * 24)),
          hour: Math.floor(timeDiff / (1000 * 60 * 60)),
          minute: Math.floor(timeDiff / (1000 * 60)),
          second: Math.floor(timeDiff / 1000),
        }
        // 默认返回完整格式
        const hours = units.hour % 24
        const minutes = units.minute % 60
        const seconds = units.second % 60
        dateData.value = `${hours}小时${minutes}分钟${seconds}秒`
      }, 1000)
    }
  } catch (error) {
    console.log('error', error)
    uni.showToast({
      title: error.msg,
      icon: 'error',
    })
  } finally {
    uni.hideLoading()
  }
}

const change = async (e) => {
  if (e.state && !orderStatus.value) {
    try {
      uni.showLoading({
        title: '获取位置信息...'
      })
      
      // 获取开始服务时的位置
      const locationData = await getCurrentLocation().catch(err => {
        uni.hideLoading()
        verify.value.initialization()
        throw new Error('无法获取位置信息，请确保已开启位置权限')
      })
      
      // 构建参数字符串
      const params = `secondOrderId=${secondOrderId.value}&serviceStartLongitude=${locationData.longitude.toString()}&serviceStartLatitude=${locationData.latitude.toString()}`
      
      // 调用开始服务接口，通过URL查询参数传递位置信息
      const res = await getTimesByDate(params)
      
      if (res.code === 200) {
        uni.showToast({
          title: '已开始服务',
          icon: 'success',
          success: () => {
            verify.value.initialization()
            // 验证成功
            orderStatus.value = true
          },
        })
      }
    } catch (error) {
      console.error('开始服务失败', error)
      uni.showToast({
        title: error.message || '开始服务失败',
        icon: 'none'
      })
    } finally {
      uni.hideLoading()
    }
  }
  
  if (e.state && orderStatus.value) {
    try {
      uni.showLoading({
        title: '获取位置信息...'
      })
      
      // // 获取结束服务时的位置
      // const locationData = await getCurrentLocation().catch(err => {
      //   uni.hideLoading()
      //   verify.value.initialization()
      //   throw new Error('无法获取位置信息，请确保已开启位置权限')
      // })
      
      // // 构建参数字符串
      // const params = `secondOrderId=${secondOrderId.value}&serviceFinishLongitude=${locationData.longitude.toString()}&serviceFinishLatitude=${locationData.latitude.toString()}`
      
      // // 调用结束服务接口，通过URL查询参数传递位置信息
      // await getVolunteerFinishSecondOrder(params)
      uni.showToast({
        title: '操作成功',
        icon: 'success',
        success: () => {
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages_classify/pages/order/index?secondOrderId=${secondOrderId.value}`,
            })
          }, 800)
        },
      })
    } catch (error) {
      console.error('结束服务失败', error)
      uni.showToast({
        title: error.message || '结束服务失败',
        icon: 'none'
      })
      verify.value.initialization()
    } finally {
      uni.hideLoading()
    }
  }
}

onLoad((options) => {
  secondOrderId.value = options.secondOrderId
  getOrderDetail()
  
  // 初始检查位置权限
  getCurrentLocation().then(location => {
    console.log('位置权限正常，可以获取位置');
  }).catch(err => {
    console.error('位置权限检查失败', err);
    uni.showModal({
      title: '位置权限提示',
      content: '服务需要获取您的位置信息，请确保已开启位置权限',
      confirmText: '去设置',
      cancelText: '知道了',
      success: (res) => {
        if (res.confirm) {
          uni.openSetting();
        }
      }
    });
  });
})
onUnload(() => {
  clearInterval(timer)
  timer = null
})
</script>
<style lang="scss" scoped>
.order-detail {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 280rpx;
  overflow-y: auto;

  .order-card {
    border-radius: 8px;
    background: rgba(255, 255, 255, 1);
    padding: 12px;
    margin-bottom: 12px;
  }

  .font-title {
    margin-bottom: 12px;
  }

  .user-box {
    display: flex;

    .user-img {
      width: 65.8px;
      height: 65.8px;
      margin-right: 12px;
    }
  }

  .register-box {
    display: flex;
    margin-bottom: 12px;

    .register-img {
      width: 90px;
      height: 90px;
      margin-right: 12px;
    }
  }

  .info-list {
    flex: 1;
    font-size: 14px;
    font-weight: 500;
    letter-spacing: 0px;
    line-height: 23.27px;
    color: rgba(51, 51, 51, 1);
  }

  .price {
    font-size: 18px;
    font-weight: 500;
    color: rgba(246, 74, 31, 1);

    .price-yuan {
      font-size: 13px;
      font-weight: 700;
      color: rgba(246, 74, 31, 1);
    }
  }

  .upload-img {
    height: 68px;
    width: 68px;
    margin-right: 12px;
    margin-bottom: 12px;
  }

  .upload-box {
    display: flex;
    flex-wrap: wrap;

    .upload-img-item {
      position: relative;

      .delete-icon {
        position: absolute;
        top: -7px;
        right: 7px;
        z-index: 1;
      }
    }
  }

  .phone {
    color: #3c9cff;
  }
}

.handle-user {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .handle-user-left {
    display: flex;
    align-items: center;

    .handle-user-info {
      .user-name {
        font-size: 32rpx;
        font-weight: 400;
        color: rgba(17, 24, 39, 1);
      }

      .user-id {
        font-size: 28rpx;
        font-weight: 400;
        color: rgba(107, 114, 128, 1);
      }
    }
  }

  .user-phone {
    display: flex;
    align-items: center;
    justify-content: center;

    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    background: rgba(221, 94, 69, 1);
  }
}

.handle-adress {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 38rpx;

  .adress-text {
    flex: 1;
    text-align: left;
    padding-left: 24rpx;
  }
}

.handle-remark {
  margin-top: 30rpx;

  .remark-title {
    font-size: 28rpx;
    font-weight: 400;
    color: rgba(17, 24, 39, 1);
    margin-bottom: 20rpx;
  }

  .remark-text {
    border-radius: 16rpx;
    background: rgba(249, 250, 251, 1);
    padding: 32rpx;
    font-size: 32rpx;
    font-weight: 400;
    line-height: 48rpx;
    color: rgba(75, 85, 99, 1);
  }
}

.handle-start {
  margin-bottom: 30rpx;
  font-size: 32rpx;
  font-weight: 400;
  color: rgba(75, 85, 99, 1);
  text-align: center;

  .handle-time {
    font-size: 32rpx;
    font-weight: 400;
    color: rgba(17, 24, 39, 1);
  }
}

.footer-g {
  padding: 12px;
  position: absolute;
  bottom: 18px;
  left: 0px;
  right: 0px;
  background: rgba(255, 255, 255, 1);
}
</style>
