<!-- 订单详情 -->
<template>
  <view>
    <view class="order-detail">
      <PositioningMap :address="detaile.address" />
    </view>

    <view class="user-info">
      <view class="handle-user-info">
        <view class="user-name">
          <text class="user-PlaEde">下单时间：</text>
          <text class="user-PlaEde-content">{{ detaile.workDate }}</text>
          <up-text type="primary" text="查看时间" class="view-time"></up-text>
        </view>
        <view class="user-name">
          <text class="user-PlaEde">上门时间：</text>
          <text class="user-PlaEde-content">{{
            detaile.workDate + ' ' + detaile.workStartTime
          }}</text>
        </view>
        <view class="user-name">
          <text class="user-PlaEde">服务人员：</text>
          <text class="user-PlaEde-content">{{ detaile.clientName }}</text>
        </view>
        <view class="user-name" style="display: flex">
          <text class="user-PlaEde">服务类别：</text>
          <text class="user-PlaEde-content">{{
            detaile.businessTireName
          }}</text>
        </view>
        <view class="user-name">
          <text class="user-seRssEdc">地址：</text>
          <text class="address-text">{{ detaile.address }}</text>
        </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 && detaile.serviceStartTime && dateData"
      >
        服务已开始：<text class="handle-time">{{ dateData }}</text>
      </view>
      <Slide
        ref="verify"
        @change="change"
        :sliderText="slideData"
        :btnType="orderStatus ? 'upload' : 'start'"
      />
    </view>

    <!-- <view class="handle-adress">
      <up-icon name="map" color="rgba(156, 163, 175, 1)" size="20"></up-icon>
    </view> -->
    <!-- <view>
      <view class="handle-remark">
        <text class="remark-title">服务次数：{{ detaile.singleQuantity }}次</text>
      </view>
      <view class="handle-remark">
        <text class="remark-title">服务时间： {{ detaile.workDate + ' ' + detaile.workStartTime }}</text>
      </view>
    </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 { getLatLong } from '@/utils/adress'
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) => {
        console.log('TCL: getCurrentLocation -> res', res)
        // 已授权，直接获取位置
        getLocation(resolve, reject)
        // if (!res.authSetting['scope.getFuzzyLocation']) {
        //   // 如果用户未授权，先请求授权
        //   uni.authorize({
        //     scope: 'scope.getFuzzyLocation',
        //     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.getFuzzyLocation({
    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,
    })

    detaile.value = res.data

    if (res.data.orderStatus === '3') {
      orderStatus.value = true
    }
    if (res.data.serviceStartTime) {
      timer = setInterval(() => {
        const timeDiff = Math.abs(
          new Date() - new Date(res.data.serviceStartTime)
        )
        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 locationData = await getLatLong()
      // 构建参数字符串
      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: '获取位置信息...'
      // })

      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>
.handle-user-info {
  position: absolute;
  top: 531rpx;
  left: 0;
  right: 0;
  background: #ffffff;
  width: 750rpx;
  border-radius: 20rpx 20rpx 0rpx 0rpx;
  padding: 30rpx;
  box-sizing: border-box;
  .user-name {
    width: 660rpx;
    height: 50rpx;
    // opacity: 0.4;
    border-bottom: 1rpx solid rgba(230, 230, 230, 0.6);
    margin-bottom: 30rpx;
    margin-left: 20rpx;
    display: flex;
    align-items: center;
  }
  .user-PlaEde {
    width: 140rpx;
    height: 40rpx;
    font-family: PingFang SC;
    font-size: 28rpx;
    font-weight: normal;
    line-height: 40rpx;
    letter-spacing: normal;
    color: #7b7b7b;
  }
  .user-PlaEde-content {
    margin-left: 24rpx;
  }
  .seRssEdc {
    width: 140rpx;
    height: 40rpx;
    font-family: PingFang SC;
    font-size: 28rpx;
    font-weight: normal;
    line-height: 40rpx;
    letter-spacing: normal;
    color: #7b7b7b;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 224rpx; /* 8个字的大致宽度，28rpx * 8 */
    display: inline-block;
  }
  .user-seRssEdc {
    height: 40rpx;
    font-family: PingFang SC;
    font-size: 28rpx;
    font-weight: normal;
    line-height: 40rpx;
    letter-spacing: normal;
    color: #7b7b7b;
  }
  // 备注
  .handle-remark {
    width: 660rpx;
    height: 50rpx;
    opacity: 0.4;
    margin-bottom: 30rpx;
    margin-left: 20rpx;
  }

  .remark-title {
    width: 140rpx;
    height: 40rpx;
    font-family: PingFang SC;
    font-size: 28rpx;
    line-height: 40rpx;
    
  }

  .remark-text {
    width: 660rpx;
    min-height: 80rpx;
    height: auto;
    border-radius: 14px;
    opacity: 1;
    display: flex;
    background: #ffffff;
    color: #ff6e51;
    box-sizing: border-box;
    border: 1px solid #fe675b;
    padding: 20rpx;
    word-break: break-all;
    margin-top: 25rpx;
  }

  .address-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 480rpx; /* 留出seRssEdc的宽度 */
    display: inline-block;
    vertical-align: top;
    font-size: 28rpx;
    margin-left: 24rpx;
  }

  .view-time {
    position: absolute;
    left: 529rpx;
  }
}

.footer-g {
  position: fixed;
  bottom: 50rpx;
  left: 0;
  right: 0;
  padding: 0 30rpx;
  z-index: 10;
}

.handle-start {
  text-align: center;
  margin-bottom: 20rpx;
  color: #333;
  font-size: 28rpx;
}

.handle-time {
  font-weight: bold;
  color: #f64a1f;
}

:deep(.slider-verify) {
  width: 100%;
  height: 100rpx;
  overflow: hidden;
  border-radius: 50rpx;
}
</style>
