<template>
  <view class="page-container">
    <view class="sticky-header">
      <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 class="search-wrapper">
        <view class="query">
          <u-row customStyle="margin-bottom: 10px" gutter="20">
            <u-col span="9">
              <u--input
                  @focus="timeShow = true"
                  v-model="startTimeXd"
                  placeholder="开始日期 ~ 结束日期"
                  prefixIcon="calendar"
                  prefixIconStyle="font-size: 22px;color: #909399"
                  @clear="handleSearch"
              ></u--input>
            </u-col>
            <u-col span="3">
              <view class="query-btn" @click="clearSearch">
                <view class="query-btn-text">清空</view>
              </view>
            </u-col>
          </u-row>

          <!-- 新增：门店名称搜索框 -->
          <u-row customStyle="margin-bottom: 10px" gutter="20" v-if="currentTab === 3">
            <u-col span="12">
              <u--input
                  v-model="storeNameQuery"
                  placeholder="请输入门店名称"
                  prefixIcon="search"
                  prefixIconStyle="font-size: 22px;color: #909399"
                  @confirm="handleSearch"
                  @clear="handleSearch"
                  clearable
              ></u--input>
            </u-col>
          </u-row>
        </view>
      </view>
    </view>

    <!-- 门店汇总显示区域 - 表格形式 -->
    <view v-if="currentTab === 3" class="store-summary-container">
      <scroll-view class="summary-list" scroll-y="true">
        <view v-if="summaryList.length === 0" class="empty-list">
          <text>暂无汇总数据</text>
        </view>

        <view v-else class="summary-table-wrapper">
          <!-- 表头 -->
          <view class="table-header">
            <view class="header-cell store-col">门店</view>
            <view class="header-cell product-col">品相</view>
            <view class="header-cell number-col">数量</view>
          </view>

          <!-- 表格内容 -->
          <view class="table-body">

            <!-- 每个门店的第一行 -->
            <view class="table-row" v-for="(store, storeIndex) in summaryList" :key="storeIndex">
              <view class="table-cell store-col">
                <view class="store-name-cell">
                  <uni-icons type="shop" size="16" color="#3c82f8"></uni-icons>
                  <text class="store-name-text">{{ store.storeName }}</text>
                </view>
              </view>
              <view>
                <view class="table-row-cl2" v-for="(item, itemIndex) in store.writeOffRecordDetailVos" :key="itemIndex">
                  <view class="table-cell product-col">
                    <text>{{ item.item }}</text>
                  </view>
                  <view class="table-cell number-col">
                    <text>{{ item.writeOffAmount }}</text>
                  </view>
                </view>
                <view class="table-row-cl2 ">
                  <view class="table-cell product-col">
                    <text>汇总</text>
                  </view>
                  <view class="table-cell number-col">
                    <text style="color: orange;">{{ store.summaryCount }}</text>
                  </view>
                </view>

              </view>


            </view>

          </view>

        </view>
      </scroll-view>
    </view>
    <!-- 原有记录列表（tab 0-2时显示） -->
    <scroll-view
        v-else
        class="list-container"
        scroll-y="true"
        @scrolltolower="loadMore"
    >
      <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.orderNo)" style="text-decoration: underline">{{ record.orderNo }}</text>
          <view class="status-badge pending" v-if="record.status === 0">
            {{ getStatusText(record.status) }}
          </view>
          <view class="status-badge verifying"  v-if="record.status === 1">
            {{ getStatusText(record.status) }}
          </view>
          <view class="status-badge verified"  v-if="record.status === 2">
            {{ getStatusText(record.status) }}
          </view>
        </view>

        <view class="card-body">
          <view class="detail-row">
            <text class="detail-label">门店名称</text>
            <text class="detail-value">{{ record.storeName }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">上传时间</text>
            <text class="detail-value">{{ record.uploadTime }}</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 class="detail-row" v-if="record.status === 1 ||record.status === 2">
            <text class="detail-label">提交时间</text>
            <text class="detail-value">{{ record.applyTime }}</text>
          </view>

          <view class="detail-row" v-if="record.status === 2">
            <text class="detail-label">审核时间</text>
            <text class="detail-value">{{ record.writeOffTime }}</text>
          </view>
        </view>

        <view class="card-footer" v-if="record.status === 0">
          <button class="verify-btn" @click="verify(record.id,record.orderNo)">一键核销</button>
        </view>
      </view>

      <uni-load-more :status="loadStatus"></uni-load-more>
    </scroll-view>

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

<script>
import {queryAddRecord, doCommitToJxs, queryStoreSummary} from "@/api/hexiao"; // 假设新的接口

export default {
  data() {
    return {
      startTime: '',
      endTime: '',
      timeShow: false,
      startTimeXd: "",
      mode: 'range',
      storeNameQuery: '', // 新增：门店名称查询条件
      searchQuery: '',
      tabs: [
        { name: '待核销', key: 'pending', id: 0 },
        { name: '核销中', key: 'verifying', id: 1},
        { name: '已核销', key: 'verified', id: 2},
        { name: '门店汇总', key: 'all', id: 3},
      ],
      currentTab: 0,
      recordList: [],
      summaryList: [
        {
          writeOffRecordDetailVos:[]
        }
      ], // 门店汇总数据
      grandTotal: 0, // 总计数量
      pagination: { page: 1, limit: 10 },
      loadStatus: 'more', // 'more', 'loading', 'noMore'
      isLoading: false,
    };
  },
  onLoad() {
    this.fetchRecords(true);
  },
  onPullDownRefresh() {
    if (this.currentTab === 3) {
      this.fetchStoreSummary(true);
    } else {
      this.fetchRecords(true);
    }
  },
  methods: {
    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 = {
        0: 'pending',
        1: 'verifying',
        2: 'verified'
      };
      return statusMap[status] || '';
    },

    getStatusText(status) {
      const statusMap = {
        0: '待核销',
        1: '核销中',
        2: '已核销'
      };
      return statusMap[status] || '未知';
    },

    changeTab(tabKey) {
      if (this.currentTab === tabKey) return;
      this.currentTab = tabKey;

      if (this.currentTab === 3) {
        // 切换到门店汇总tab
        this.fetchStoreSummary(true);
      } else {
        // 切换到其他tab（0-2）
        this.fetchRecords(true);
      }
    },

    async fetchStoreSummary(isRefresh = false) {
      if (this.isLoading) return;

      this.isLoading = true;

      try {
        const params = {
          startTime: this.startTime,
          endTime: this.endTime,
          storeName: this.storeNameQuery // 新增：门店名称参数
        };

        const res = await queryStoreSummary(params);
        if (res.code === 0) {
          this.summaryList = res.data || [];
          this.grandTotal = res.data.grandTotal || 0;
        } else {
          this.summaryList = [];
          this.grandTotal = 0;
          uni.showToast({ title: '获取汇总数据失败', icon: 'none' });
        }
        console.log('this.summaryList',this.summaryList)

        console.log('this.summaryList',this.summaryList.length)
      } catch (error) {
        console.error('获取门店汇总失败:', error);
        this.summaryList = [];
        this.grandTotal = 0;
      } finally {
        this.isLoading = false;
        uni.stopPullDownRefresh();
      }
    },

    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;
      }
      data.startTime = this.startTime;
      data.endTime = this.endTime;
      data.storeName = this.storeNameQuery; // 新增：门店名称参数
      data.pageIndex = this.pagination.page
      data.pageSize = this.pagination.limit

      queryAddRecord(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){
      uni.navigateTo({ url: `/pages/hexiao/ywy/hexiao_detail?id=`+id });
    },

    loadMore() {
      if (this.currentTab === 3) {
        // 门店汇总不需要分页加载
        return;
      }
      this.fetchRecords();
    },

    clearSearch(){
      this.startTime = "";
      this.endTime = "";
      this.startTimeXd = "";
      this.storeNameQuery = ""; // 清空门店名称查询
      this.handleSearch()
    },

    handleSearch() {
      if (this.currentTab === 3) {
        this.fetchStoreSummary(true);
      } else {
        this.fetchRecords(true);
      }
    },

    verify(id,orderNo) {
      uni.showModal({
        title: '提示',
        content: `确认核销订单 ${orderNo} 吗？`,
        success: (res) => {
          if (res.confirm) {
            doCommitToJxs(id).then(res=>{
              if(res.code === 0){
                this.fetchRecords(true);
                uni.showToast({ title: '核销成功' });
              }else{
                uni.showToast({ title: '核销失败' });
              }
            });
          }
        }
      });
    }
  }
}
</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;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.query {
  .u-row {
    margin-bottom: 16rpx !important;

    &:last-child {
      margin-bottom: 0 !important;
    }
  }

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

.tabs-wrapper {
  display: flex;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  margin-top: 4rpx;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 25rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;
    transition: all 0.3s ease;

    &.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;
        transition: all 0.3s ease;
      }
    }

    &:active {
      background-color: rgba(60, 130, 248, 0.05);
    }
  }
}

.query-btn {
  background-color: #409eff;
  color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
  height: 34rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s ease;

  &:active {
    background-color: #3080e0;
    transform: scale(0.98);
  }
}

.query-btn-text {
  font-weight: 400;
  font-size: 30rpx;
  color: #F5F5F5;
}

/* 门店汇总样式 - 表格形式 */
.store-summary-container {
  //flex: 1;
  background-color: #f5f6fa;
  overflow: auto;
  height: 100%;
}

.summary-list {
  height: 100%;
}

.summary-table-wrapper {
  background-color: #ffffff;
  border-radius: 16rpx;
  margin: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.table-header {
  display: flex;
  background-color: #f8f9fa;
  padding: 24rpx 20rpx;
  border-bottom: 1rpx solid #e8e8e8;

  .header-cell {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    text-align: center;

    &.store-col {
      width: 220rpx;
      flex-shrink: 0;
    }

    &.product-col {
      flex: 1;
    }

    &.number-col {
      width: 150rpx;
      flex-shrink: 0;
      text-align: center;
    }
  }
}

.table-body {
  .table-row {
    display: flex;
    align-items: center;
    padding: 0 20rpx;
    min-height: 100rpx;
    border-bottom: 1rpx solid #a5a5a5;

    .table-cell {
      font-size: 28rpx;
      color: #333;
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      min-height: 100rpx;
      box-sizing: border-box;

      &.store-col {
        width: 220rpx;
        flex-shrink: 0;

        .store-name-cell {
          display: flex;
          align-items: center;

          uni-icons {
            margin-right: 10rpx;
          }

          .store-name-text {
            font-weight: 500;
          }
        }
      }

      &.product-col {
        flex: 1;
      }

      &.number-col {
        width: 150rpx;
        flex-shrink: 0;
        text-align: right;
        justify-content: flex-end;
      }
    }
  }

  .store-divider {
    height: 1rpx;
    background-color: #f0f0f0;
    margin: 0 20rpx;
  }
}

.table-footer {
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  min-height: 100rpx;
  background-color: #f0f7ff;
  border-top: 2rpx solid #3c82f8;

  .footer-cell {
    font-size: 30rpx;
    font-weight: bold;
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    min-height: 100rpx;
    box-sizing: border-box;

    &.store-col {
      width: 220rpx;
      flex-shrink: 0;
    }

    &.product-col {
      flex: 1;
      justify-content: flex-end;
      padding-right: 10rpx;

      .total-label {
        color: #333;
      }
    }

    &.number-col {
      width: 150rpx;
      flex-shrink: 0;
      text-align: right;

      .total-number {
        color: #3c82f8;
        font-size: 32rpx;
      }
    }
  }
}

.empty-list {
  text-align: center;
  color: #999;
  padding-top: 150rpx;
}

/* 原有样式保持不变 */
.list-container {
  flex: 1;
  height: 100%;
}

.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: #54CFAB; }
}

.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;
  transition: all 0.3s ease;

  &:active {
    background-color: #2c72e8;
    transform: scale(0.98);
  }

  &::after { border: none; }
}

.table-row-cl2{
  display: flex;
}

/* 响应式调整 */
@media (max-width: 375px) {
  .search-wrapper {
    padding: 15rpx;
  }

  .tabs-wrapper {
    .tab-item {
      font-size: 26rpx;
      padding: 20rpx 0;
    }
  }

  .query-btn-text {
    font-size: 28rpx;
  }
}
</style>
