<template>
  <div class="seller-records gradient-background-circles">
    <!-- 使用 GeneralHeader 替换 MobileHeader -->
    <GeneralHeader
      :showLanguageList="true"
      :title="t('transaction_records')"
      color="black"
      style="box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); z-index: 999"
    />

    <div style="padding: 16px; position: relative; z-index: 2">
      <!-- 搜索框 -->
      <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px">
        <div
          style="
            flex: 1;
            min-width: 0;
            border-radius: 32px;
            border: 1px solid #fff;

            box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.25);
            padding: 0 8px;

            display: flex;
            align-items: center;
            height: max-content;
          "
        >
          <img src="../../assets/icon/search.png" alt="" width="24px" style="opacity: 0.6" />
          <input
            v-model="searchQuery"
            type="text"
            :placeholder="t('enter_user_id')"
            style="
              width: 100%;
              outline: none;
              border: none;
              background-color: transparent;
              color: black;
              padding: 10px 8px;
            "
            @keyup.enter="debouncedSearch"
          />
        </div>

        <div v-if="!hasSearched && searchQuery" style="font-weight: 600" @click="debouncedSearch">
          {{ t('search') }}
        </div>
        <div v-else style="font-weight: 600" @click="clearSearch">{{ t('cancel') }}</div>
      </div>

      <!-- 标签按钮 -->
      <div style="display: flex; position: relative; margin-bottom: 16px">
        <button
          v-for="tab in tabs"
          :key="tab.id"
          ref="tabItems"
          @click="switchTab(tab)"
          :style="{
            flex: 1,
            padding: '8px 16px',
            background: 'transparent',
            border: 'none',
            fontWeight: '600',
            fontSize: '14px',
            color: selectedTab.id === tab.id ? '#8B5CF6' : 'rgba(0, 0, 0, 0.6)',
            cursor: 'pointer',
            transition: 'all 0.3s',
            position: 'relative',
          }"
        >
          {{ t(tab.langKey) }}
        </button>
        <!-- 下划线元素 -->
        <div
          style="width: 15px; height: 3px; background-color: #bb92ff"
          :style="underlineStyle"
        ></div>
      </div>

      <!-- 用户列表(加载中...) -->
      <div
        v-if="loading && !records.length"
        style="
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 60px 20px;
          color: #666;
        "
      >
        <!-- 加载动画 -->
        <div class="loading-spinner"></div>

        <!-- 提示文本 -->
        <p style="margin: 0; font-size: 14px">{{ t('loading') }}...</p>
      </div>

      <!-- 用户列表(加载完...) -->
      <div v-else style="display: flex; flex-direction: column; gap: 12px">
        <!-- 用户项 -->
        <div
          v-for="record in records"
          :key="record.id"
          style="
            background-color: white;
            padding: 16px;

            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 4px;
          "
        >
          <!-- 个人资料 -->
          <div
            style="
              flex: 1;
              min-width: 0;
              align-self: stretch;

              display: flex;
              align-items: center;
              gap: 4px;
            "
          >
            <!-- 头像 -->
            <div
              style="
                width: 3.5em;
                align-self: stretch;
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <img
                :src="
                  (record.type
                    ? record.acceptUserAccount.userAvatar
                    : record.userAccount.userAvatar) || ''
                "
                alt=""
                style="
                  display: block;
                  width: 100%;
                  aspect-ratio: 1/1;
                  border-radius: 50%;
                  object-fit: cover;
                "
                @error="handleAvatarImageError"
              />
            </div>

            <!-- 个人资料 -->
            <div
              style="
                flex: 1;
                min-width: 0;
                align-self: stretch;

                display: flex;
                flex-direction: column;
                justify-content: space-around;
                gap: 4px;
              "
            >
              <!-- 名称 -->
              <div
                style="
                  font-size: 0.9em;
                  font-weight: 600;
                  color: #333;

                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                "
              >
                {{
                  record.type
                    ? record.acceptUserAccount.userNickName
                    : record.userAccount.userNickName
                }}
              </div>

              <!-- ID -->
              <div style="font-size: 0.8em; font-weight: 590; color: rgba(0, 0, 0, 0.4)">
                {{ t('user_id_prefix') }}
                {{ record.type ? record.acceptUserAccount.account : record.userAccount.account }}
              </div>
            </div>
          </div>

          <!-- 收支和时间 -->
          <div
            style="
              width: auto;
              min-width: 0;
              align-self: stretch;

              display: flex;
              flex-direction: column;
              align-items: flex-end;
              gap: 4px;
            "
          >
            <div style="font-size: 0.9em; color: rgba(0, 0, 0, 0.4); font-weight: 510">
              {{ record.amount }} {{ t('coins') }}
            </div>
            <div style="font-size: 0.8em; font-weight: 510; color: rgba(0, 0, 0, 0.4)">
              {{ record.time }}
            </div>
          </div>
        </div>

        <!-- 收入列表触发加载功能 -->
        <div
          ref="incomeLoadmore"
          v-show="incomeRecords.length != 0 && selectedTab?.langKey === 'income'"
        ></div>

        <!-- 支出列表触发加载功能 -->
        <div
          ref="expenditureLoadmore"
          v-show="expenditureRecords.length != 0 && selectedTab?.langKey === 'expenditure'"
        ></div>
      </div>

      <!-- 用户列表(加载完且列表为空) -->
      <div
        v-if="!loading && records.length === 0"
        style="
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 60px 20px;
          color: #666;
          text-align: center;
        "
      >
        <div style="font-size: 48px; margin-bottom: 16px">📋</div>
        <p style="margin: 0 0 8px 0; font-size: 16px; font-weight: 500">
          {{ t('no_transaction_records') }}
        </p>
        <span style="font-size: 14px; color: #9ca3af">{{ t('no_selling_records_yet') }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { setDocumentDirection } from '@/locales/i18n'
import { formatUTCCustom } from '@/utils/utcFormat.js'
import { getUserId } from '@/utils/userStore.js'
import { handleAvatarImageError } from '@/utils/image/imageHandler.js'
import { useDebounce, useThrottle } from '@/utils/useDebounce'

import { getFreightWaterFlow } from '@/api/wallet.js'

import GeneralHeader from '@/components/GeneralHeader.vue'

const { t, locale } = useI18n()

// 监听语言变化并设置文档方向
locale.value && setDocumentDirection(locale.value)

const userId = ref(getUserId())
const loading = ref(false)

const incomeRecords = ref([]) //收入记录
const expenditureRecords = ref([]) //支出记录
const records = computed(() => {
  if (selectedTab.value.langKey === 'income') {
    return incomeRecords.value
  } else {
    return expenditureRecords.value
  }
})

// 获取底部加载div
const incomeLoadmore = ref(null)
const expenditureLoadmore = ref(null)

const searchQuery = ref('')
const hasSearched = ref(false)
const searchResults = ref([]) //搜索结果

const selectedTab = ref({ id: 0, langKey: 'income' })
const tabItems = ref([]) // 存储标签DOM引用
// 标签页数据
const tabs = ref([
  { id: 0, langKey: 'income' },
  { id: 1, langKey: 'expenditure' },
])

// 切换标签页
const switchTab = async (tab) => {
  selectedTab.value = tab

  await fetchRecords() //获取记录
  reSetObserve() // 重新绑定观察器
}

// 计算下划线样式
const underlineStyle = computed(() => {
  console.log('计算属性')

  // 访问 locale.value 使其成为依赖项
  const currentLocale = locale.value
  console.log('当前语言:', currentLocale)

  if (tabItems.value.length === 0) return {} //没有这个元素
  const activeTab = tabItems.value[selectedTab.value.id]
  console.log('选中元素的左边距', activeTab.offsetLeft)

  return {
    position: 'absolute',
    left: `${activeTab.offsetLeft + activeTab.offsetWidth / 2 - 15 / 2}px`,
    bottom: '0',
    transition: 'left 0.3s ease', // 平滑过渡
  }
})

// 获取金额显示
const getAmountDisplay = (type, quantity) => {
  const prefix = type === 0 ? '+' : '-'
  return `${prefix}${quantity}`
}

// 获取记录
const fetchRecords = async (lastId = '') => {
  loading.value = true

  try {
    if (!userId.value) {
      console.error('无法获取用户ID')
      return
    }

    // 切换标签时，既不是下拉加载，也不是空列表，则不请求接口
    if (records.value.length != 0 && lastId == '') {
      return
    }

    // 接口参数
    let data = {
      userId: userId.value, //用户id
      type: selectedTab.value.id, //记录类型
      searchId: searchQuery.value, //目标用户id
      lastId, //最后一条记录id
    }

    const response = await getFreightWaterFlow(data)

    if (response && response.status && response.body) {
      // 处理返回的数据
      let records = response.body.map((item) => ({
        ...item,

        amount: getAmountDisplay(item.type, item.quantity), //添加±号
        time: formatUTCCustom(item.createTime), //格式化时间
      }))

      if (selectedTab.value.id == 1) {
        expenditureRecords.value.push(...records)
      } else {
        incomeRecords.value.push(...records)
      }
    }
  } catch (error) {
    console.error('获取记录失败:', error)
  } finally {
    loading.value = false
    console.log('加载完毕')
  }
}

// 清除搜索
const clearSearch = async () => {
  hasSearched.value = false
  searchQuery.value = ''
  searchResults.value = []

  incomeRecords.value = [] //置空收入列表
  expenditureRecords.value = [] //置空支出列表
  await fetchRecords() //重新获取记录
  reSetObserve() // 重新绑定观察器
}

// 创建防抖版本的搜索函数
const debouncedSearch = useDebounce(
  async () => {
    console.log('searchQuery.value:', searchQuery.value)

    if (!searchQuery.value.trim()) {
      searchResults.value = []
      return
    }

    // 使用已有的 loading 状态来防止并发请求
    if (loading.value) return

    hasSearched.value = true // 设置搜索状态

    searchResults.value = []
    if (searchQuery.value.trim()) {
      incomeRecords.value = [] //置空收入列表
      expenditureRecords.value = [] //置空支出列表
      await fetchRecords() //搜索记录
      reSetObserve() // 重新绑定观察器
    }
  },
  500,
  true,
)

const throttleFetch = useThrottle((fetchFn) => {
  fetchFn()
}, 1000)

// IntersectionObserver配置
const obsever = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.intersectionRatio > 0) {
      console.log('监控到底部')
      let lastId = records.value[records.value.length - 1].id
      console.log('lastId:', lastId)
      if (entry.target === incomeLoadmore.value) {
        console.log('incomeLoadmore')
        throttleFetch(() => {
          fetchRecords(lastId) //加载income新记录
        })
      }
      if (entry.target === expenditureLoadmore.value) {
        console.log('expenditureLoadmore')
        throttleFetch(() => {
          fetchRecords(lastId) //加载expenditure新记录
        })
      }
    }
  })
})

// 重新绑定观察器
const reSetObserve = () => {
  nextTick(() => {
    if (incomeLoadmore.value) {
      obsever.unobserve(incomeLoadmore.value)
      obsever.observe(incomeLoadmore.value)
    }
    if (expenditureLoadmore.value) {
      obsever.unobserve(expenditureLoadmore.value)
      obsever.observe(expenditureLoadmore.value)
    }
  })
}

onMounted(async () => {
  await fetchRecords()
  underlineStyle.value // 触发计算属性更新

  reSetObserve() // 绑定观察器
})
</script>

<style scoped>
* {
  color: rgba(0, 0, 0, 0.8);
}

.seller-records {
  overflow-y: auto;
  max-height: 100vh;
}

.seller-records::-webkit-scrollbar {
  display: none;
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #f59e0b;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.transaction-type {
  font-size: 12px;
  color: #9ca3af;
  margin-top: 2px;
}

input::placeholder {
  font-weight: bold;
  color: rgba(0, 0, 0, 0.4);
}

@media screen and (max-width: 360px) {
  * {
    font-size: 10px;
  }

  .help-btn {
    width: 14px;
  }
}

@media screen and (min-width: 360px) {
  * {
    font-size: 12px;
  }

  .help-btn {
    width: 16px;
  }
}

@media screen and (min-width: 768px) {
  * {
    font-size: 24px;
  }

  .help-btn {
    width: 28px;
  }
}

/* RTL支持 */
[dir='rtl'] .search-icon {
  transform: scaleX(-1);
}
</style>
