<template>
  <view
    class="pl-30 pr-30"
    v-if="infiniteScroller.list && infiniteScroller.list.length"
  >
    <block v-for="(item, index) in infiniteScroller.list" :key="index">
      <view
        class="item flex-align-center"
        @click="detail(index)"
        v-if="!item.hidden"
      >
        <view class="mr-28" v-if="isInvoice">
          <style-checkbox :checked="item.checked"></style-checkbox>
        </view>


        <view class="flex-column flex-grow">
          <view class="flex-align-center ">
            <view
              class="fs-24 fw-500"
              :style="{ opacity: item.invoiceStatus === 1 ? 0.5 : 1 }"
              >订单号:{{item.startChargeSeq}}</view>

            <view
              v-if="
                isInvoice &&
                (item.invoiceStatus === 1 ||
                  item.invoiceStatus === 2 ||
                  item.invoiceStatus === 3)
              "
              class="flex-center ml-24 fs-24 color-000-6 width-96 height-46 br-8"
              style="background: #e5e5e5"
              >{{ isInvoiceTitles[item.invoiceStatus] }}</view
            >
          </view>

          <view class="flex-inline">
            <view class="fs-24 mt-10" style="color: rgba(0, 0, 0, 0.4)">
              {{item.endTime}}
          </view>
            <view class="ml-auto" style="text-align: right">
              <view class="fs-36 fw-500 ">
                <text>{{ item.payAmount }}</text>
                <text class="fs-24 ml-6">元</text>
                  <uni-icons  class="ml-20" type="right" size="12" color="rgba(0,0,0,0.4)"></uni-icons>
              </view>
            </view>


          </view>

        </view>


      </view>

    </block>
  </view>

  <view
    class="pt-40 flex-center fs-30"
    style="color: rgba(0, 0, 0, 0.6)"
    v-if="infiniteScroller.list && infiniteScroller.list.length <= 0"
    >暂无数据</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-primary mr-8">{{ checkedCount }}</view>
        <view class="fs-28 color-000">个订单，共</view>
        <view class="fs-28 color-primary 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="ml-auto mr-40 bg-primary height-80 br-80 fs-32 fw-500 color-fff flex-center"
        style="width: 216rpx"
        @click="nextInvoice"
        >下一步</view
      >
    </view>
  </style-bottom-view>
</template>

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

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 = () => {
  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 openInvoiceHistory = () => {
  uni.showLoading({
    title: "请求中",
  });
  fetchInvoiceList().then((res) => {
    uni.hideLoading();
    if (res.length <= 0) {
      uni.showToast({
        title: "无开票历史",
        icon: "none",
      });
      return;
    }
    isInvoiceHistory.value = true;
  });
};
const nextInvoice = () => {
  uni.showLoading({
    title: "请求中",
  });
  applyInvoice(
    infiniteScroller.list
      .filter((item: any) => item.checked)
      .map((item: any) => item.startChargeSeq)
  )
    .then((res) => {
      uni.hideLoading();
      uni.navigateToMiniProgram({
        appId: res.miniprogramAppid,
        path: res.miniprogramPath,
        success(res) {
          console.log("打开成功");
          isInvoiceing.value = true;
        },
        fail() {
          console.log("打开失败");
          cancelApplyInvoice();
        },
      });
    })
    .catch((err) => {
      uni.hideLoading();
      uni.showModal({
        content: `${err.errMsg}`,
      });
    });
};
const checkPage = () => {
  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(() => {
  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">
.item {
  height: 150rpx;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.1);
  &:last-child {
    border-bottom: none;
  }
}
.invoice-placeholder {
  height: 60rpx;
}
.foot-placeholder {
  height: 112rpx;
}
.foot {
  height: 112rpx;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}
</style>
