<template>
  <view class="page">
    <navBar :title="'兑换详情'" />
    <scroll-view scroll-y class="content">
      <!-- 兑换详情信息区域 -->
      <view class="detail-card">
        <view class="detail-row">
          <text class="detail-label">兑换号：</text>
          <text class="detail-value">{{ exchangeNo }}</text>
        </view>
        <view class="detail-row" style="align-items: flex-start;">
          <text class="detail-label">兑换物品：</text>
          <text class="detail-value">{{ goodsName }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">兑换数量：</text>
          <text class="detail-value">{{ quantity }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">积分：</text>
          <text class="detail-value points-value">{{ points }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">创建时间：</text>
          <text class="detail-value">{{ createTime }}</text>
        </view>
        <view class="detail-row"  v-if="type == 1">
          <text class="detail-label">物流：</text>
          <text class="detail-value">{{ logistics }}</text>
        </view>
        <view class="detail-row logistics-row" v-if="type == 1">
          <text class="detail-label">物流编号：</text>
          <view class="logistics-no-wrapper">
            <text class="detail-value logistics-no" >{{ logisticsNo }}</text>
            <view class="copy-btn" @click="copyLogisticsNo" v-if="logisticsNo ">复制</view>
          </view>
        </view>
        <view class="detail-row"  v-if="type == 2">
          <text class="detail-label">手机号：</text>
          <text class="detail-value">{{ mobile }}</text>
        </view>
      </view>

     
      
    </scroll-view>

    <!-- 底部快递查询按钮 -->
    <view class="bottom-bar" @click="goLogistics" v-if="status == 4 && type == 1 && logistics && logisticsNo">
      <text class="query-btn-text">快递查询</text>
    </view>
    <view class="bottom-bar bew"  v-if="status == 1 && restTime > 0">
      <view class="left"><up-count-down :time="restTime" format="mm:ss" @finish="finishCount"></up-count-down>分钟后此订单自动取消</view>
      <view class="right">
         <view class="cancel" @click="cancelOrder">取消订单</view>
         <view class="pay" @click="goPay">去支付</view>
         </view>
      </view>
    
  </view>
  <unidialog
	:title="'确认兑换信息'"
    :visible="freeVisible"
    :content="freeContent"
    :titleColor="'#000'"
    @close="freeClose"
    @confirm="freeConfirm"
  >
  <template #content>
	<view>
		<view class="row">
			<view class="left">收件人：</view>
			<view class="right">{{ user_name }}</view>
		</view>
		<view class="row">
			<view class="left">手机号：</view>
			<view class="right">{{ mobile }}</view>
		</view>
		<view class="row" v-if="type==1">
			<view class="left">地址：</view>
			<view class="right">{{ address }}</view>
		</view>
		<view class="row" v-else>
			<view class="left">邮箱：</view>
			<view class="right">{{ email }}</view>
		</view>
		<view class="row">
			<view class="left">兑换积分：</view>
			<view class="right"><text class="price">{{ points }}积分</text>(包邮)</view>
		</view>
		<view class="row">请确认此次兑换，物品不退不换</view>
	</view>
  </template>
  </unidialog>
</template>

<script setup>
import navBar from '@/components/navBar/navBar.vue';
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';
import goods_api from '@/api/goods_api';
import navTo from '@/utils/navTo';
import unidialog from '@/components/dialog/dialog.vue';
import dayjs from 'dayjs';

const id = ref('');
const user_name = ref('');
const address = ref('');
const email = ref('');
const goods_order_id = ref('');
const cancelOrder = () => {
	goods_api.cancelGoodsOrder({
		goods_order_uuid: exchangeNo.value,
	}).then(res => {
		if(res.code == 200){
			uni.showToast({
				title: '取消成功',
				icon: 'none',
				duration: 2000
			});
      fetchExchangeDetail()
    }
  })
}
onLoad((options) => {
  if (options && options.id) {
    id.value = options.id;
  }
  fetchExchangeDetail()
});

// 响应式数据
const restTime = ref(0);
const exchangeNo = ref('');
const goodsName = ref('');
const quantity = ref();
const points = ref();
const createTime = ref('2');
const logistics = ref('');
const logisticsNo = ref('');
const mobile = ref('');
const type = ref(1);
const status = ref(null);
const freeVisible = ref(false)
// 复制物流编号
const freeClose = () => {
	freeVisible.value = false
}
const freeConfirm = () => {
	freeVisible.value = false;
	goods_api.payGoodsOrder({
		goods_order_uuid: goods_order_id.value,
	}).then(res => {
		if(res.code == 1 || res.code == 200){
			uni.showToast({
				title: '兑换成功',
				icon: 'none',
				duration:1000
			});
			setTimeout(() => {
				navTo({
					url: '/pages_goods/pointMall/pointMall?from=exchange'
				})
			}, 1000)
		}
	})
}
const finishCount = () => {
  restTime.value = 0;
  cancelOrder();
}
const copyLogisticsNo = () => {
  uni.setClipboardData({
    data: logisticsNo.value,
    success: () => {
      uni.showToast({
        title: '已复制',
        icon: 'none'
      });
    },
    fail: () => {
      uni.showToast({
        title: '复制失败',
        icon: 'none'
      });
    }
  });
};

// 跳转到物流查询页面
const goLogistics = () => {
  uni.navigateTo({
    url: `/pages_goods/logistics/logistics?order_id=${exchangeNo.value}&name=${logistics.value}`
  });
};
const goPay = () => {
  console.log('222')
   freeVisible.value = true
};
// 格式化时间
const formatDateTime = (timestamp) => {
  if (!timestamp) return '';
  const d = new Date(Number(timestamp) * 1000);
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const h = String(d.getHours()).padStart(2, '0');
  const min = String(d.getMinutes()).padStart(2, '0');
  return `${y}-${m}-${day} ${h}:${min}`;
};



// 获取兑换详情（如果需要从API获取）
const fetchExchangeDetail = async () => {
  try {
    // 这里可以调用相应的API获取订单详情
    const res = await goods_api.getGoodsOrderDetail({ 
      uuid:id.value

     });
    if (res.code === 200 && res.data) {
      const data = res.data;
      exchangeNo.value = data.goods_order_id || '';
      goodsName.value = data.name || '';
      quantity.value = data.goods_num || 0;
      points.value = data.pionts || 0;
      createTime.value = formatDateTime(data.create_date) || '';
      logistics.value = data.express_name || '';
      logisticsNo.value = data.express_id || '';
      mobile.value = data.mobile || '';
      type.value = data.type;
      status.value = data.status;
      goods_order_id.value = data.goods_order_id;
      user_name.value = data.user_name || '';
      address.value = data.address || '';
      email.value = data.email || '';
      let time1=dayjs(new Date().getTime());
      
      //console.log(dayjs(data.time_expire*1000).format('YYYY-MM-DD HH:mm:ss'))
      let time2=dayjs(data.time_expire*1000);
      restTime.value = time2.diff(time1, 'millisecond');
     if(restTime.value <=0 && status.value == 1){
      cancelOrder();
     }
      console.log(restTime.value)
    }
  } catch (e) {
    console.error('获取兑换详情失败:', e);
    uni.showToast({
      title: '获取详情失败',
      icon: 'none'
    });
  }
};
</script>

<style scoped lang="scss">
.page {
  min-height: 100vh;
  background: #f5f5f5;
  :deep(.dialog-title){
   color:#000;
  }
  :deep(.u-count-down__text){
    color:#ff0000!important;
  }
}

.content {
  position: absolute;
  top: calc(var(--status-bar-height) + 44px);
  bottom: 100rpx;
  left: 0;
  right: 0;
  background: #f5f5f5;
 
}

// 兑换详情卡片
.detail-card {
  background: #fff;
  padding: 30rpx;
  // border-radius: 16rpx;
  margin-bottom: 40rpx;
  padding-top: 0;
}

.detail-row {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;

  &:last-child {
    border-bottom: none;
  }
}

.detail-label {
  color: #333;
  font-size: 30rpx;
  white-space: nowrap;
  width: 180rpx;
  flex-shrink: 0;
}

.detail-value {
  color: #666;
  font-size: 30rpx;
  flex: 1;
  word-break: break-all;
}

// 积分值红色显示
.points-value {
  color: #ff0000;
  font-weight: 500;
}

// 物流编号行
.logistics-row {
  align-items: center;
}

.logistics-no-wrapper {
  display: flex;
  align-items: center;
  flex: 1;
  gap: 20rpx;
}

.logistics-no {
  flex: 1;
}

// 复制按钮
.copy-btn {
  background: #ff0000;
  color: #fff;
  font-size: 24rpx;
  padding: 8rpx 20rpx;
  border-radius: 8rpx;
  white-space: nowrap;
  flex-shrink: 0;
}

// 参考提示文字
.reference-text {
  text-align: center;
  color: #ff0000;
  font-size: 30rpx;
  padding: 40rpx 0;
}

// 底部按钮
.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #27c5b8;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}
.bottom-bar.bew{
  display: flex;
  align-items: center;
  justify-content: space-between;
  background:#efefef;
  .left{
    display: flex;
    align-items: center;
    white-space: nowrap;
    font-size: 26rpx;
    margin-left: 30rpx;
    color: #666;
  }
  .right{
    margin-right: 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .cancel{
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26rpx;
      color: #666;
      padding: 10rpx 20rpx;
      border-radius: 10rpx;
      border: 2rpx solid #666;
    }
    .pay{
      display: flex;
      align-items: center;
      margin-left: 20rpx;
      justify-content: center;
      font-size: 26rpx;
      color: #ffff;
      background: #8b2116;
      padding: 10rpx 20rpx;
      border-radius: 10rpx;
      border: 2rpx solid #8b2116;
    }
  }
}
.query-btn-text {
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
}
.row{
	display: flex;
	align-items: flex-start;
	font-size: 28rpx;
	padding: 12rpx 0;

	max-width: 800rpx;
	
	.left{
		text-align: left;
		max-width: 141rpx;
    white-space: nowrap;
		width:auto!important;
	}
	.price{
		color: #FF4D4F;
	}
}
.left{
	width: 160rpx;
}
</style>