<template>
  <view class="tui-manage-container">
    <!-- 顶部导航栏 -->
    <view class="navbar" :style="navbarStyle">
      <view class="nav-left" @tap="goBack">
        <uni-icons type="back" size="24" color="#222" />
      </view>
      <view class="nav-title">推广官管理</view>
      <view class="nav-right">
        <!-- <uni-icons type="more-filled" size="24" color="#222" style="margin-right: 16rpx;" />
        <uni-icons type="scan" size="24" color="#222" /> -->
      </view>
    </view>
    <!-- Tab栏 -->
    <view class="tab-bar-fixed" :style="{top: navBarRealHeight + 'px'}">
      <template v-if="!searchMode">
        <view class="tab-tabs">
          <view :class="['tab-item', {active: currentTab === 0}]" @tap="switchTab(0)">全部</view>
          <view :class="['tab-item', {active: currentTab === 1}]" @tap="switchTab(1)">推广官申请列表</view>
        </view>
        <uni-icons type="search" size="28" color="#222" class="tab-search" @tap="onSearchIconClick" />
      </template>
      <template v-else>
        <view class="search-input-wrap">
          <uni-icons type="search" size="22" color="#999" />
          <input
            ref="searchInput"
            class="search-input"
            v-model="searchText"
            placeholder="请输入要查询的内容"
            placeholder-style="color:#ccc"
          />
          <uni-icons v-if="searchText" type="close" size="22" color="#ccc" @tap="onClearSearch" />
        </view>
        <text class="search-cancel" @tap="onCancelSearch">取消</text>
      </template>
    </view>
    <view class="tab-content" :style="{paddingTop: (navBarRealHeight + tabBarHeight) + 'px'}">
      <!-- 全部 -->
      <view v-if="currentTab === 0">
        <view v-for="(item, idx) in filteredTuiList" :key="idx" class="tui-card" @tap="goTuiDetail(item)">
          <view class="tui-info-row"><text class="tui-label">姓名：</text><text class="tui-value">{{ item.name }}</text></view>
          <view class="tui-info-row"><text class="tui-label">一级推广数：</text><text class="tui-value">{{ item.level1 }}人</text></view>
          <view class="tui-info-row"><text class="tui-label">二级推广数：</text><text class="tui-value">{{ item.level2 }}人</text></view>
          <view class="tui-info-row"><text class="tui-label">回收总额：</text><text class="tui-value">{{ item.totalAmount }}元</text></view>
          <view class="tui-info-row"><text class="tui-label">佣金总额：</text><text class="tui-value">{{ item.commission }}元</text></view>
        </view>
      </view>
      <!-- 推广官申请列表 -->
      <view v-if="currentTab === 1">
        <view v-for="(item, idx) in filteredApplyList" :key="idx" class="tui-card" @tap.stop="goApplyDetail(item)">
          <view class="tui-info-row"><text class="tui-value">{{ item.name }} 的推广官申请</text></view>
          <view class="tui-info-row"><text class="tui-label">电话：</text><text class="tui-value">{{ item.phone }}</text></view>
          <view class="tui-info-row"><text class="tui-label">每日可花推广时间：</text><text class="tui-value">{{ item.time }}</text></view>
          <view class="tui-info-row"><text class="tui-label">申请时间：</text><text class="tui-value">{{ item.applyTime }}</text></view>
          <view class="tui-status-bar">
            <view v-if="item.status==='待审批'" class="tui-status orange">待审批</view>
            <view v-else-if="item.status==='已驳回'" class="tui-status red">已驳回</view>
            <view v-else-if="item.status==='已确认'" class="tui-status gray">已确认</view>
          </view>
          <view class="tui-action-bar">
            <view class="tui-action" v-if="item.status==='待审批'"><uni-icons type="undo" size="32" color="#999" /><text>驳回</text></view>
            <view class="tui-action" v-if="item.status==='待审批'" ><uni-icons type="person" size="32" color="#999" /><text>审批</text></view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import pullRefreshMixin from '../mixins/pullRefreshMixin.js'
export default {
  mixins: [pullRefreshMixin],
  data() {
    return {
      currentTab: 0,
      tuiList: [],
      applyList: [
        { name: '周小艺', phone: '18899102278', time: '6小时', applyTime: '2025-03-20 11:00', status: '待审批' },
        { name: '周小艺', phone: '18899102278', time: '6小时', applyTime: '2025-03-20 11:00', status: '已驳回' },
        { name: '周小艺', phone: '18899102278', time: '6小时', applyTime: '2025-03-20 11:00', status: '已确认' },
        { name: '周小艺', phone: '18899102278', time: '6小时', applyTime: '2025-03-20 11:00', status: '待审批' },
      ],
      statusBarHeight: 0,
      navBarRealHeight: 0,
      tabBarHeight: 80, // px
      searchMode: false,
      searchText: '',
    }
  },
  computed: {
    navbarStyle() {
      return `padding-top: ${this.statusBarHeight}px;`;
    },
    filteredTuiList() {
      if (!this.searchText) return this.tuiList;
      const text = this.searchText.toLowerCase();
      return this.tuiList.filter(item =>
        (item.name && item.name.toLowerCase().includes(text)) ||
        (item.phone && item.phone.toLowerCase().includes(text))
      );
    },
    filteredApplyList() {
      if (!this.searchText) return this.applyList;
      const text = this.searchText.toLowerCase();
      return this.applyList.filter(item =>
        (item.name && item.name.toLowerCase().includes(text)) ||
        (item.phone && item.phone.toLowerCase().includes(text))
      );
    }
  },
  onLoad() {
    uni.getSystemInfo({
      success: (res) => {
        this.statusBarHeight = res.statusBarHeight || 20;
      }
    });
    this.$nextTick(() => {
      uni.createSelectorQuery().select('.navbar').boundingClientRect(rect => {
        if (rect) {
          this.navBarRealHeight = rect.height;
        }
      }).exec();
    });
    // 获取推广官列表
    this.fetchPromotionList();
    // 获取推广官申请列表
    this.fetchPromotionApplyList();
  },
  onShow() {
    this.fetchPromotionList();
    this.fetchPromotionApplyList();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    switchTab(idx) {
      this.currentTab = idx;
    },
    goTuiDetail(tui) {
      uni.navigateTo({
        url: '/pages/manager/tui-detail',
        success: (res) => {
          res.eventChannel.emit('tuiDetail', tui);
        }
      });
    },
    goApplyDetail(apply) {
      uni.navigateTo({
        url: '/pages/manager/tui-apply-detail',
        success: (res) => {
          res.eventChannel.emit('applyDetail', apply);
        }
      });
    },
    refreshData() {
      // TODO: 实现推广官列表刷新逻辑，如重新请求接口
    },
    async onRefresh() {
      await this.refreshData && this.refreshData()
    },
    async fetchPromotionList() {
      try {
        const res = await this.$api('getPromotionList', { pageSize: 1000, current: 1 });
        if (res && res.code === 200 && res.result && Array.isArray(res.result.records)) {
          this.tuiList = res.result.records.map(user => ({
            name: user.name || user.nickName || '-',
            level1: 0, // 一级推广数，暂定
            level2: 0, // 二级推广数，暂定
            totalAmount: user.money || 0,
            commission: user.price || 0,
            phone: user.phone || ''
          }));
        }
      } catch (e) {
        uni.showToast({ title: '获取推广官列表失败', icon: 'none' });
      }
    },
    async fetchPromotionApplyList() {
      try {
        const res = await this.$api('getPromotionApplyListPage', { pageSize: 1000, current: 1 });
        if (res && res.code === 200 && res.result && Array.isArray(res.result.records)) {
          this.applyList = res.result.records.map(user => ({
            id: user.id,
            name: user.name || user.nickName || '-',
            phone: user.phone || '',
            time: user.userTime || '',
            applyTime: user.createTime || '',
            status: user.status === 0 ? '待审批' : user.status === 1 ? '已确认' : user.status === 2 ? '已驳回' : ''
          }));
        }
      } catch (e) {
        uni.showToast({ title: '获取申请列表失败', icon: 'none' });
      }
    },
    onSearchIconClick() {
      this.searchMode = true;
      this.$nextTick(() => {
        this.$refs.searchInput && this.$refs.searchInput.focus();
      });
    },
    onClearSearch() {
      this.searchText = '';
    },
    onCancelSearch() {
      this.searchText = '';
      this.searchMode = false;
    },
  },
  onPullDownRefresh() {
    Promise.all([
      this.fetchPromotionList(),
      this.fetchPromotionApplyList()
    ]).finally(() => {
      uni.stopPullDownRefresh();
    });
  }
}
</script>

<style lang="scss" scoped>
.tui-manage-container {
  min-height: 100vh;
  background: #f7f7f7;
  padding-bottom: 40rpx;
}
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100rpx;
  background: #fff;
  z-index: 10;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
  padding: 0 32rpx;
  .nav-left {
    flex: 0 0 48rpx;
    display: flex;
    align-items: center;
    height: 100%;
  }
  .nav-title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: bold;
    color: #222;
    line-height: 100rpx;
  }
  .nav-right {
    flex: 0 0 80rpx;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    height: 100%;
  }
}
.tab-bar-fixed {
  position: fixed;
  left: 0;
  width: 100vw;
  z-index: 20;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-around;
  height: 80rpx;
  border-bottom: 2rpx solid #f3f3f3;
  margin: 0;
  box-sizing: border-box;
  padding-left: 0;
  padding-right: 32rpx;
}
.tab-tabs {
  display: flex;
  flex: 1;
  height: 100%;
}
.tab-item {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  color: #222;
  font-weight: 500;
  position: relative;
  padding-bottom: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.tab-item.active {
  color: #ffb400;
  font-weight: bold;
}
.tab-item.active::after {
  content: '';
  display: block;
  width: 48rpx;
  height: 6rpx;
  border-radius: 6rpx;
  background: #ffb400;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 0;
}
.tab-search {
  margin-left: 16rpx;
}
.tab-content {
  margin-top: 32rpx;
}
.tui-card {
  background: #fff;
  border-radius: 40rpx;
  margin: 0 32rpx 32rpx 32rpx;
  padding: 40rpx 36rpx 36rpx 36rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.03);
}
.tui-info-row {
  display: flex;
  align-items: center;
  margin-bottom: 18rpx;
  .tui-label {
    font-size: 30rpx;
    color: #b3b3b3;
    width: 180rpx;
    font-weight: 400;
  }
  .tui-value {
    font-size: 32rpx;
    color: #222;
    font-weight: 500;
  }
}
.tui-status-bar {
  display: flex;
  justify-content: flex-end;
  margin-top: 12rpx;
}
.tui-status {
  font-size: 28rpx;
  border-radius: 0 0 20rpx 0;
  padding: 8rpx 32rpx;
  font-weight: 400;
  &.orange {
    background: #fff7e6;
    color: #ffb400;
  }
  &.red {
    background: #ffeaea;
    color: #ff4d4f;
  }
  &.gray {
    background: #f5f5f5;
    color: #999;
  }
}
.tui-action-bar {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 24rpx;
  gap: 80rpx;
}
.tui-action {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 28rpx;
  color: #999;
  uni-icons {
    margin-bottom: 4rpx;
  }
}
.search-input-wrap {
  display: flex;
  align-items: center;
  padding: 2rpx;
  border: 1rpx solid #ccc;
  border-radius: 10rpx;
  .search-input {
    flex: 1;
    // padding: 8rpx;
  }
}
.search-cancel {
  margin-left: 16rpx;
  color: #999;
}
</style> 