<template>
  <view class="container">
    <uv-sticky bgColor="#f7f7f7">
      <uv-tabs
        :list="orderType"
        :lineColor="`url('${$handleImageUrl('/order/tabs_line.png')}') 100% 100%`"
        lineWidth="64rpx"
        lineHeight="10rpx"
        activeStyle="color: #ff0000;font-weight: 700;"
        inactiveStyle="color: #1a1a1a;font-weight: 400;"
        customStyle="padding-bottom: 20rpx;"
        @change="clickBtn"
      ></uv-tabs>
    </uv-sticky>
    <!--订单列表-->
    <view class="order-list">
      <mallOrderItem
        v-for="item in orderList"
        :key="item.orderId"
        :orderData="item"
        @click.stop="goInfo(item)"
      >
        <template v-slot:btnGroup>
          <view class="u-flex-center-sb u-mt10">
            <view
              class="btn-item u-text-center u-999 br-999"
              @click.stop="cancelOrder(item)"
              v-if="item.transactionStatus == 0"
            >
              取消订单</view
            >
            <view
              class="btn-item1 u-text-center u-999 br-999"
              @click.stop="goPayment(item)"
              v-if="item.transactionStatus == 0"
            >
              去付款</view
            >
            <view
              class="btn-item1 u-text-center u-999 br-999"
              @click.stop="goReceipt(item)"
              v-if="
                item.receivingStatus != 20 &&
                item.rightsMethod == 0 &&
                item.shippingStatus == 20 &&
                item.shippingMethod == 0
              "
            >
              确认收货</view
            >
            <view
              class="btn-item u-text-center u-999 br-999"
              @click.stop="goRefundType(item)"
              v-if="item.rightsStatus == 0 && item.paymentStatus == 10"
            >
              申请售后</view
            >
          </view>
        </template>
      </mallOrderItem>
    </view>
    <noData
      v-if="orderList.length == 0"
      :config="{ top: 20, content: '暂无数据~' }"
    ></noData>
    <loadMore v-if="orderList.length > 0" :status="status"></loadMore>
  </view>
</template>

<script setup>
import { ref, reactive } from "vue";
import {
  onLoad,
  onShow,
  onReachBottom,
  onPullDownRefresh,
} from "@dcloudio/uni-app";
import {
  shoporderPage_Api,
  receiptOrder_Api,
  saleRightsOrderPage_Api,
  shoporderCancel_Api
} from "@/api/order";

const orderType = ref([
  { name: "全部" },
  { name: "待付款" },
  { name: "待发货" },
  { name: "待收货" },
  { name: "待评价" },
  { name: "退款/退货" },
]);

const orderList = ref([]);
const status = ref("more");
const isChange = ref(0);
const currentKey = ref(null);

const parmas = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 获取订单列表数据
const getOrderList = () => {
  uni.showLoading({
    title: "加载中",
    mask: true,
  });
  let objs = { ...parmas };
  switch (isChange.value) {
    case 0:
      break;
    case 1:
      objs.transactionStatus = 0;
      break;
    case 2:
      objs.transactionStatus = 10;
      break;
    case 3:
      objs.transactionStatus = 20;
      break;
    case 4:
      objs.transactionStatus = 30;
      objs.commentStatus = 0;
      break;
    case 5:
      objs.transactionStatus = 100;
      break;
    default:
      break;
  }
  // console.log(objs);
  let url = isChange.value == 5 ? saleRightsOrderPage_Api : shoporderPage_Api;
  url(objs).then((res) => {
    uni.hideLoading();
    if (res && res.code == 200) {
      uni.stopPullDownRefresh();
      if (parmas.pageNum == 1) {
        orderList.value = [];
      }
      orderList.value = orderList.value.concat(res.rows);
      if (res.total <= orderList.value.length) {
        status.value = "noMore";
      } else {
        status.value = "more";
      }
    }
  });
};

// tab切换
const clickBtn = (e) => {
  // console.log(e);
  let index = e.index;
  isChange.value = index;
  if (index == 2 || index == 3 || index == 4) {
    let key = 1;
    if (index == 2) {
      key = 1;
    } else if (index == 3) {
      key = 3;
    } else if (index == 4) {
      key = 5;
    }
    currentKey.value = key;
  }
  status.value = "loading";
  parmas.pageNum = 1;
  getOrderList();
};

// 重置列表请求
const handleReset = () => {
  status.value = "loading";
  parmas.pageNum = 1;
  getOrderList();
};

// 查看详情
const goInfo = (item) => {
  let url = `/pages/order/orderDetails?orderId=${item.orderId}`;
  if (isChange.value == 5) {
    url = `/pages/order/orderblackDetails?id=${item.id}`;
  }
  uni.navigateTo({
    url,
    events: {
      handleReset: handleReset,
    },
  });
};

// 去付款
const goPayment = (item) => {
  let expiredTime = new Date(item.expiredTime).getTime();
  let expiredNum = expiredTime - new Date().getTime();
  // console.log(expiredNum);
  // console.log(expiredTime);
  if (expiredNum <= 0) {
    uni.$uv.toast("订单已过期，请重新下单");
    setTimeout(() => {
      handleReset();
    }, 500);
    return;
  }
  let url = `/pages/order/pay?orderNo=${item.orderNo}&total_amount=${
    item.actualPayment || ""
  }&expired_pay_time=${expiredTime}&orderId=${item.orderId}&pagesType=1`;
  uni.navigateTo({
    url,
    events: {
      callback: function (data) {
        console.log(data);
        handleReset();
      },
    },
  });
};

// 申请退款
const goRefundType = (item) => {
  // console.log(item);
  uni.setStorageSync("blackgoodsList", item.orderDetails || []);
  if (item.shippingStatus == 0 || item.shippingMethod == 10) {
    uni.navigateTo({
      url: `/pages/order/applicationDrawback?orderId=${item.orderId}&keystatus=1`,
    });
  } else {
    uni.navigateTo({
      url: "/pages/order/refundType?orderId=" + item.orderId,
    });
  }
};

// 确认收货
const goReceipt = (item) => {
  uni.showModal({
    title: "是否确认收货？",
    content: "确认收货后，将无法撤销",
    success: (res) => {
      if (res.confirm) {
        console.log("用户点击确定");
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        receiptOrder_Api({ orderId: item.orderId })
          .then((res) => {
            uni.hideLoading();
            if (res && res.code == 200) {
              uni.showToast({
                title: "确认收货成功",
                icon: "success",
              });
              setTimeout(() => {
                handleReset();
              }, 1000);
            }
          })
          .catch((err) => {
            // uni.hideLoading();
          });
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
};

// 取消订单
const cancelOrder = (item) => {
  uni.showModal({
    title: "提示",
    content: "确定取消该订单吗？",
    success: (res) => {
      if (res.confirm) {
        shoporderCancel_Api({
          orderId: item.orderId,
          cancellationMethod: 10,
        }).then((res) => {
          if (res && res.code == 200) {
            uni.$uv.toast("取消成功");
            setTimeout(() => {
              handleReset();
            }, 500);
          }
        });
      } else if (res.cancel) {
      }
    },
  });
};

onLoad((options) => {
  console.log(options);
  if (options.keys) {
    if (options.keys == -1) {
      isChange.value = 0;
    } else if (options.keys == 0) {
      isChange.value = 1;
    } else if (options.keys == 6) {
      isChange.value = 5;
    } else {
      if (options.keys == 1) {
        isChange.value = 2;
      } else if (options.keys == 3) {
        isChange.value = 3;
      } else if (options.keys == 5) {
        isChange.value = 4;
      }
      currentKey.value = options.keys;
    }
  }
  getOrderList();
});

onShow(() => {});

onReachBottom(() => {
  if (status.value == "noMore") return;
  status.value = "loading";
  parmas.pageNum++;
  getOrderList();
});

onPullDownRefresh(() => {
  handleReset();
});
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f7f7f7;
  box-sizing: border-box;
  .btn-item,
  .btn-item1 {
    width: 170rpx;
    height: 67rpx;
    line-height: 67rpx;
    background: #ffffff;
    border-radius: 10rpx;
    font-size: 28rpx;
    font-weight: 700;
  }
  .btn-item {
    border: 1rpx solid #cccccc;
    color: #808080;
    margin-left: 20rpx;
  }
  .btn-item1 {
    border: 1rpx solid #e93534;
    color: #e93534;
    margin-left: 20rpx;
  }
}
</style>
