<template>
  <view class="page-container">
    <view class="sticky-header">
<!--      <view class="search-wrapper">-->
<!--        <view class="query">-->
<!--          <u-row customStyle="margin-bottom: 10px" gutter="20">-->
<!--            <u-col span="9">-->
<!--              <u&#45;&#45;input-->
<!--                  @focus="timeShow = true"-->
<!--                  v-model="startTimeXd"-->
<!--                  placeholder="开始日期 ~ 结束日期"-->
<!--                  prefixIcon="calendar"-->
<!--                  prefixIconStyle="font-size: 22px;color: #909399"-->
<!--                  @clear="handleSearch"-->
<!--              ></u&#45;&#45;input>-->
<!--            </u-col>-->
<!--            <u-col span="3">-->
<!--              <view class="query-btn" @click="clearSearch">-->
<!--                <view class="query-btn-text">清空</view>-->
<!--              </view>-->
<!--            </u-col>-->
<!--          </u-row>-->
<!--        </view>-->
<!--      </view>-->
      <view class="tabs-wrapper">
        <view
            v-for="tab in tabs"
            :key="tab.key"
            class="tab-item"
            :class="{ 'active': currentTab === tab.id }"
            @click="changeTab(tab.id)"
        >
          {{ tab.name }}
        </view>
      </view>
    </view>
    <view v-if="currentTab == 1">
      <scroll-view class="list-container" scroll-y="true" @scrolltolower="loadMore" >
        <view v-if="pendingList.length === 0 && loadStatus !== 'loading'" class="empty-list">
          <text>暂无相关记录</text>
        </view>

        <view v-for="(pendInfo) in pendingList" :key="pendInfo.ywyId" class="record-card">


          <view class="card-header" @click="detail(pendInfo.ywyId,1)">
            <uni-icons type="paperclip" size="20" color="#3c82f8"></uni-icons>
            <text class="record-id" style="text-decoration: underline">{{ pendInfo.ywyName }}</text>
            <view class="status-badge pending">
              {{ getStatusText(0) }}
            </view>
          </view>


          <view class="card-body">

            <view class="detail-row product-item" v-for="(item, index) in pendInfo.detail" :key="index">
              <text class="detail-label">{{ item.categoryName }}</text>
              <text class="detail-value">{{ item.num }}</text>
            </view>
          </view>

          <view class="card-footer">
            <button class="verify-btn" @click="verify(pendInfo.ywyId)">核销</button>
          </view>
        </view>

        <uni-load-more :status="loadStatus"></uni-load-more>
      </scroll-view>
      <view class="fixed-footer" v-if="pendingList.length>0">
        <button class="add-btn" @click="verify(-1)">一键核销</button>
      </view>
    </view>
    <scroll-view class="list-container" scroll-y="true" @scrolltolower="loadMore" v-if="currentTab>1 && currentTab<4">
      <view v-if="recordList.length === 0 && loadStatus !== 'loading'" class="empty-list">
        <text>暂无相关记录</text>
      </view>

      <view v-for="record in recordList" :key="record.orderNo" class="record-card">
        <view class="card-header">
          <uni-icons type="paperclip" size="20" color="#3c82f8"></uni-icons>
          <text class="record-id" @click="detail(record.id)" style="text-decoration: underline">{{ record.orderNo }}</text>
          <view class="status-badge verifying"  v-if="record.status === 0">
            {{ getStatusText(record.status) }}
          </view>
          <view class="status-badge verified" style="background-color: #54CFAB"  v-if="record.status === 1">
            {{ getStatusText(record.status) }}
          </view>
        </view>
        <view class="card-body">
<!--          <view class="detail-row">-->
<!--            <text class="detail-label">业务员名称</text>-->
<!--            <text class="detail-value">{{ record.ywyName }}</text>-->
<!--          </view>-->
          <view class="detail-row" >
            <text class="detail-label">提交时间</text>
            <text class="detail-value">{{ record. dealerApplyTime }}</text>
          </view>

<!--          <view class="detail-row" v-if="record.status === 1">-->
<!--            <text class="detail-label">审核时间</text>-->
<!--            <text class="detail-value">{{ record.finishTime }}</text>-->
<!--          </view>-->
          <view class="detail-row">
            <text class="detail-label">商品总数</text>
            <text class="detail-value">{{ record.writeOffNum }}</text>
          </view>
          <view class="detail-row product-item" v-for="(item, index) in record.writeOffRecordDetailVos" :key="index">
            <text class="detail-label">{{ item.categoryName }}</text>
            <text class="detail-value">{{ item.num }}</text>
          </view>



        </view>

      </view>

      <uni-load-more :status="loadStatus"></uni-load-more>
    </scroll-view>
    <view v-if="currentTab == 4" style="
    padding-top: 17px;
    padding-right: 17px;">

      <view class="query-btn" style="width: 25%;float: right" @click="toHistory()">
        <view class="query-btn-icon">
        </view>
        <view class="query-btn-text">详情记录</view>
      </view>
    </view>
    <scroll-view v-if="currentTab == 4">
      <view class="data-display-container">
        <view class="header-row">
          <view class="header-item">项目</view>
          <view class="header-item">已核销</view>
          <view class="header-item">未核销</view>
        </view>

        <view class="data-body">
          <view class="data-row" v-for="(item, index) in hexiaoList" :key="index">
            <view class="data-cell item-column">{{ item.itemName }}</view>
            <view class="data-cell">{{ item.writeOffCount }}</view>
            <view class="data-cell">{{ item.waitWriteOffCount }}</view>
          </view>

        </view>
      </view>
    </scroll-view>
    <u-calendar min-date="2025-07-01" max-date="2030-07-01" @close="timeShow = false" :show="timeShow" :mode="mode" @confirm="confirm"></u-calendar>

  </view>
</template>

<script>
import {queryJxsAddRecord,doCommitToJxs,doCommitToChang, queryHexiaoRecord,queryPendingWriteOffRecord,queryWriteOffDetailByItem} from "@/api/hexiao";

export default {
  data() {
    return {
      startTime: '',
      endTime: '',
      timeShow: false,
      startTimeXd:"",
      mode: 'range',
      searchQuery: '',
      tabs: [
        { name: '待审核', key: 'pending',id: 1 },
        // { name: '核销中', key: 'verifying', id: 2},
        { name: '已提交', key: 'verified' , id :3},
        { name: '我的账户', key: 'zhanghu' , id :4},
      ],
      currentTab: 1,
      recordList: [],
      hexiaoList:[],
      pendingList:[],
      pagination: { page: 1, limit: 10 },
      loadStatus: 'more', // 'more', 'loading', 'noMore'
      isLoading: false,
    };
  },
  onLoad() {
    this.getReadyData(true);
  },
  onPullDownRefresh() {
    this.fetchRecords(true);
  },
  methods: {
    toHistory(){
      uni.navigateTo({ url: `/pages/hexiao/jxs/hexiao_record_history`});
    },
    confirm(e) {
      this.startTime = e[0];
      this.endTime = e[e.length-1];
      this.startTimeXd = e[0]+' ~ '+e[e.length-1];
      if(!this.show){
        this.handleSearch()
      }
      this.timeShow = false;

    },
    getStatusClass(status){
      const statusMap = {
        1: 'pending',
        2: 'verifying',
        3: 'verified',
      };
      return statusMap[status] || '';
    },
    getStatusText(status) {
      const statusMap = {
        0: '核销中',
        1: '已提交'
      };
      return statusMap[status] || '未知';
    },
    changeTab(tabKey) {
      if (this.currentTab === tabKey) return;
      this.currentTab = tabKey;
      if(this.currentTab  ==1){
        this.getReadyData(true);
      }else{
        if(this.currentTab == 4){
          this.itemByDetail();
          return;
        }
        this.fetchRecords(true); // 切换tab时重新加载数据
      }
    },
    getReadyData(isRefresh = false) {
      queryPendingWriteOffRecord({pageIndex:this.pagination.page,pageSize:100,ywyName:this.searchQuery}).then(res=>{
           this.pendingList = res.data.records?res.data.records:[];
      })
    },
    async fetchRecords(isRefresh = false) {
      if (this.isLoading || (this.loadStatus === 'noMore' && !isRefresh)) {
        return;
      }
      if (isRefresh) {
        this.pagination.page = 1;
        this.recordList = [];
        this.loadStatus = 'more';
      }
      this.isLoading = true;
      this.loadStatus = 'loading';


      let data = {};
      if(this.currentTab !== -1){
        data.status = this.currentTab-2;
      }
      data.startTime = this.startTime;
      data.endTime = this.endTime;
      data.pageIndex = this.pagination.page
      data.pageSize = this.pagination.limit
      queryHexiaoRecord(data).then(res=>{
        let finalData = res.data.records;
        if(!finalData){
          finalData = [];
        }
        if (finalData.length > 0) {
          this.recordList = [...this.recordList, ...finalData];
          this.pagination.page++;
          this.loadStatus = 'more';
        } else {
          this.loadStatus = 'noMore';
        }
        this.isLoading = false;
        uni.stopPullDownRefresh();
      });



    },
    detail(id,type){
      if(type == 1){
        uni.navigateTo({ url: `/pages/hexiao/jxs/hexiao_pending_detail?id=`+id });
        return;
      }
      uni.navigateTo({ url: `/pages/hexiao/jxs/hexiao_detail?id=`+id });
    },
    loadMore() {
      this.fetchRecords();
    },
    clearSearch(){
      this.startTime = "";
      this.endTime = "";
      this.startTimeXd = "";
      this.handleSearch()
    },
    handleSearch() {
      this.fetchRecords(true);
    },
    verify(id) {
      let title = "确认核销该订单吗？";
      if(id == -1){
        title = "一键核销";
      }
      uni.showModal({
        title: '提示',
        content: title,
        success: (res) => {
          if (res.confirm) {
            doCommitToChang(id).then(res=>{
              if(res.code === 0){
                this.getReadyData(true);
                uni.showToast({ title: '核销成功' });
              }else{
                uni.showToast({ title: '核销失败' });
              }

            });
          }
        }
      });
    },
    itemByDetail() {
      queryWriteOffDetailByItem({}).then(res=>{
        this.hexiaoList = res.data;
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f6fa;
}

.sticky-header {
  position: sticky;
  top: 0;
  z-index: 100;
  background-color: #f5f6fa;
}
.search-wrapper {
  padding: 20rpx;
  background-color: #ffffff;
}
.search-bar {
  display: flex;
  align-items: center;
  background-color: #f5f6fa;
  border-radius: 50rpx;
  padding: 0 25rpx;
  height: 70rpx;
}
.search-input { flex: 1; font-size: 28rpx; margin-left: 15rpx; }
.placeholder { color: #b0b0b0; }

.tabs-wrapper {
  display: flex;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 25rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;
    &.active {
      color: #3c82f8;
      font-weight: 500;
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 6rpx;
        background-color: #3c82f8;
        border-radius: 3rpx;
      }
    }
  }
}

.list-container {
  flex: 1;
  height: 100%;
}
.empty-list { text-align: center; color: #999; padding-top: 150rpx; }

.record-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  margin: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

.card-header {
  display: flex;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
  .record-id {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-left: 15rpx;
  }
}

.status-badge {
  position: absolute;
  top: 0;
  right: 0;
  padding: 8rpx 20rpx;
  font-size: 24rpx;
  color: #fff;
  border-top-right-radius: 16rpx;
  border-bottom-left-radius: 16rpx;

  &.pending { background-color: #3c82f8; }
  &.verifying { background-color: #ff9900; }
  &.verified { background-color: #909399; }
}

.card-body {
  padding-top: 10rpx;
}
.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12rpx 0;
  font-size: 28rpx;
  .detail-label { color: #666; }
  .detail-value { color: #333; }
  &.product-item {
    .detail-label { color: #333; }
    .detail-value { color: #999; }
  }
}

.card-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
}
.verify-btn {
  background-color: #3c82f8;
  color: #fff;
  font-size: 26rpx;
  padding: 0 30rpx;
  height: 60rpx;
  line-height: 60rpx;
  border-radius: 30rpx;
  margin: 0;
  &::after { border: none; }
}

.query-btn {
  background-color: #409eff;
  color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
  height: 34rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
.query-btn-icon {
  height: 32rpx;
  width: 32rpx;
  background-image:
      url("https://hyscancode.oss-cn-hangzhou.aliyuncs.com/xiaochengxu/cjx/queryIoc.png");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}
.query-btn-text {
  font-weight: 400;
  font-size: 30rpx;
  color: #F5F5F5;
}

.fixed-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #f5f6fa;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;
  z-index: 100;
}
.add-btn {
  background-color: #3c82f8;
  color: white;
  border-radius: 50rpx;
  font-size: 32rpx;
  height: 90rpx;
  line-height: 90rpx;
  &::after { border: none; }
}


.data-display-container {
  padding: 30rpx;
  font-size: 28rpx;
  color: #333;
  min-height: 100vh; /* 确保内容撑满整个视口高度 */
  box-sizing: border-box; /* 边框和内边距包含在元素的总宽度和高度内 */
}

.card {
  background-color: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08); /* 更柔和的阴影 */
  overflow: hidden; /* 确保圆角显示 */
  display: flex;
  flex-direction: column;
  max-height: calc(100vh - 60rpx); /* 卡片最大高度，留出上下padding */
}

.header-row {
  display: flex;
  flex-direction: row;
  background-color: #4A90E2; /* 品牌蓝色 */
  color: #ffffff;
  font-weight: bold;
  padding: 24rpx 0; /* 上下内边距增加 */
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.2); /* 浅色边框 */
  position: sticky; /* 头部固定 */
  top: 0;
  z-index: 10;
}

.header-item {
  flex: 1;
  text-align: center;
  padding: 0 10rpx; /* 左右内边距 */
  font-size: 28rpx;
}

.data-body-scroll {
  flex: 1; /* 占据剩余空间 */
  overflow-y: auto; /* 允许滚动 */
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
}

.data-row {
  display: flex;
  flex-direction: row;
  align-items: center; /* 垂直居中对齐 */
  padding: 20rpx 0; /* 上下内边距 */
  border-bottom: 1rpx solid #f0f0f0; /* 更细的分割线 */
  transition: background-color 0.2s ease; /* 鼠标悬停或点击的平滑过渡 */
}

.data-row:last-child {
  border-bottom: none; /* 最后一行没有底部边框 */
}

.data-row.even-row {
  background-color: #f9f9f9; /* 隔行变色 */
}

.data-row:hover {
  background-color: #eef7ff; /* 悬停效果 */
}

.data-cell {
  flex: 1;
  padding: 0 10rpx; /* 左右内边距 */
  text-align: center;
  font-size: 26rpx; /* 数据字体略小 */
  color: #555;
  word-break: break-word; /* 允许长文本在任何地方换行 */
  line-height: 1.4; /* 增加行高 */
}

.item-column {
  text-align: left;
  padding-left: 20rpx; /* 品项左边距 */
  color: #333;
  font-weight: 500;
}

.no-data {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 30rpx;
}
</style>
