<template>
  <view class="audits-container">

    <!-- 新增搜索栏 -->
    <view class="search-bar">
      <!-- 修改后的搜索栏 -->
      <view class="search-bar">
        <u-search
            placeholder="请输入姓名或完整手机号搜索"
            v-model="searchKeyword"
            @search="handleSearch"
            @clear="handleClearSearch"
            :show-action="false"
            bg-color="#FFFFFF"
            shape="round"
            :search-icon="'/static/ic_search_gray.png'"
        ></u-search>
      </view>
    </view>
    <!-- 员工审核列表 -->
    <scroll-view
        class="list-container"
        scroll-y
        :refresher-enabled="true"
        refresher-background="#f7f7f7"
        :refresher-triggered="refresherTriggered"
        @refresherrefresh="onRefresh"
        @scrolltolower="loadMore"
        :lower-threshold="50"
        scroll-with-animation>

      <!-- 员工审核卡片 -->
      <view v-for="(item, index) in list" :key="index" class="employee-card">
        <!-- 左侧头像 -->
        <image class="avatar" :src="item.img || '/static/ic_avg.png'"/>

        <!-- 右侧信息 -->
        <view class="info-container">
          <view class="name-row">
            <text class="name">{{ item.userName }}</text>
            <image
                class="gender-icon"
                :src="item.gender === 1 ? '/static/ic_man.png' : '/static/ic_women.png'"
            />
          </view>
          <text class="phone">{{ item.phone }}</text>
        </view>
        <!-- 编辑图标 -->
        <image
            class="edit-icon"
            src="/static/ic_edit.png"
            @click="handleCardClick(item)"
        />
        <!-- 审核状态 - 精确贴合右上角 -->
        <view class="date-badge">
          {{ formatDate(item.createTime) }}
        </view>
      </view>

      <!-- 底部加载提示 -->
      <view v-if="loading" class="loading-text">加载中...</view>
      <view v-if="noMore" class="loading-text">没有更多数据了</view>
      <view v-if="searchKeyword && list.length === 0" class="loading-text">未找到匹配结果</view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      list: [], // 员工列表数据
      pageNum: 1, // 当前页码
      pageSize: 10, // 每页数量
      noMore: false, // 是否没有更多数据
      loading: false, // 加载状态
      refresherTriggered: false, // 下拉刷新状态
      searchKeyword: '', // 搜索关键词
    };
  },
  created() {
    this.loadData();
  },
  methods: {
    // 下拉刷新
    async onRefresh() {
      this.refresherTriggered = true;
      this.pageNum = 1;
      this.noMore = false;
      await this.loadData();
      this.refresherTriggered = false;
    },
    // 滚动加载更多
    async loadMore() {
      if (this.loading || this.noMore) return;
      this.pageNum++;
      await this.loadData();
    },
    // 请求数据
    async loadData() {
      this.loading = true;
      try {
        // 判断搜索内容是否是手机号（简单判断）
        const isPhone = /^[0-9]{11}$/.test(this.searchKeyword);

        let params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          unitId: uni.getStorageSync('lifeData').vuex_user.unitId,
          isAudit: 1
        };

        // 根据输入内容决定使用哪个搜索字段
        if (this.searchKeyword) {
          if (isPhone) {
            params.phone = this.searchKeyword;
          } else {
            params.userName = this.searchKeyword;
          }
        }

        let res = await this.$u.api.unit.queryEmployee(params);
        if (res.code == "200") {
          let rows = res.rows || [];
          if (rows.length < this.pageSize) {
            this.noMore = true;
          }

          if (this.pageNum === 1) {
            this.list = rows;
          } else {
            this.list = [...this.list, ...rows];
          }
          await this.getImageUrl();
        }
      } catch (e) {
        console.error(e);
      } finally {
        this.loading = false;
      }
    },
    // 点击卡片事件
    handleCardClick(item) {
      uni.navigateTo({
        url: `/pages/sys/workbench/unitManagement/employeeEdit?id=${item.id}`
      });
    },
    async getImageUrl() {
      // 收集所有需要获取链接的图片ID
      const imgIds = [];
      const imgIdToIndexMap = []; // 保存图片ID对应的list索引

      for (let i = 0; i < this.list.length; i++) {
        const item = this.list[i];
        if (item.img) {
          imgIds.push(item.img);
          imgIdToIndexMap.push({
            id: item.img,
            index: i
          });
        }
      }

      // 如果有图片ID需要处理，则调用API一次获取所有图片链接
      if (imgIds.length > 0) {
        console.log(imgIds);
        try {
          const imgRes = await this.$u.api.getImageUrl({}, imgIds.join(','));
          if (imgRes.code == 200 && imgRes.data) {
            // 将返回的图片URL映射回对应的list项
            imgRes.data.forEach(imgItem => {
              const mapping = imgIdToIndexMap.find(m => m.id === imgItem.ossId);
              if (mapping) {
                this.$set(this.list[mapping.index], 'img',  this.vuex_config.imgUrl+imgItem.url);
              }
            });
          }
          console.log(this.list);
        } catch (error) {
          console.error('获取图片链接失败:', error);
        }
      }
    },
    // 新增搜索方法
    handleSearch() {
      this.pageNum = 1;
      this.noMore = false;
      if (this.searchKeyword) {
        // 如果有搜索关键词，使用本地过滤
        this.refresherTriggered = true;
        setTimeout(() => {
          this.refresherTriggered = false;
        }, 500);
      } else {
        // 如果没有搜索关键词，重新加载数据
        this.onRefresh();
      }
    },
    // 新增清除搜索方法
    handleClearSearch() {
      this.searchKeyword = '';
      this.onRefresh();
    },
    // 格式化日期为YYYY-MM-DD
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);

      // 获取年月日
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 补零
      const day = date.getDate().toString().padStart(2, '0'); // 补零

      return `${year}-${month}-${day}`;
    }
  }
};
</script>

<style scoped>
.audits-container {
  height: calc(100vh - (44px + env(safe-area-inset-top)));
  background-color: #f7f7f7;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.list-container {
  flex: 1;
  padding: 28rpx 30rpx;
  box-sizing: border-box;
}

.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: 24rpx;
}

.info-container {
  flex: 1;
  padding-right: 100rpx; /* 为状态标签留出空间 */
}

.name-row {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.name {
  font-size: 36rpx;
  color: #333;
  font-weight: bold;
  margin-right: 20rpx;
}

.gender-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 20rpx;
}

.phone {
  font-size: 26rpx;
  color: #999;
}

.employee-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  position: relative;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
  overflow: hidden; /* 新增：确保状态标签圆角贴合 */
}

.date-badge {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 28rpx;
  padding: 6rpx 12rpx;
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;
  width: 28%;
  text-align: left;
  color: #ADADAD;
}


.loading-text {
  text-align: center;
  color: #999;
  font-size: 26rpx;
  padding: 20rpx;
}

/* 隐藏滚动条 */
.list-container {
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.list-container::-webkit-scrollbar {
  display: none;
}

:deep .list-container ::-webkit-scrollbar {
  display: none !important;
  width: 0 !important;
  height: 0 !important;
  background-color: transparent !important;
}

/* 新增搜索栏样式 */
.search-bar {
  padding: 20rpx 17rpx;
  background-color: #f7f7f7;
  position: sticky;
  top: 0;
  z-index: 10;
}


/* 调整列表容器上边距 */
.list-container {
  flex: 1;
  padding: 0 30rpx 28rpx 30rpx; /* 上边距改为0，因为搜索栏已经有padding */
  box-sizing: border-box;
}

/* 新增编辑图标样式 */
.edit-icon {
  width: 50rpx;
  height: 50rpx;
  position: absolute;
  right: 50rpx;
  top: 60%;
  transform: translateY(-50%);
  z-index: 2;
  bottom: 50rpx;
}


</style>