<template>
  <view class="container">
    <uni-card :is-shadow="true" :shadow="shadow">
      <template v-slot:title>

        <view class="header-section collapse-title">
          <uni-row>
            <uni-col :span="8">
              <view>
                <image v-if="currentUser.avatar" :src="currentUser.avatar" class="cu-avatar xl round"></image>
              </view>
            </uni-col>
            <uni-col :span="16" class="flex padding justify-between">
              <uni-row>
                <uni-col>
                  <text>{{ formData.checkerName }} </text></br>
                  <!-- <text class="collapse-summary" v-if="formData.positionText">{{ formData.positionText }} ： </text>
                  <text class="collapse-summary">{{ formData.securityLocationText }} </text> -->
                </uni-col>

              </uni-row>

            </uni-col>
          </uni-row>
        </view>
      </template>
    </uni-card>
    <!-- 顶部tab切换 -->
    <view class="tabs">
      <view v-for="(tab, index) in tabList" :key="index" :class="['tab-item', currentTab === index ? 'active' : '']"
        @click="switchTab(index)">
        {{ tab.name }}
        <view v-if="currentTab === index" class="tab-line"></view>
      </view>
    </view>

    <!-- 时间筛选 -->
    <uni-card :is-shadow="true" :shadow="shadow">

      <view class="filter">
        <view v-for="(item, index) in timeFilters" :key="index"
          :class="['filter-item', activeTimeFilter === index ? 'active' : '']" @click="changeTimeFilter(index)">
          {{ item }}
        </view>
      </view>
      <view class="filter filter-column" style="margin-top: 20rpx;" v-if="currentTab === 1">
        <text class="label">人员查询</text>
        <input v-model="keyword" class="search-input" type="text" placeholder="请输入人员姓名" @input="doFilter" />
      </view>


      <!-- 大类 -->
      <view class="form-item">
        <text class="label">查获类型筛选</text>
        <picker :value="this.activeTypeFilter" :range="typeFilters" @change="changeTypeFilter($event.detail.value)">
          <view class="picker-box">{{ typeFilters[this.activeTypeFilter] || '请选择' }}</view>
        </picker>
      </view>
      <!-- 查获类型筛选 -->
      <!-- <view class="filter" style="margin-top: 20rpx">
        <view v-for="(type, index) in typeFilters" :key="index"
          :class="['filter-item', activeTypeFilter === index ? 'active' : '']" @click="changeTypeFilter(index)">
          {{ type }}
        </view>
      </view> -->
    </uni-card>


    <uni-card :is-shadow="true" :shadow="shadow">

      <!-- 数据统计 -->
      <view class="stats">
        <view class="stat-item">
          <text class="num">{{ stats.total }}</text>
          <text class="label">查获总数</text>
        </view>
        <view class="stat-item">
          <text class="num">{{ stats.forbidden }}</text>
          <text class="label">移交公安数量</text>
        </view>
        <view class="stat-item">
          <text class="num">{{ stats.limited }}</text>
          <text class="label">故意隐匿数</text>
        </view>
      </view>
    </uni-card>

    <!-- 记录列表 -->

    <view class="record-list">
      <view v-for="(item, index) in recordList" :key="index" class="record-item" @tap="viewDetail(item)">
        <view class="item-content">
          <text class="name">{{ item.categoryNameTwo }}</text>
          <text class="location">{{ item.location }} {{ item.name }}</text>
          <text class="time">{{ item.time }}</text>
        </view>
        <view class="item-footer">
          <!-- <text class="user">{{ formData.checkerName }}</text> -->
          <!-- <text class="type" :class="'type-' + item.typeKey">{{ item.type }}</text> -->
        </view>
        <view class="arrow">></view>
      </view>
      <view v-if="recordList.length === 0" class="empty">暂无数据</view>
    </view>
  </view>
</template>

<script>
import { selectByConditions } from '@/api/seizureRecord/seizureRecord.js'
import { selectGroupCount } from '@/api/seizureRecord/seizureRecord.js'
import { treeSelectByType } from "@/api/system/common"


export default {
  data() {
    return {
      shadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
      activeTypeFilter: 0,
      typeFilters: ['全部', '违禁品', '限带品', '其他'],
      typeOptions: [],
      currentTab: 0,
      tabList: [{ name: '我的查获记录' }, { name: '本班组查获记录' }],
      activeTimeFilter: 0,
      timeFilters: ['今日', '本周', '本月'],
      recordList: [],
      stats: { total: 0, forbidden: 0, limited: 0 },
      allRows: [], // 原始数据缓存
      keyword: '',   // 人员姓名关键字
      dataType: 'ALL',


      formData: {
        // 安检员信息
        checkerId: this.$store.state.user.id,
        checkerName: this.$store.state.user.name,
        positionText: '安检员',
        securityLocationText: 'T3航站楼',

      },
    }
  },
  onLoad() {
    this.loadData()
  },
  computed: {
    currentUser() {
      return this.$store.state.user;
    },

  },
  methods: {
    // 扁平化 children 成 [{ label, code }]
    getChildrenOptions(tree) {
      return tree.flatMap(node => (node.children || []).map(c => ({
        label: c.label,
        code: c.code
      })));
    },
    /* 切换 tab / 时间 / 类型 都重新拉数据+过滤 */
    changeTypeFilter(idx) {
      const selectedCode = this.typeOptions[idx - 1].code;
      console.log("selectedCode===", selectedCode)
      this.dataType = selectedCode
      this.loadData();

      this.activeTypeFilter = idx
      // this.doFilter()
    },
    switchTab(idx) {
      this.currentTab = idx
      this.loadData()
    },
    changeTimeFilter(index) {
      this.activeTimeFilter = index
      this.loadData()
    },

    /* 调接口拿到原始数据 */
    async loadData() {
      uni.showLoading({ title: '加载中' })
      try {
        // 真实项目换成自己的封装方法

        const res = await selectByConditions({
          timeType: this.activeTimeFilter + 1,
          recordType: this.currentTab + 1,
          inspectUserId: this.$store.state.user.id,
          seizureType: this.dataType,
          pageNum: 1,
          pageSize: 500,
          // tab: this.currentTab,
          // time: this.activeTimeFilter
        })

        if (res.code === 200) {
          this.allRows = res.rows || []
          this.doFilter()
        }


        const [itemCategoryRes] = await Promise.all([
          treeSelectByType("ITEM_CATEGORY", 2)
        ]);


        // 先拉类型树
        const [{ data: typeTree }] = await Promise.all([
          treeSelectByType("ITEM_CATEGORY", 2)
        ]);
        this.typeOptions = this.getChildrenOptions(typeTree);   // [{label,code}]
        this.typeFilters = ['全部', ...this.typeOptions.map(o => o.label)];
        const count = await selectGroupCount({
          timeType: this.activeTimeFilter + 1,
          recordType: this.currentTab + 1,
          inspectUserId: this.$store.state.user.id,
          seizureType: this.dataType

          // tab: this.currentTab,
          // time: this.activeTimeFilter
        })
        this.stats.total = count.data.total;
        this.stats.forbidden = count.data.policeTotal
        this.stats.limited = count.data.concealTotal
        console.log("count", count)



        console.log("typeFilters", this.typeFilters)

      } catch (e) {
        console.log("e===", e)
        uni.showToast({ title: '加载失败', icon: 'none' })
      } finally {
        uni.hideLoading()
      }
    },

    doFilter() {
      let list = this.allRows;
      // 第 0 个永远是“全部”
      if (this.activeTypeFilter > 0) {
        const selectedCode = this.typeOptions[this.activeTypeFilter - 1].code;
        console.log("list", list);
        console.log("selectedCode", selectedCode);

        list = list.filter(v => v.categoryCodeTwo === selectedCode);
      }
      /* 新增：人员姓名搜索（仅本班组） */
      if (this.currentTab === 1 && this.keyword.trim()) {
        list = list.filter(v =>
          (v.inspectUserName || '').includes(this.keyword.trim())
        );
      }

      this.recordList = list.map(v => ({
        id: v.id,
        name: v.inspectUserName || '-',
        type: v.checkMethodDesc,
        location: v.regionalName || '-',
        time: v.seizureTime || '-',
        categoryNameOne: v.categoryNameOne,
        categoryNameTwo: v.categoryNameTwo
      }));

      this.stats.total = this.recordList.length;
      this.stats.forbidden = list.filter(v => v.handlingMethodDesc === '移交机场公安').length;
      this.stats.limited = list.filter(v => v.isActiveConcealment === 1).length;
    },

    viewDetail(item) {
      uni.navigateTo({ url: '/pages/seizureRecord/detail?id=' + item.id });
    },

    /* 模拟接口：直接把题目给的返回值包一层 Promise */
    mockApi() {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve({
            code: 200,
            rows: [
              {
                id: 5,
                remark: '打火机',
                checkMethodDesc: '违禁品',
                inspectUserName: '张三',
                channelName: 'A区安检口',
                seizureTime: '2025-07-15 18:42:09'
              },
              {
                id: 6,
                remark: '矿泉水',
                checkMethodDesc: '限带品',
                inspectUserName: '李四',
                channelName: 'B区安检口',
                seizureTime: '2025-07-15 19:00:00'
              }
            ]
          })
        }, 300)
      })
    }
  }
}
</script>


<style>
.container {
  padding: 20rpx;
}

.tabs {
  display: flex;
  height: 80rpx;
  margin-bottom: 20rpx;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #2979FF;
  font-weight: bold;
}

.tab-line {
  width: 60rpx;
  height: 6rpx;
  background: #2979FF;
  border-radius: 3rpx;
  position: absolute;
  bottom: 0;
}

.filter {
  display: flex;
  margin-bottom: 20rpx;
}

.filter-item {
  padding: 10rpx 20rpx;
  margin-right: 20rpx;
  border-radius: 30rpx;
  background: #f5f5f5;
  color: #666;
}

.filter-item.active {
  background: #2979FF;
  color: #fff;
}

.stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 10rpx;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.num {
  font-size: 36rpx;
  font-weight: bold;
  color: #2979FF;
}

.label {
  font-size: 24rpx;
  color: #999;
}

.item-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.name {
  font-size: 32rpx;
  font-weight: bold;
}

.type {
  padding: 0 10rpx;
  background: #ff4d4f;
  color: #fff;
  border-radius: 4rpx;
  font-size: 24rpx;
}

.item-footer button {
  width: 160rpx;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 26rpx;
  background: #2979FF;
  color: #fff;
}

.empty {
  padding: 60rpx 0;
  text-align: center;
  color: #999;
}

.type-1 {
  background: #ff4d4f;
}

.type-2 {
  background: #faad14;
}

.type-3 {
  background: #52c41a;
}

.record-list {
  padding: 30rpx;
  display: flex;
  flex-direction: column;
}

.record-item {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.item-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}



.location {
  font-size: 28rpx;
  color: #666;
}

.time {
  font-size: 28rpx;
  color: #999;
}

.item-footer {
  display: flex;
  align-items: center;
}

.user {
  font-size: 28rpx;
  color: #666;
}

.type {
  padding: 0 10rpx;
  background: #ff4d4f;
  color: #fff;
  border-radius: 4rpx;
  font-size: 24rpx;
  margin-left: 10rpx;
}

.arrow {
  width: 30rpx;
  height: 30rpx;
  /* background: url('path/to/arrow.png') no-repeat center center; */
  background-size: contain;
}

.empty {
  padding: 60rpx 0;
  text-align: center;
  color: #999;
}

.picker-box {
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 30rpx;
}

.label {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.filter-column {
  display: flex;
  flex-direction: column;
}

.search-input {
  width: 100%;
  height: 80rpx;
  /* 明显加高 */
  line-height: 96rpx;
  padding: 0 24rpx;
  font-size: 30rpx;
  border: 1rpx solid #ddd;
  border-radius: 12rpx;
  box-sizing: border-box;
}
</style>
