<template>
  <view class="page-container">
    <view class="search-wrapper">
      <view class="search-bar">
        <uni-icons type="search" size="20" color="#999"></uni-icons>
        <input
            class="search-input"
            v-model="searchQuery"
            placeholder="输入门店名称"
            placeholder-class="placeholder"
            @confirm = "handleSearch"
        />
      </view>

      <!-- 新增：审核状态Tab筛选 -->
      <view class="filter-tabs">
<!--        <view-->
<!--            class="tab-item"-->
<!--            :class="{ active: auditFilter === '' }"-->
<!--            @click="changeAuditFilter('')"-->
<!--        >-->
<!--          <text>全部</text>-->
<!--        </view>-->
        <view
            class="tab-item"
            :class="{ active: auditFilter === 0 }"
            @click="changeAuditFilter(0)"
        >
          <text>待审核</text>
        </view>
        <view
            class="tab-item"
            :class="{ active: auditFilter === 1 }"
            @click="changeAuditFilter(1)"
        >
          <text>已审核</text>
        </view>
        <view
            class="tab-item"
            :class="{ active: auditFilter === 2 }"
            @click="changeAuditFilter(2)"
        >
          <text>已驳回</text>
        </view>
      </view>
    </view>

    <!-- 修改：优化scroll-view的高度和滚动设置 -->
    <scroll-view
        scroll-y="true"
        class="list-container"
        :style="listContainerStyle"
        @scrolltolower="handleScrollToLower"
        :lower-threshold="100"
    >
      <!-- 添加加载状态提示 -->
      <view v-if="isLoading && pagination.page === 1" class="loading-wrapper">
        <text>加载中...</text>
      </view>

      <view v-if="storeList.length === 0 && !isLoading" class="empty-list">
        <text>没有找到相关门店</text>
      </view>

      <view v-for="store in storeList" :key="store.id" class="store-card">
        <!-- 新增：审核状态标签 -->
        <view v-if="store.audit_status" class="audit-tag" :class="store.audit_status">
          <text v-if="store.audit_status === 'pending'">待审核</text>
          <text v-if="store.audit_status === 'approved'">已审核</text>
          <text v-if="store.audit_status === 'rejected'">已驳回</text>
        </view>

        <view class="card-decorator"></view>
        <view class="card-content">
          <view class="card-header">
            <uni-icons type="shop-filled" size="20" color="#3c82f8"></uni-icons>
            <text class="store-name">{{ store.store_name }}</text>
          </view>
          <view class="info-grid">
            <view class="info-row">
              <text class="info-label">店主名称：</text>
              <text class="info-value">{{ store.contact_name }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">联系方式：</text>
              <text class="info-value">{{ store.contact_phone }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">门店地址：</text>
              <text class="info-value">{{ store.address }}</text>
            </view>
            <view class="info-row"   v-if="store.review_status === 2">
              <text class="info-label">驳回原因：</text>
              <text class="info-value" style="color: red">{{ store.reject_reason }}</text>
            </view>
          </view>
          <view class="action-buttons">
            <view class="action-btn" @click="viewDetails(store.id)">
              <uni-icons type="eye-filled" size="18" color="#3c82f8"></uni-icons>
              <text>详情</text>
            </view>
            <view class="action-btn" @click="dataDetail(store.id)" v-if="ywyId > 0">
              <uni-icons type="compose" size="18" color="#3c82f8"></uni-icons>
              <text>数据查看</text>
            </view>
            <view class="action-btn" @click="editStore(store.id)" v-if="ywyId === 0">
              <uni-icons type="tune-filled" size="18" color="#3c82f8"></uni-icons>
              <text>编辑</text>
            </view>
            <view class="action-btn" @click="patrolStore(store.id)" v-if="ywyId === 0 && store.review_status === 1">
              <uni-icons type="home-filled" size="18" color="#3c82f8"></uni-icons>
              <text>巡店</text>
            </view>
            <view class="action-btn delete-btn" @click="deleteStore(store.id)" v-if="ywyId === 0">
              <uni-icons type="trash-filled" size="18" color="#e54d42"></uni-icons>
              <text>删除</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 在列表最后添加一个空的占位元素 -->
      <view class="list-placeholder"></view>

      <!-- 添加底部加载状态 -->
      <view v-if="isLoading && pagination.page > 1" class="load-more">
        <text>加载更多...</text>
      </view>
      <view v-if="loadStatus === 'noMore' && storeList.length > 0" class="load-more">
        <text>没有更多数据了</text>
      </view>
    </scroll-view>

    <view class="fixed-footer" v-if="ywyId === 0">
      <button class="add-store-btn" @click="addNewStore">新增门店</button>
    </view>

    <CustomTabbar v-if="ywyId === 0" :current="1"/>
  </view>
</template>

<script>
// 您自定义tabBar的路径，请确保正确
import CustomTabbar from '@/components/cjx/tabbar_hexiao_ywy.vue';
import {getStoreList,removeRetail} from "@/api/hexiao";
export default {
  components: {
    CustomTabbar
  },
  data() {
    return {
      searchQuery: '',
      storeList: [],
      filteredList: [],
      pagination: {
        page: 1,
        limit: 10,
      },
      ywyId: 0,
      isLoading: false,
      loadStatus: 'more', // more: 可以继续加载, loading: 加载中, noMore: 没有更多数据
      auditFilter: 0, // 1 已审核 0 未审核 2 已驳回
      // 新增：防止重复触发滚动事件
      scrollTimer: null,
      isScrolling: false,
    };
  },
  computed: {
    // 计算列表容器高度
    listContainerStyle() {
      let bottomPadding = 0;
      if (this.ywyId === 0) {
        // 有底部按钮和tabbar时
        bottomPadding = 250; // rpx
      }
      return {
        height: `calc(100vh - ${this.getHeaderHeight()}px)`,
        paddingBottom: `${bottomPadding}rpx`
      };
    }
  },
  onShow(){
    this.fetchStoreList(true);
  },
  onLoad(opt) {
    if(opt.id){
      this.ywyId = opt.id;
    }
    this.fetchStoreList(true);
  },
  methods: {
    // 获取头部高度（搜索栏+筛选Tab）
    getHeaderHeight() {
      // 搜索栏高度大约 70rpx + 40rpx padding = 110rpx ≈ 55px
      // 筛选Tab高度大约 70rpx ≈ 35px
      // 总共约 90px
      return 90; // 可以根据实际情况调整
    },

    fetchStoreList(isRefresh = false) {
      if (this.isLoading || (this.loadStatus === 'noMore' && !isRefresh)) {
        return; // 防止重复加载
      }
      if (isRefresh) {
        this.pagination.page = 1;
        this.storeList = [];
        this.loadStatus = 'more';
      }

      this.isLoading = true;

      if (!isRefresh) {
        this.loadStatus = 'loading';
      }

      getStoreList(this.pagination.page, this.pagination.limit, this.searchQuery, this.ywyId, this.auditFilter).then(res=>{
        let data = res.data;
        let mockData = data.records;
        if (mockData.length > 0) {
          this.storeList = [...this.storeList, ...mockData];
          this.pagination.page++;
          this.loadStatus = mockData.length < this.pagination.limit ? 'noMore' : 'more';
        } else {
          this.loadStatus = 'noMore';
        }
        this.isLoading = false;

        // 新增：加载完成后重置滚动状态
        this.isScrolling = false;
      }).catch(err => {
        this.isLoading = false;
        this.isScrolling = false;
        console.error('加载数据失败:', err);
      });
    },

    handleSearch() {
      this.pagination.page = 1;
      this.fetchStoreList(true);
    },

    changeAuditFilter(status) {
      if (this.auditFilter !== status) {
        this.auditFilter = status;
        this.pagination.page = 1;
        this.fetchStoreList(true);
      }
    },

    // 优化滚动到底部事件处理
    handleScrollToLower() {
      // 防止重复触发
      if (this.isScrolling || this.isLoading || this.loadStatus === 'noMore') {
        return;
      }

      this.isScrolling = true;

      // 添加防抖处理
      if (this.scrollTimer) {
        clearTimeout(this.scrollTimer);
      }

      this.scrollTimer = setTimeout(() => {
        this.fetchStoreList(false);
        this.scrollTimer = null;
      }, 300);
    },

    viewDetails(id) {
      uni.navigateTo({ url: '/pages/hexiao/ywy/add_retail?edit=0&id='+id });
      console.log('查看详情 ID:', id);
    },
    dataDetail(id){
      uni.navigateTo({ url: '/pages/hexiao/ywy/retail_detail?id='+id });
      console.log('查看数据 ID:', id);
    },
    editStore(id) {
      uni.navigateTo({ url: '/pages/hexiao/ywy/add_retail?edit=1&id='+id });
    },
    patrolStore(id) {
      uni.navigateTo({ url: '/pages/hexiao/ywy/add_patrol?edit=1&id='+id });
    },
    deleteStore(id) {
      let self = this;
      uni.showModal({
        title: '确认删除',
        content: '您确定要删除这家门店吗？此操作不可恢复。',
        confirmColor: '#e54d42',
        success: (res) => {
          if (res.confirm) {
            removeRetail(id).then(() => {
              self.resetSearch();
              uni.showToast({ title: '删除成功', icon: 'success' });
            });
          }
        }
      });
    },
    resetSearch(){
      this.fetchStoreList(true);
    },
    addNewStore() {
      uni.navigateTo({ url: `/pages/hexiao/ywy/add_retail?edit=1` });
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  background-color: #f5f6fa;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* 防止页面整体滚动 */
}

.search-wrapper {
  padding: 20rpx;
  background-color: #ffffff;
  position: sticky;
  top: 0;
  z-index: 100;
  flex-shrink: 0; /* 防止搜索区域被压缩 */
}

.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;
}

/* 新增：审核状态Tab筛选样式 */
.filter-tabs {
  display: flex;
  background-color: #f5f6fa;
  border-radius: 10rpx;
  margin-top: 20rpx;
  padding: 8rpx;
  flex-shrink: 0; /* 防止Tab区域被压缩 */
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 16rpx 0;
  font-size: 26rpx;
  color: #666;
  border-radius: 8rpx;
  transition: all 0.3s;
}

.tab-item.active {
  background-color: #ffffff;
  color: #3c82f8;
  font-weight: bold;
  box-shadow: 0 2rpx 8rpx rgba(60, 130, 248, 0.2);
}

/* 新增：审核状态标签样式 */
.audit-tag {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  font-weight: bold;
  z-index: 1;
}

.audit-tag.pending {
  background-color: #fff8e1;
  color: #ff9800;
  border: 1rpx solid #ff9800;
}

.audit-tag.approved {
  background-color: #e8f5e9;
  color: #4caf50;
  border: 1rpx solid #4caf50;
}

.audit-tag.rejected {
  background-color: #ffebee;
  color: #f44336;
  border: 1rpx solid #f44336;
}

.list-container {
  flex: 1;
  padding: 0 20rpx;
  box-sizing: border-box;
  overflow: hidden; /* 确保滚动区域正常工作 */
}

/* 移除原来的padding-bottom设置，改用动态计算 */
/* .list-container.with-padding-bottom {
  padding-bottom: 250rpx;
} */

/* 加载状态样式 */
.loading-wrapper {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
}

.load-more {
  text-align: center;
  padding: 30rpx 0;
  color: #999;
  font-size: 26rpx;
  border-top: 1rpx solid #f0f0f0;
  margin-top: 20rpx;
}

.empty-list {
  text-align: center;
  color: #999;
  padding-top: 100rpx;
  font-size: 28rpx;
}

.store-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  margin-top: 20rpx;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
}

.card-decorator {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 8rpx;
  background-color: #e3efff;
}

.card-content {
  padding: 30rpx;
  padding-left: 40rpx;
}

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

.store-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-left: 15rpx;
}

.info-grid {
  margin-top: 20rpx;
  font-size: 26rpx;
  color: #666;
}

.info-row {
  margin-top: 10rpx;
}

.action-buttons {
  display: flex;
  justify-content: space-around;
  border-top: 1rpx solid #f5f5f5;
  margin-top: 30rpx;
  padding-top: 25rpx;
}

.action-btn {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #3c82f8;
}

.action-btn text {
  margin-left: 8rpx;
}

.delete-btn {
  color: #e54d42;
}

.fixed-footer {
  position: fixed;
  /* --- 关键改动 1 --- */
  /* bottom值 = 自定义tabBar的高度(100rpx) + iPhone等机型的底部安全区 */
  bottom: calc(100rpx + constant(safe-area-inset-bottom));
  bottom: calc(100rpx + env(safe-area-inset-bottom));

  left: 0;
  width: 100%;
  background-color: #f5f6fa;
  padding: 20rpx 30rpx;
  box-sizing: border-box;
  z-index: 90; // z-index比tabBar低，但比页面内容高
  flex-shrink: 0; /* 防止底部按钮区域被压缩 */
}

.add-store-btn {
  background-color: #3c82f8;
  color: white;
  border-radius: 50rpx;
  font-size: 32rpx;
  height: 90rpx;
  line-height: 90rpx;
  &::after {
    border: none;
  }
}
.list-placeholder {
  height: 150rpx; /* 这个高度应该等于底部按钮区域的高度 */
  width: 100%;
}
</style>