<template>
  <view class="page-container">
    <!-- 订单列表 -->
    <view class="order-list pl-30 pr-30 pt-20" v-if="infiniteScroller.list && infiniteScroller.list.length">
      <block v-for="(item, index) in infiniteScroller.list" :key="index">
        <view 
          class="order-card bg-fff br-16 mb-24 shadow-sm" 
          @click="detail(index)"
          v-if="!item.hidden"
        >
          <!-- 订单头部 -->
          <view class="order-header pl-30 pr-30 pt-28" :class="{ 'invoice-mode': isInvoice }">
            <!-- 复选框 -->
            <view class="checkbox-container" v-if="isInvoice">
              <style-checkbox :checked="item.checked" @click.stop></style-checkbox>
            </view>
            <view class="flex-align-center justify-between">
              <view 
                class="order-id fs-24 fw-500" 
                :style="{ opacity: item.invoiceStatus === 1 ? 0.5 : 1 }"
              >
                <uni-icons type="document" size="20" color="#666" class="mr-12"></uni-icons>
                订单号:{{item.startChargeSeq}}
              </view>
              
              <!-- 发票状态标签 -->
              <view 
                v-if="
                  isInvoice &&
                  (item.invoiceStatus === 1 ||
                    item.invoiceStatus === 2 ||
                    item.invoiceStatus === 3)
                "
                class="invoice-status-tag flex-center fs-20 br-6 px-16 py-8"
                :class="{
                  'status-invoiced': item.invoiceStatus === 1,
                  'status-cancelled': item.invoiceStatus === 2,
                  'status-processing': item.invoiceStatus === 3
                }"
              >
                {{ isInvoiceTitles[item.invoiceStatus] }}
              </view>
            </view>
          </view>
          
          <!-- 订单信息 -->
          <view class="order-info pl-30 pr-30 pb-28" :class="{ 'invoice-mode': isInvoice }">
            <view class="flex-align-center justify-between">
              <view class="order-time fs-24 color-999">
                <uni-icons type="time" size="18" color="#999" class="mr-12"></uni-icons>
                {{item.endTime || '未结束'}}
              </view>
              <view class="order-amount flex-align-center">
                <view class="fs-32 fw-600 color-theme mr-8">¥{{ item.payAmount }}</view>
                <uni-icons type="right" size="16" color="#ccc" class="ml-8"></uni-icons>
              </view>
            </view>
          </view>
        </view>
      </block>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state flex-center flex-column" v-if="infiniteScroller.list && infiniteScroller.list.length <= 0">
      <uni-icons type="empty" size="80" color="#ccc"></uni-icons>
      <view class="fs-30 color-999 mt-24">暂无订单数据</view>
    </view>
    
    <!-- 占位符 -->
    <view class="invoice-placeholder" v-if="isInvoice"></view>
    <view class="foot-placeholder"></view>
    
    <!-- 底部操作栏 -->
    <style-bottom-view>
      <view class="foot flex-align-center" v-if="!isInvoice">
        <view
          class="flex-center ml-auto mr-40 height-72 br-72"
          style="width: 176rpx; border: 1rpx solid rgba(0, 0, 0, 0.2)"
          @click="openInvoice"
        >
          <view class="fs-28 color-333 mr-12">开发票</view>
          <uni-icons type="right" size="14" color="#333"></uni-icons>
        </view>
      </view>
      <view class="foot flex-align-center relative" v-else>
        <view
          class="height-56 flex-align-center absolute-top-left pl-30"
          style="
            background-color: #f6f7fa;
            width: 100%;
            transform: translateY(-100%);
          "
        >
          <view class="fs-28 color-theme mr-8">{{ checkedCount }}</view>
          <view class="fs-28 color-000">个订单，共</view>
          <view class="fs-28 color-theme mr-8 ml-8">{{ checkedPrice }}</view>
          <view class="fs-28 color-000">元</view>
        </view>
        <view class="flex-align-center ml-30" @click="checkPage">
          <style-checkbox :checked="checkAll"></style-checkbox>
          <view class="ml-16 fs-28 color666">本页全选</view>
        </view>
        <view class="flex-align-center ml-auto mr-20">
          <view
            class="cancel-btn mr-20 border border-theme height-80 br-80 fs-32 fw-500 color-theme flex-center"
            style="width: 180rpx"
            @click="cancelInvoice"
            >取消</view
          >
          <view
            class="mr-40 bg-theme height-80 br-80 fs-32 fw-500 color-fff flex-center"
            style="width: 216rpx"
            @click="nextInvoice"
            >下一步</view
          >
        </view>
      </view>
    </style-bottom-view>
  </view>
</template>

<script setup lang="ts">
import {
  onLoad,
  onPullDownRefresh,
  onReachBottom,
  onShow,
} from "@dcloudio/uni-app";
import { fetchOrders } from "../../api/user";
import { fetchInvoiceList } from "../../api/index";
import { useInfiniteScroll } from "../../utils/infinite-scroll";
import { ref } from "vue";
import { to } from "@/utils/navigate";
import { requireAuth } from "@/utils/auth";

const isInvoice = ref(false);
const isInvoiceing = ref(false);
const isInvoiceHistory = ref(false);
const isInvoiceTitles = ref(["未开票", "已开票", "已作废", "开票中"]);
const checkAll = ref(false);
const checkedPrice = ref(0);
const checkedCount = ref(0);

// 0-未开票 1-已开票 2-已作废 3-开票中
const infiniteScroller = useInfiniteScroll(20, (page) => {
  return fetchOrders(page, 20).then((res: any) => {
    if (res && res.list && res.list.length) {
      res.list.forEach((item: any) => {
        item.payAmount = (Number(item.payAmount) / 100).toFixed(2);
        item.checked = false;
        item.hidden = item.chargeStatus === 4 && !item.endTime;
      });
    }
    console.log(res.list)
    return res.list;
  });
});

const setCheckData = () => {
  if (!infiniteScroller.list) return;
  let count = 0;
  let price = 0;
  infiniteScroller.list.forEach((item: any) => {
    if (item.checked) {
      count++;
      price += Number(item.payAmount);
    }
  });
  checkAll.value = infiniteScroller.list
    .filter((item: any) => item.invoiceStatus === 0 && !item.hidden)
    .every((item: any) => item.checked);
  checkedCount.value = count;
  checkedPrice.value = Number(Number(price).toFixed(2));
};
const detail = (index: number) => {
  if (!infiniteScroller.list) {
    return;
  }
  if (isInvoice.value) {
    if ([0].includes(infiniteScroller.list[index].invoiceStatus)) {
      infiniteScroller.list[index].checked =
        !infiniteScroller.list[index].checked;
      setCheckData();
    }
    if ([1].includes(infiniteScroller.list[index].invoiceStatus)) {
      to(
        `/pages-common/invoice/invoice?id=${infiniteScroller.list[index].startChargeSeq}`
      );
    }
    return;
  }
  to(
    `/pages-charge/order/order?id=${infiniteScroller.list[index].startChargeSeq}`
  );
};
const openInvoice = () => {
  isInvoice.value = true;
};

const cancelInvoice = () => {
  isInvoice.value = false;
  if (!infiniteScroller.list) return;
  infiniteScroller.list.forEach((item: any) => {
    item.checked = false;
  });
  setCheckData();
};
// 获取发票历史
const openInvoiceHistory = () => {
  uni.showLoading({
    title: "请求中",
  });
  fetchInvoiceList().then((res) => {
    uni.hideLoading();
    if (res.length <= 0) {
      uni.showToast({
        title: "无开票历史",
        icon: "none",
      });
      return;
    }
    isInvoiceHistory.value = true;
  });
};
const nextInvoice = () => {
  if (!infiniteScroller.list) return;
  const checkedSeqs = infiniteScroller.list
    .filter((item: any) => item.checked)
    .map((item: any) => item.startChargeSeq);

  if (!checkedSeqs.length) {
    uni.showToast({ title: "请选择订单", icon: "none" });
    return;
  }

  isInvoiceing.value = true;
  to(`/pages-common/invoice/invoice-form?startChargeSeqs=${checkedSeqs.join(",")}`);
};
const checkPage = () => {
  if (!infiniteScroller.list) return;
  infiniteScroller.list = infiniteScroller.list.map((item: any) => {
    if (item.invoiceStatus === 0 && !item.hidden) {
      return {
        ...item,
        checked: checkAll.value ? false : true,
      };
    }
    return {
      ...item,
      checked: false,
    };
  });
  setCheckData();
};

onLoad(() => {
  if (!requireAuth()) {
    return;
  }
  infiniteScroller.refresh();
});
onShow(() => {
  if (isInvoiceing.value) {
    isInvoiceing.value = false;
    isInvoice.value = false;
    infiniteScroller.refresh();
  }
});
onPullDownRefresh(() => {
  if (isInvoice.value) {
    uni.stopPullDownRefresh();
    return;
  }
  infiniteScroller.refresh();
});
onReachBottom(() => {
  infiniteScroller.next();
});
</script>

<style lang="scss">
.page-container {
  background-color: #f5f7fa;
  min-height: 100vh;
}

.order-list {
  padding-bottom: 20rpx;
}

.order-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  
  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  }
}

.checkbox-container {
  position: absolute;
  left: 24rpx;
  top: 28rpx;
  z-index: 2;
}

.order-header {
  border-bottom: 1rpx solid #f0f0f0;
  padding-bottom: 20rpx;
}

.order-header.invoice-mode {
  padding-left: 80rpx !important;
}

.order-info {
  padding-top: 20rpx;
}

.order-info.invoice-mode {
  padding-left: 80rpx !important;
}

.order-id {
  color: #333;
  display: flex;
  align-items: center;
  white-space: nowrap;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
}

.invoice-status-tag {
  font-size: 20rpx;
  font-weight: 500;
  white-space: nowrap;
  min-width: 80rpx;
  text-align: center;
  
  &.status-invoiced {
    background-color: rgba(65, 157, 149, 0.1);
    color: #419D95;
  }
  
  &.status-cancelled {
    background-color: #ffebee;
    color: #f44336;
  }
  
  &.status-processing {
    background-color: rgba(65, 157, 149, 0.1);
    color: #419D95;
  }
}

.order-info {
  padding-top: 20rpx;
}

.order-time {
  display: flex;
  align-items: center;
}

.order-amount {
  color: #419D95;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.empty-state {
  min-height: 60vh;
  padding-top: 100rpx;
}

.invoice-placeholder {
  height: 60rpx;
}

.foot-placeholder {
  height: 112rpx;
}

.foot {
  height: 112rpx;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
}

/* 工具类 */
.shadow-sm {
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.bg-fff {
  background-color: #ffffff;
}

.br-16 {
  border-radius: 16rpx;
}

.br-12 {
  border-radius: 12rpx;
}

.br-8 {
  border-radius: 8rpx;
}

.br-6 {
  border-radius: 6rpx;
}

.p-20 {
  padding: 20rpx;
}

.px-16 {
  padding-left: 16rpx;
  padding-right: 16rpx;
}

.py-8 {
  padding-top: 8rpx;
  padding-bottom: 8rpx;
}

.mb-24 {
  margin-bottom: 24rpx;
}

.mr-28 {
  margin-right: 28rpx;
}

.mr-12 {
  margin-right: 12rpx;
}

.mr-8 {
  margin-right: 8rpx;
}

.ml-8 {
  margin-left: 8rpx;
}

.ml-16 {
  margin-left: 16rpx;
}

.ml-24 {
  margin-left: 24rpx;
}

.mt-24 {
  margin-top: 24rpx;
}

.mt-20 {
  margin-top: 20rpx;
}

.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.flex-align-center {
  display: flex;
  align-items: center;
}

.flex-column {
  display: flex;
  flex-direction: column;
}

.flex-grow {
  flex-grow: 1;
}

.flex-inline {
  display: inline-flex;
}

.justify-between {
  justify-content: space-between;
}

.bg-fff {
  background-color: #ffffff;
}

.color-333 {
  color: #333333;
}

.color-666 {
  color: #666666;
}

.color-999 {
  color: #999999;
}

.color-primary {
  color: #ff6b35;
}

.color-theme {
  color: #419D95;
}

.color-fff {
  color: #ffffff;
}

.bg-primary {
  background-color: #ff6b35;
}

.bg-theme {
  background-color: #419D95;
}

.cancel-btn {
  transition: all 0.3s ease;
  border: 2rpx solid #419D95;
  background-color: transparent;
  
  &:hover {
    background-color: rgba(65, 157, 149, 0.05);
    transform: translateY(-2rpx);
    box-shadow: 0 2rpx 8rpx rgba(65, 157, 149, 0.2);
  }
  
  &:active {
    background-color: rgba(65, 157, 149, 0.1);
    transform: translateY(0);
  }
}

.fs-20 {
  font-size: 20rpx;
}

.fs-24 {
  font-size: 24rpx;
}

.fs-28 {
  font-size: 28rpx;
}

.fs-30 {
  font-size: 30rpx;
}

.fs-32 {
  font-size: 32rpx;
}

.fs-36 {
  font-size: 36rpx;
}

.fw-500 {
  font-weight: 500;
}

.fw-600 {
  font-weight: 600;
}

.height-46 {
  height: 46rpx;
}

.height-72 {
  height: 72rpx;
}

.height-80 {
  height: 80rpx;
}

.width-96 {
  width: 96rpx;
}

.pl-30 {
  padding-left: 30rpx;
}

.pr-30 {
  padding-right: 30rpx;
}

.pt-20 {
  padding-top: 20rpx;
}

.pt-28 {
  padding-top: 28rpx;
}

.pb-28 {
  padding-bottom: 28rpx;
}

</style>
