<template>
  <view class="container">
    <view class="tabs">
      <view v-for="(item, index) in categoryList" :key="index"
        :class="['tabItem', selectedTab === index ? 'active2' : '']" @click="selectTab(index, item)">
        {{ item.category_name }}
      </view>

    </view>

    <view class="content">
      <view v-if="selectedTab === 6">
        <awaitRated :orderData="orderData" />
      </view>
      <view v-else-if="selectedTab === 7">
        <rated :orderData="orderData" />
      </view>
      <view v-else-if="selectedTab === 8">
        <afterSale :afterSaleList="afterSaleList" @revokeApply="revokeApply" />
      </view>
      <view v-else>
        <view v-for="(item, index) in orderData" :key="index">
          <view class="contentList">
            <!-- 订单头部信息 -->
            <view class="order-header" @click="toDetails(item)">
              <view class="orderTitle">
                <view class="orderTitleSupplier">{{ item.supplier_name }}
                  <view v-if="item.order_status == 6 || item.order_status == 5" class="status3">{{
                    getOrderStatus(item.order_status) }}</view>
                  <view v-else-if="item.order_status == 7" class="status2">
                    <img src="https://wechat-img-file.oss-cn-beijing.aliyuncs.com/myOrder/refund.png" />
                    {{ getOrderStatus(item.order_status) }}
                  </view>
                  <view v-else class="order_status">{{
                    getOrderStatus(item.order_status)
                  }}</view>
                </view>
                <text>提交订单：{{ item.order_time }}</text>
              </view>
            </view>

            <!-- 商品列表 -->
            <view class="goods-list" @click="toDetails(item)">
              <view v-for="(goods, goodsIndex) in item.commodity_order_item_list" :key="goodsIndex" class="goods-item">
                <image :src="goods.commodity_pic" class="goods-img"></image>
              </view>
            </view>

            <!-- 订单底部信息 -->
            <view class="order-footer">
              <view class="order-footer-text" @click="toDetails(item)">共{{ item.total_count }}件商品，共计
                <text> {{ item.total_amount }}</text>
              </view>
              <view>
                <view class="btn-group" v-if="item.order_status === 1">
                  <button class="cancel-btn" @click="cancelOrder(item)">
                    取消订单
                  </button>
                  <!-- <button class="yfd-btn" @click="cancelOrder">运费单</button> -->
                  <button class="pay-btn" @click="goToPay(item)">立即支付</button>
                </view>
                <view class="btn-group" v-if="item.order_status === 3">
                  <button class="cancel-btn" @click="applyRefund(item)">申请退款</button>
                </view>
                <view class="btn-group" v-if="item.order_status === 4">
                  <button class="cancel-btn" @click="viewLogistics(item)">查看物流</button>
                  <button class="pay-btn" @click="confirmReceiving(item)">确认收货</button>
                </view>
                <view class="btn-group" v-if="item.order_status === 5">
                  <text class="afterSaleNum">{{ item.commodity_order_item_list.length }}笔售后</text>
                  <button class="cancel-btn" @click="afterSale(item)">退换/售后</button>
                  <button class="pay-btn" @click="orderEvaluate(item)" :disabled="item.evauate_status === 1">评价</button>
                </view>
                <view class="btn-group" v-if="item.order_status === 6">
                  <!-- <button class="cancel-btn" @click="orderEvaluate">
                    服务评价
                  </button>
                  <button class="yfd-btn" @click="cancelOrder">运费单</button> -->
                  <!-- <button class="pay-btn" @click="goToPay(item)">再来一单</button> -->
                </view>
                <view class="btn-group" v-if="item.order_status === 7">
                  <!-- <button class="pay-btn" @click="goToPay(item)">再来一单</button> -->
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!------------------ 以下为popup ------------------>
    <!-- 取消订单 -->
    <cancel-order-popup :showPopup.sync="showPopup" @orderCancelled="handleOrderCancelled" />

    <!-- 申请退款 -->
    <refund-popup :showPopup.sync="showTkPopup" @refundConfirmed="handleRefundConfirmed" />

    <!-- 退换 售后 - 选择退款原因 -->
    <!-- 售后弹窗组件 -->
    <after-sale-popup :afterSaleGoods.sync="afterSaleGoods" :orderItem="afterSaleOrderItem" ref="afterSalePopupRef"
      @refundSubmitted="handleRefundSubmitted" :order_cate="1" />

    <!-- 无售后商品 -->
    <view>
      <u-popup ref="popup" mode="center" :show="noSalePopup" :round="15" :mask-close-able="false">
        <view class="noSalePopup">
          <view>抱歉该订单已无可申请售后的商品</view>
          <button class="noSalePopup-btn" @click="noSalePopup = false">我知道了</button>
        </view>
      </u-popup>
    </view>


  </view>
</template>
<script>
import {
  isPhone,
  picUrl,
  request,
  upload,
  NavgateTo
} from '../../../utils';
import { apiArr as afterSaleApi } from "../../../api/afterSale";
import Rated from "../rated/rated.vue";
import AwaitRated from "../awaitRated/awaitRated.vue";
import AfterSale from "../afterSale/index.vue";
import cancelOrderPopup from './popup/cancelOrder/cancelOrder.vue';
import refundPopup from './popup/refund/refund.vue';
import afterSalePopup from './popup/afterSale/index.vue';


export default {
  components: {
    Rated,
    AwaitRated,
    AfterSale,
    cancelOrderPopup,
    refundPopup,
    afterSalePopup
  },
  data() {
    return {
      categoryList: [
        { category_name: "全部" },
        { category_name: "待付款" },
        { category_name: "待发货" },
        { category_name: "配送中" },
        { category_name: "已完成" },
        { category_name: "已取消" },
        { category_name: "待评价" },
        { category_name: "已评价" },
        { category_name: "售后" },
      ],
      selectedTab: 0,
      // orderData: orderMockData,
      orderData: [],

      showPopup: false,//取消订单
      afterSaleGoods: [],//售后商品列表
      afterSaleOrderItem: {},//售后订单对象
      noSalePopup: false,//无售后商品
      showTkPopup: false,//申请退款
      afterSaleItem: '',//操作对象
      afterSaleList: [],//售后列表
      selectStatus: '',//选中的status
      evaluateStatus: '',//评价状态
    };
  },
  methods: {
    selectTab(index, item) {
      this.selectedTab = index;
      if (index == 6) {
        this.evaluateStatus = 2;
        this.selectStatus = ''
      } else if (index == 7) {
        this.evaluateStatus = 1;
        this.selectStatus = ''
      } else if (index == 2) {
        this.selectStatus = 3;
        this.evaluateStatus = ''
      } else {
        this.selectStatus = index > 2 ? index + 1 : index;
        this.evaluateStatus = ''
      }
      this.getOrderList();
    },
    // 取消订单
    cancelOrder(item) {
      this.afterSaleItem = item;
      this.showPopup = true
    },

    // 处理订单取消事件
    handleOrderCancelled(data) {
      const params = {
        order_id: this.afterSaleItem.id,
        method: 1,
        cancel_reason: data.reason,
      }
      request(afterSaleApi.cancelOrConfirm, "POST", params).then((res) => {
        this.getOrderList();
      });

    },

    // 售后按钮
    afterSale(item) {
      this.afterSaleGoods = item.commodity_order_item_list;
      // 保存完整的订单对象
      this.afterSaleOrderItem = item;
      this.$refs.afterSalePopupRef.openAfterSalePopup();
      console.log(item.id);

      // 根据条件判断是否可以售后
      //   request(afterSaleApi.isAllow, "POST", {
      //     order_id: item.id,
      //   }).then((res) => {
      //     if (res.data.is_allow_after_sales) {
      //       this.afterSaleGoods = res.data.allow_items;
      //       // this.selectedAsGood = item.commodity_order_item_list[0].id;
      //       this.$refs.afterSalePopupRef.openAfterSalePopup();
      //     } else {
      //       this.noSalePopup = true
      //     }
      //   });
    },

    // 处理退款提交事件
    handleRefundSubmitted(data) {
      const params = {
        nick_name: uni.getStorageSync("nickName"),
        order_id: this.afterSaleOrderItem.id,
        goods_ids: this.afterSaleOrderItem.commodity_order_item_list.map(item => item.goods_id),
        after_sales_type: data.afterSalesType,
        after_sales_reason: data.refundReason,
        refund_amount: this.afterSaleOrderItem.total_amount,
        application_description: data.refundDescription,
        // 将图片对象数组转换为字符串数组，多个URL用逗号分隔
        application_images: data.imgList && data.imgList.length > 0 ?
          data.imgList.map(img => img.url).join(',') : '',
        order_status: 5,
        receiving_address: data.merchantAddress,
        change_goods_id: data.changeServiceId
      }
      request(afterSaleApi.afterSaleCreate, "POST", params).then((res) => {
        this.getOrderList();
      });
    },


    // 申请退款
    applyRefund(item) {
      this.afterSaleItem = item;
      this.showTkPopup = true
    },

    // 查看物流
    viewLogistics(item) {

    },

    // 处理退款确认事件
    handleRefundConfirmed(data) {
     const params = {
        order_id: this.afterSaleItem.id,
      }
      request(afterSaleApi.orderRefund, "POST", params).then((res) => {
        uni.showToast({ title: "退款成功", icon: "none" });
        this.getOrderList();
      });
    },

    // 确认收货
    confirmReceiving(item) {
      uni.showModal({
        title: "确认收货",
        content: "确认收货后订单状态将变为【已完成】,如有售后需求可正常申请退款/售后,确定要确认收货吗？",
        success: (res) => {
          if (res.confirm) {
            const params = {
              order_id: item.id,
              method: 2,
            }
            request(afterSaleApi.cancelOrConfirm, "POST", params).then((res) => {
              this.getOrderList();
            });
          }
        },
      });
    },
    goToPay(item) {
      // 创建转换后的商品数组
      const transformedItems = item.commodity_order_item_list.map(goods => ({
        isafterSale: true,
        orderId: item.id,
        commodity_goods_info: {
          commodity_brief: "",
          commodity_id: goods.commodity_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.commodity_id,
        count: goods.count,
        create_time: item.create_time,
        goods_id: goods.goods_id,
        group_buy_id: 0,
        id: goods.id,
        supplier_id: item.supplier_id,
        supplier_name: item.supplier_name,
        update_time: item.update_time,
        user_id: item.user_id
      }));

      NavgateTo(`/packages/shop/groupPurchaseSubmit/index?shopCarList=${JSON.stringify(transformedItems)}`)
    },
    toDetails(item) {
      NavgateTo(
        `/packages/myOrders/orderDetails/index?item=${JSON.stringify(item)}`
      );
    },

    checkLogistics() {
      NavgateTo(`/packages/myOrders/logistics/index`);
    },

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

    getOrderStatus(order_status) {
      switch (order_status) {
        case 1:
          return "待付款";
        case 2:
          return "支付中";
        case 3:
          return "待发货";
        case 4:
          return "配送中";
        case 5:
          return "已完成";
        case 6:
          return "已取消";
        case 7:
          return "退款中";
        case 8:
          return "已退款";
      }
    },

    getOrderList() {
      this.orderData = []
      request(afterSaleApi.orderList, "POST", {
        order_status: this.selectStatus,
        evaluate_status: this.evaluateStatus,
        user_id: uni.getStorageSync("userId"),
      }).then((res) => {
        res.order_list?.forEach(item => {
          item.commodity_order_item_list?.forEach(good => {
            good.commodity_pic = picUrl + good.commodity_pic;
          })
        })
        this.orderData = res.order_list.filter(item => item.order_cate == 1);
        this.getAfterSaleList();
      });
    },
    getAfterSaleList() {
      const params = {
        user_id: uni.getStorageSync('userId'),
        order_cate: 1,
      }
      request(afterSaleApi.afterSalesList, "POST", params).then((res) => {
        res.after_sales_list?.forEach(item => {
          item.commodity_order_item?.forEach(good => {
            good.commodity_pic = picUrl + good.commodity_pic;
          })
        })
        this.afterSaleList = res.after_sales_list;
      });
    },

    // 处理订单撤销成功事件
    revokeApply() {
      this.getOrderList();
    }
  },

  onLoad(options) {
    this.getOrderList();
  },
  onShow() {
    this.getOrderList();
    uni.removeStorageSync('afterSaleItem')
  },
};
</script>
<style>
@import url("./index.css");
</style>