<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">待配送</view>
      <view class="countdown">预计到货时间: {{ orderInfo.estimated_delivery_time }}</view>
      <view class="tips">
        配送司机：15901518415
        <img class="phone" src="https://wechat-img-file.oss-cn-beijing.aliyuncs.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 === '退款中'">
      <view class="status">已完成</view>
      <view class="countdown">预计到货时间: 2025-09-09 9:59:59</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">
            <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: "9:59:59",
      orderInfo: {},
    };
  },
  onLoad(options) {
    const item = JSON.parse(options?.item);
    // 启动倒计时
    item.order_status == "1" ? this.startCountdown() : "";
    this.status = JSON.stringify(item.order_status);
    this.orderInfo = item;
  },
  methods: {
    startCountdown() {
      // 倒计时模拟
      let seconds = 10 * 60; // 10分钟
      const timer = setInterval(() => {
        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")}`;
        if (seconds <= 0) {
          clearInterval(timer);
          // 倒计时结束，处理订单
          uni.showToast({ title: "订单已取消", icon: "none" });
          setTimeout(() => uni.navigateBack(), 1500);
        }
      }, 1000);
    },
    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 = {
              nick_name: uni.getStorageSync("nickName"),
              order_id: this.orderInfo.id,
              goods_ids: this.orderInfo.commodity_order_item_list.map(item => item.goods_id),
              after_sales_type: 1,
              after_sales_reason: '用户申请退款',
              refund_amount: this.orderInfo.total_amount,
              order_status: 3
            }
            request(afterSaleApi.afterSaleCreate, "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 => ({
        checked: true,
        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/groupPurchaseSubmit/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>