<template>
  <view class="container">
    <!-- 顶部状态栏 -->
    <view class="status-bar" v-if="status === '1'">
      <view class="status">待付款</view>
      <view class="countdown">剩余支付时间: {{ countdown }}</view>
      <view class="tips">10分钟内未支付订单自动取消</view>
    </view>
    <view class="status-bar" v-if="status === '3'">
      <view class="status">待发货</view>
      <view class="countdown">预计到货时间: {{ orderInfo.estimated_delivery_time }}</view>
      <view class="tips">商家正在加急打包中了，请耐心等候</view>
    </view>
    <view class="status-bar" v-if="status === '4'">
      <view class="status" v-if="orderInfo.order_cate === 1">待配送</view>
      <view class="status" v-if="orderInfo.order_cate === 2">待自提</view>
      <view class="countdown">预计到货时间: {{ orderInfo.estimated_delivery_time }}</view>
      <view class="tips">
        配送司机：15901518415
        <img class="phone" src="https://static.hshuishang.com/myOrder/phone.png" />
      </view>
    </view>
    <view class="status-bar" v-if="status === '5' || status === '退款中'">
      <view class="status">已完成</view>
      <view class="countdown">预计到货时间: {{ orderInfo.estimated_delivery_time }}</view>
      <view class="tips">感谢对我们的信任，期待下次光临</view>
    </view>
    <view class="status-bar" v-if="status === '6'">
      <view class="status">已取消</view>
      <view class="countdown">订单已取消</view>
      <!-- <view class="tips">您的订单已取消，再来一单吧</view> -->
    </view>
    <view class="status-bar" v-if="status === '7'">
      <view class="status">退款中</view>
      <view class="tips">感谢对我们的信任，期待下次光临</view>
    </view>

    <view class="content">
      <!-- 订单金额 -->
      <view class="amount-section">
        <view v-if="status !== '退款中'">
          <view class="total-amount">¥{{ orderInfo.total_amount }}</view>
          <view class="original-price">商品下单应付
            <text> ¥{{ orderInfo.total_amount }}</text>
          </view>
        </view>
        <view class="goods-item" v-for="(item, index) in orderInfo.commodity_order_item_list" :key="index">
          <view class="goods-content" @click="toDetail(orderInfo, item)">
            <image :src="item.commodity_pic" class="goods-img"></image>
            <view class="goods-info">
              <view>
                <view class="goods-name">{{ item.goods_name }}</view>
                <view class="goods-desc">{{ item.desc }}</view>
              </view>
              <view>
                <view class="goods-price">¥{{ item.sales_price }}</view>
                <view class="goods-info-right"> x{{ item.count }}</view>
              </view>
            </view>
          </view>
          <view v-if="status === '退款中'" class="goods-info-tk">退款已完成</view>
        </view>
        <view class="hr"></view>
        <view class="info-item">
          <view class="info-label1">下单总金额( ¥{{ orderInfo.total_amount }} )</view>
          <view class="info-action">明细</view>
        </view>
        <view class="info-item">
          <view class="info-label">商品下单总金额</view>
          <view class="info-value">¥{{ orderInfo.total_amount }}</view>
        </view>
        <view class="info-item">
          <view class="info-label">运费总计</view>
          <view class="info-value">¥{{ orderInfo.freight }}</view>
        </view>
      </view>

      <view v-if="status !== '退款中'">
        <!-- 配送信息 -->
        <view class="delivery-info">
          <view class="section-title">配送信息</view>
          <view class="info-item">
            <view class="info-label">配送方式</view>
            <view class="info-value" v-if="orderInfo.order_cate === 1">商家自配</view>
            <view class="info-value" v-if="orderInfo.order_cate === 2">客户自提</view>
          </view>
          <view class="info-item">
            <view class="info-label">预计配送时间</view>
            <view class="info-value">{{ orderInfo.estimated_delivery_time }}</view>
          </view>
        </view>

        <!-- 收货信息 -->
        <view class="recipient-info">
          <view class="section-title">收货信息</view>
          <view class="info-item">
            <view class="info-label">收货人</view>
            <view class="info-value">{{ orderInfo.receiving_name }}
              <text> {{ orderInfo.receiving_phone }}</text>
            </view>
          </view>
          <view class="info-item">
            <view class="info-label">收货地址</view>
            <view class="info-value">{{ orderInfo.receiving_address }}</view>
          </view>
        </view>

        <!-- 订单信息详情 -->
        <view class="order-detail-info">
          <view class="section-title">订单信息</view>
          <view class="info-item">
            <view class="info-label">订单编号</view>
            <view class="info-value">{{ orderInfo.order_no }}</view>
          </view>
          <view class="info-item">
            <view class="info-label">支付方式</view>
            <view class="info-value">{{ orderInfo.pay_method }}</view>
          </view>
          <view class="info-item">
            <view class="info-label">下单时间</view>
            <view class="info-value">{{ orderInfo.order_time }}</view>
          </view>
          <view class="info-item">
            <view class="info-label">备注</view>
            <view class="info-value">{{ orderInfo.remark }}</view>
          </view>
        </view>

        <!-- 底部操作按钮 -->
        <view class="bottom-buttons" v-if="status === '1'">
          <button class="cancel-btn" @click="cancelOrder">取消订单</button>
          <!-- <button class="yfd-btn" @click="cancelOrder">运费单</button> -->
          <button class="pay-btn" @click="gotoPayment">立即支付</button>
        </view>
        <view class="bottom-buttons" v-if="status === '3'">
          <!-- <button class="yfd-btn" @click="cancelOrder">运费单</button> -->
          <button class="cancel-btn" @click="applyRefund">申请退款</button>
          <!-- <button class="pay-btn" @click="gotoPayment">立即支付</button> -->
        </view>
        <view class="bottom-buttons" v-if="status === '4'">
          <button class="cancel-btn" @click="checkLogistics">查看物流</button>
          <!-- <button class="yfd-btn" @click="cancelOrder">运费单</button> -->
          <button class="pay-btn" @click="confirmReceiving">确认收货</button>
        </view>
        <view class="bottom-buttons" v-if="status === '5'">
          <!-- <button class="cancel-btn" @click="afterSale">退换/售后</button> -->
          <!-- <button class="yfd-btn" @click="cancelOrder">运费单</button> -->
          <button class="pay-btn" @click="orderEvaluate" :disabled="orderInfo.evauate_status === 1">评价</button>
        </view>
        <view class="bottom-buttons" v-if="status === '6'">
          <!-- <button class="yfd-btn" @click="cancelOrder">运费单</button> -->
          <!-- <button class="cancel-btn" @click="cancelOrder">服务评价</button> -->
          <!-- <button class="pay-btn" @click="gotoPayment">再来一单</button> -->
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { picUrl, NavgateTo, request } from "../../../utils";
import { apiArr as afterSaleApi } from "../../../api/afterSale";

export default {
  data() {
    return {
      status: "",
      countdown: "",
      orderInfo: {},
    };
  },
  onLoad(options) {
    let item
    // 来自客服聊天卡片：完整订单数据经本地存储中转（避免 URL 过长被截断）
    if (options && options.fromChat) {
      try { item = uni.getStorageSync('chatCardItem') } catch (e) { item = null }
      uni.removeStorageSync('chatCardItem')
    }
    if (!item) {
      item = JSON.parse(options?.item);
    }
    this.orderInfo = item;
    // 启动倒计时
    item.order_status == "1" ? this.startCountdown() : "";
    this.status = JSON.stringify(item.order_status);
  },
  methods: {
    toDetail(orderInfo, item) {
      const goodId = item.goods_id
      NavgateTo(`/packages/myOrders/goodDetails/index?item=${JSON.stringify(orderInfo)} &goodId=${JSON.stringify(goodId)}`);
    },
    startCountdown() {
      // 检查订单信息中是否有时效时间戳
      if (!this.orderInfo.timeout_time_stamp) {
        console.error('订单时效时间戳不存在');
        return;
      }

      // 获取当前时间和订单超时时间
      const now = Math.floor(new Date().getTime() / 1000);
      const timeoutTime = this.orderInfo.timeout_time_stamp;

      // 判断当前时间是否已超过超时时间
      if (now > timeoutTime) {
        // 已超过超时时间，直接取消订单
        this.handleOrderCancellation();
        return;
      }

      // 计算剩余时间（秒）
      let remainingSeconds = timeoutTime - now;
      // 确保剩余时间不为负数
      remainingSeconds = Math.max(0, remainingSeconds);

      // 更新倒计时显示的函数
      const updateCountdownDisplay = (seconds) => {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;
        this.countdown = `${hours}:${minutes.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
      };

      // 立即更新一次显示
      updateCountdownDisplay(remainingSeconds);

      // 设置定时器，每秒更新一次倒计时
      const timer = setInterval(() => {
        remainingSeconds--;

        updateCountdownDisplay(remainingSeconds);

        // 检查是否已经超时
        if (remainingSeconds <= 0) {
          clearInterval(timer);
          // 倒计时结束，取消订单
          this.handleOrderCancellation();
        }
      }, 1000);
    },

    // 处理订单取消
    handleOrderCancellation() {
      const params = {
        order_id: this.orderInfo.id,
        method: 1,
        cancel_reason: '倒计时结束取消',
      };
      request(afterSaleApi.cancelOrConfirm, "POST", params).then((res) => {
        uni.showToast({ title: "订单已取消", icon: "none" });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      });
    },
    cancelOrder() {
      uni.showModal({
        title: "提示",
        content: "确定要取消订单吗？",
        success: (res) => {
          if (res.confirm) {
            const params = {
              order_id: this.orderInfo.id,
              method: 1,
              cancel_reason: '用户主动取消',
            }
            request(afterSaleApi.cancelOrConfirm, "POST", params).then((res) => {
              uni.showToast({ title: "订单已取消", icon: "none" });
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            });
          }
        },
      });
    },

    // 申请退款
    applyRefund() {
      uni.showModal({
        title: "申请退款",
        content: "确定要申请退款吗？",
        success: (res) => {
          if (res.confirm) {
            const params = {
              order_id: this.orderInfo.id,
            }
            request(afterSaleApi.orderRefund, "POST", params).then((res) => {
              uni.showToast({ title: "退款成功", icon: "none" });
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            });
          }
        }
      });
    },

    // 确认收货
    confirmReceiving() {
      uni.showModal({
        title: "确认收货",
        content: "确认收货后订单状态将变为【已完成】,如有售后需求可正常申请退款/售后,确定要确认收货吗？",
        success: (res) => {
          if (res.confirm) {
            const params = {
              order_id: this.orderInfo.id,
              method: 2,
            }
            request(afterSaleApi.cancelOrConfirm, "POST", params).then((res) => {
              uni.showToast({ title: "已确认收货", icon: "none" });
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            });
          }
        },
      });
    },
    gotoPayment() {
      // 创建转换后的商品数组
      const transformedItems = this.orderInfo.commodity_order_item_list.map(goods => ({
        isafterSale: true,
        orderId: this.orderInfo.id,
        commodity_goods_info: {
          commodity_brief: "",
          commodity_id: goods.goods_id,
          commodity_pic: goods.commodity_pic,
          goods_alias: goods.goods_name,
          goods_carousel: "",
          goods_detail_pic: "",
          goods_intro: goods.goods_name,
          goods_name: goods.goods_name,
          goods_no: "",
          goods_spec: goods.goods_spec,
          goods_status: 1,
          goods_unit: goods.goods_unit,
          goods_video: "",
          group_buy_activity_info: null,
          id: goods.id,
          is_same_day: goods.is_same_day || false,
          is_support_same_day: goods.is_support_same_day || 2,
          market_price: goods.sales_price,
          sales_price: goods.sales_price,
          stock_quantity: goods.stock_quantity
        },
        commodity_id: goods.goods_id,
        count: goods.count,
        create_time: this.orderInfo.create_time,
        goods_id: goods.id,
        group_buy_id: 0,
        id: goods.id,
        supplier_id: this.orderInfo.supplier_id,
        supplier_name: this.orderInfo.supplier_name,
        update_time: this.orderInfo.update_time,
        user_id: this.orderInfo.user_id
      }));
      NavgateTo(`/packages/shop/goodsSubmit/index?shopCarList=${JSON.stringify(transformedItems)}`)
    },
    checkLogistics() {
      // NavgateTo(`/packages/myOrders/logistics/index`);
    },

    orderEvaluate() {
      NavgateTo(`/packages/myOrders/orderEvaluate/index?item=${JSON.stringify(this.orderInfo)}`);
    },

    // 售后按钮
    afterSale() {
      NavgateTo(`/packages/myOrders/afterSale/index`);
    }
  },
};
</script>
<style>
@import url("./index.css");
</style>