<template>
  <view class="container">
    <Header title="全部订单"></Header>
    <view class="tabs">
      <wd-tabs v-model="tab" animated :lineWidth="38" :lineHeight="3" @change="handleChange">
        <block v-for="item in tabs" :key="item.value">
          <wd-tab :title="`${item.name}`" :name="item.value">
            <view class="content" v-if="dataList.length > 0">
              <view class="box" v-for="(item, index) in dataList" :key="index">
                <view class="header" @click="handleDetail(item.orderNumber)">
                  <view class="left">
                    <image src="@/static/order/shop.png" />
                    <view class="title">{{ item.shopName }}</view>
                  </view>
                  <view class="right">
                    <span class="status">{{ stateList[item.status].label }}</span>
                    <wd-count-down
                      :time="item.countDown"
                      :format="format"
                      @finish="onFinish(item.orderNumber)"
                      v-if="item.status === 'not_pay'"
                    />
                  </view>
                </view>

                <view class="info" @click="handleDetail(item.orderNumber)">
                  <image mode="aspectFill" :src="fileDomain + item.orderItems[0].pic" />
                  <view class="info-box">
                    <view class="text">下单时间：{{ item.createTime.slice(0, 16) }}</view>
                    <view class="text">预约时间：{{ item.receiverTime }}</view>
                    <view class="text">数量：{{ item.orderItems[0].prodCount }}</view>
                    <view class="text">实付：￥{{ item.actualTotal }}</view>
                  </view>
                </view>

                <view class="btn">
                  <view
                    class="btn-info"
                    v-if="item.status === 'complete' || item.status == 'cancel'"
                    @tap="handleDelete(item.orderNumber)"
                  >
                    删除
                  </view>
                  <view
                    class="btn-info"
                    v-if="item.status === 'receive' || item.status == 'not_use'"
                    @tap="handleQrcode(item)"
                  >
                    核销码
                  </view>
                  <view
                    class="btn-info"
                    @tap="handleCancel(item.orderNumber)"
                    v-if="item.status === 'not_pay'"
                  >
                    取消订单
                  </view>
                  <view
                    class="btn-info"
                    v-if="item.status === 'not_eval'"
                    @tap="handleRemark(item)"
                  >
                    评价
                  </view>
                  <view class="btn-info" @tap="callShopPhone(item.shopTel)">联系商家</view>
                  <view
                    class="btn-error"
                    v-if="item.status === 'after_sales'"
                    @tap="handleAfterSales(item)"
                  >
                    售后详情
                  </view>
                  <view
                    class="btn-error"
                    v-if="
                      item.status === 'receive' ||
                      item.status === 'not_use' ||
                      item.status === 'not_eval'
                    "
                    @click="handleRefund(item)"
                  >
                    申请退款
                  </view>
                  <view
                    class="btn-error"
                    v-if="item.status === 'complete'"
                    @tap="anotherOrder(item)"
                  >
                    再来一单
                  </view>
                  <view
                    class="btn-error"
                    v-if="item.status === 'not_pay'"
                    @tap="openPayment(item.orderNumber, index)"
                  >
                    立即支付
                  </view>
                </view>
              </view>

              <!-- <wd-loadmore :state="state" @reload="getList" /> -->
              <view
                style="
                  width: 100%;
                  text-align: center;
                  font-size: 24rpx;
                  margin-top: 10rpx;
                  color: #888989;
                "
                v-if="isEnd"
              >
                没有更多啦~
              </view>
            </view>
            <wd-status-tip image="content" tip="暂无内容" v-else />
          </wd-tab>
        </block>
      </wd-tabs>
    </view>
    <Payment ref="PaymentRef" @payment="payNow"></Payment>
  </view>
</template>

<script setup>
import Header from './components/Header/index.vue';
import Payment from './components/Payment/index.vue';
import {
  getOrderList,
  deleteOrderApi,
  cancelOrderApi,
  repaymentApi,
  getOrderDetail,
} from '@/api/order';
import { getOrderDic } from '@/utils/orderDic';
const fileDomain = import.meta.env.VITE_APP_IMG_URL;

const stateList = ref();
onLoad((options) => {
  const orderDic = getOrderDic();
  stateList.value = orderDic.reduce((obj, item) => {
    obj[item.baseStatus] = item;
    return obj;
  }, {});
  if (options.status) {
    tab.value = options.status;
  }
  getList();
});

const tabs = ref([
  {
    name: '全部',
    value: 'all',
  },
  {
    name: '待付款',
    value: 'not_pay',
  },
  {
    name: '待使用',
    value: 'not_use',
  },
  {
    name: '待评价',
    value: 'not_eval',
  },
  {
    name: '已完成',
    value: 'complete',
  },
  {
    name: '退款/售后',
    value: 'after_sales',
  },
]);
const tab = ref('all');

onShow(() => {
  if (pendingPaymentOrder.value) {
    // 查询订单状态决定是否支付
    getOrderDetail({ orderNumber: pendingPaymentOrder.value }).then((res) => {
      console.log(res.data.baseOrder.subStatus);
      switch (res.data.baseOrder.subStatus) {
        case '1':
          xma.showToast({
            title: '支付失败',
            icon: 'error',
            duration: 2000,
          });
          pendingPaymentOrder.value = null;
          break;
        case '2':
          xma.redirectTo({
            url: `/pages/shop/paymentSuccessful?outTradeNos=${pendingPaymentOrder.value}`,
          });
          break;
        case '3':
          xma.redirectTo({
            url: `/pages/shop/paymentSuccessful?outTradeNos=${pendingPaymentOrder.value}`,
          });
          break;
        default:
          break;
      }
    });
  }
});

onPullDownRefresh(() => {
  initDataList().then(() => {
    getList();
    xma.stopPullDownRefresh();
  });
});

// 触底函数
onReachBottom(() => {
  if (dataList.value.length >= total.value) {
    isEnd.value = true;
    // state.value = 'finished';
  } else {
    getList();
  }
});

/**
 * 获取订单列表
 */
const total = ref(0);
const dataList = ref([]);
// const state = ref('loading');
const isEnd = ref(false);
const catalog = reactive({
  current: 0,
  size: 10,
  startDate: '',
  endDate: '',
  keyword: '',
  status: '', // 待付款-not_pay，待使用-not_use，待评价not_eval，退款-after_sales
  orderType: 'store', // 团购到店-store，外卖订单-takeaway，筑农物流logistics
});
const getList = async () => {
  if (isEnd.value) return;
  catalog.status = tab.value;
  if (tab.value === 'all') {
    catalog.status = '';
  }
  catalog.current++;
  // state.value = 'loading';
  xma.showLoading({
    title: '加载中...',
    mask: true,
  });
  const res = await getOrderList(catalog);
  if (res.data.records.length < catalog.size) {
    isEnd.value = true;
  }
  if (res.data.records.length > 0) {
    res.data.records.forEach((item) => {
      // 待付款倒计时计算
      if (item.status === 'not_pay') {
        item.countDown = calculateCountdown(item.createTime);
      }
    });
    dataList.value.push(...res.data.records);
    total.value = res.data.total;
  }
  // state.value = 'finished';
  xma.hideLoading();
};

/**
 * 切换状态栏
 */
const handleChange = (e) => {
  tab.value = e.name;
  initDataList().then(() => {
    getList();
  });
};

/**
 * 刷新订单列表
 */
const initDataList = () => {
  return new Promise((resolve, reject) => {
    dataList.value = [];
    total.value = 0;
    catalog.current = 0;
    isEnd.value = false;
    resolve();
  });
};

/**
 * 删除订单
 * @param {*} orderNumber
 */
const handleDelete = (orderNumber) => {
  xma.showModal({
    title: '提示',
    content: '确定要删除订单吗？',
    success: async (res) => {
      if (res.confirm) {
        xma.showLoading({
          title: '删除中...',
          mask: true,
        });
        await deleteOrderApi(orderNumber);
        xma.hideLoading();
        xma.showToast({
          title: '删除成功',
          icon: 'success',
        });
        initDataList().then(() => {
          getList();
        });
      }
    },
  });
};

/**
 * 取消订单
 * @param {*} orderNumber
 */
const handleCancel = (orderNumber) => {
  xma.showModal({
    title: '提示',
    content: '确定要取消订单吗？',
    success: async (res) => {
      if (res.confirm) {
        xma.showLoading({
          title: '取消中...',
          mask: true,
        });
        await cancelOrderApi({ orderNumber });
        xma.hideLoading();
        xma.showToast({
          title: '取消成功',
          icon: 'success',
        });
        initDataList().then(() => {
          getList();
        });
      }
    },
  });
};

/**
 * 唤起支付组件
 * @param {*} orderNumber
 */
const changeIndex = ref(0);
const PaymentRef = ref(null);
const openPayment = (orderNumber, idx) => {
  changeIndex.value = idx;
  PaymentRef.value.open(orderNumber);
};

/**
 * 立即支付
 * @param {*} orderNumber
 */
const pendingPaymentOrder = ref(null); // 待支付订单
const payNow = async (data) => {
  console.log(data);
  const param = {
    orderNumber: data.orderNumber,
    tradeType: data.selectType,
  };
  const res = await repaymentApi(param);
  const { paymentUrl, outTradeNo } = res.data.result;
  // 修改列表待付款订单号
  dataList.value[changeIndex.value].orderNumber = outTradeNo;
  pendingPaymentOrder.value = outTradeNo;
  window.location.href = paymentUrl;
};

/**
 * 计算倒计时
 */
const format = ref('mm:ss');
const calculateCountdown = (item) => {
  const now = new Date().getTime();
  const orderTime = new Date(item).getTime();
  const countdown = orderTime + 30 * 60 * 1000 - now;
  if (countdown <= 0) {
    return 0;
  }
  return countdown;
};

/**
 * 倒计时结束触发
 */
const onFinish = async (orderNumber) => {
  await cancelOrderApi({ orderNumber });
  initDataList().then(() => {
    getList();
  });
};

const handleDetail = (id) => {
  // 清空查询待付款状态
  pendingPaymentOrder.value = null;
  uni.navigateTo({
    url: `/pages/order/detail?orderNumber=${id}`,
  });
};

/**
 * 拨打商家电话
 * @param {*} phoneNumber
 */
function callShopPhone(phoneNumber) {
  // 清空查询待付款状态
  pendingPaymentOrder.value = null;
  xma.makePhoneCall({
    phoneNumber, // 仅为示例
  });
}

/**
 * 再来一单
 */
const anotherOrder = (item) => {
  // 清空查询待付款状态
  pendingPaymentOrder.value = null;
  xma.navigateTo({
    url: `/pages/shop/confirmOrder?prodId=${item.orderItems[0].prodId}&skuId=${item.orderItems[0].skuId}`,
  });
};

/**
 * 查看核销码
 */
const handleQrcode = (item) => {
  // 清空查询待付款状态
  pendingPaymentOrder.value = null;
  xma.navigateTo({
    url: `/pages/order/ticketCode?orderNumber=${item.orderNumber}`,
  });
};

/**
 * 订单评价
 */
const handleRemark = (item) => {
  xma.navigateTo({
    url: `/pages/order/remark?orderNumber=${item.orderNumber}&shopName=${item.shopName}`,
  });
};

const handleAfterSales = (item) => {
  xma.navigateTo({
    url: `/pages/order/afterSales?orderNumber=${item.orderNumber}`,
  });
};

/**
 * 申请退款
 */
const handleRefund = (item) => {
  xma.navigateTo({
    url: `/pages/order/refund?orderNumber=${item.orderNumber}`,
  });
};
</script>

<style scoped lang="scss">
page {
  background: #f3f3f3;
}

.container {
  width: 375 * 2rpx;
  margin: 0 auto;

  .tabs {
    padding-top: 44px;

    .wd-tabs {
      background-color: #f5f5f5;
    }

    &:deep(.wd-tabs__nav) {
      background-color: #f5f5f5;
    }

    &:deep(.wd-tabs__line) {
      background-color: #e9231b;
      bottom: 2px;
    }
  }
}

.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  gap: 24rpx;

  .box {
    background-color: #fff;
    width: 100%;
    border-radius: 16rpx;
    padding: 28rpx 18rpx;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    gap: 30rpx;

    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .left {
        display: flex;
        align-items: center;
        gap: 6rpx;
        font-weight: bold;

        image {
          height: 38rpx;
          width: 38rpx;
        }

        .title {
          color: #333;
          font-size: 32rpx;
          font-family: PingFang SC;
        }
      }

      .right {
        display: flex;
        align-items: center;
        gap: 6rpx;

        .status {
          color: #666;
          font-size: 28rpx;
        }
      }
    }

    .info {
      display: flex;
      gap: 20rpx;

      image {
        width: 110rpx;
        height: 110rpx;
        border-radius: 12rpx;
      }

      .info-box {
        display: flex;
        flex-direction: column;
        gap: 18rpx;

        .text {
          color: #666;
          line-height: 28rpx;
          font-size: 28rpx;
          font-family: PingFang SC;
        }
      }
    }

    .btn {
      display: flex;
      justify-content: flex-end;
      gap: 14rpx;

      .btn-info {
        width: 162rpx;
        height: 66rpx;
        border-radius: 34rpx;
        border: 1rpx solid #999999;
        color: #666;
        font-size: 28rpx;
        font-family: PingFang SC;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .btn-error {
        width: 162rpx;
        height: 66rpx;
        border-radius: 34rpx;
        border: 1rpx solid #e9231b;
        color: #e9231b;
        font-size: 28rpx;
        font-family: PingFang SC;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style>
