<script setup>
import { ref, watch, nextTick, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import API from '@/util/http.js'
import moment from 'moment'
import { useI18n } from 'vue-i18n'
import { useAdminStore } from "@/store/index.js"
import { storeToRefs } from "pinia"

const { t } = useI18n()
const route = useRoute()
const adminStore = useAdminStore()
const { flag } = storeToRefs(adminStore)

const tableData = ref([])
const total = ref(0)
const loading = ref(false)

const selectData = ref({
  jwcode: '',
  walletId: ''
})

const getObj = ref({
  pageNum: 1,
  pageSize: 20
})

const tableRef = ref(null)
const scrollTableTop = () => {
  tableRef.value?.setScrollTop?.(0)
}

// 精网号去空格
const trimJwCode = () => {
  if (selectData.value.jwcode) {
    selectData.value.jwcode = selectData.value.jwcode.replace(/\s/g, '');
  }
}

// 获取类型文本
const getWalletRecordTypeText = (item) => {
  const type = Number(item.type)
  if (type === 0) {
    return t('clientCount.recharge')
  }
  if (type === 1) {
    return t('clientCount.consume')
  }
  if (type === 2) {
    return t('clientCount.refund')
  }
  return item.typeText || t('clientCount.other')
}

// 格式化金额
const format3 = (num) => {
  return num.toLocaleString('en-US')
}

// 统一获取数据的方法
const getWalletData = async () => {
  if (!selectData.value.walletId) return;

  if (selectData.value.jwcode) {
    const numberRegex = /^\d{1,9}$/;
    if (!numberRegex.test(selectData.value.jwcode)) {
      ElMessage.error(t('elmessage.checkJwcodeFormat'))
      return
    }
  }

  loading.value = true
  try {
    const params = {
      pageNum: getObj.value.pageNum,
      pageSize: getObj.value.pageSize,
      userWalletRecord: {
        walletId: selectData.value.walletId,
        jwcode: selectData.value.jwcode ? Number(selectData.value.jwcode) : null
      }
    }

    const result = await API({
      url: '/cashCollection/selectWalletRecords',
      method: 'post',
      data: params
    })

    if (result.code === 200) {
      tableData.value = result.data.list.map(item => ({
        ...item,
        time: moment(item.createTime).format('YYYY-MM-DD HH:mm:ss'),
        typeText: getWalletRecordTypeText(item),
        amount: Number(item.amount) || 0,
        desc: item.description || '',
        orderNo: item.orderCode,
        status: item.status === 0 ? 1 : 2,
        userName: item.userName || '-',
        jwcode: item.jwcode || '-'
      }))
      total.value = result.data.total
      await nextTick()
      scrollTableTop()
    } else {
      ElMessage.error(result.msg || t('elmessage.getDataFailed'))
    }
  } catch (error) {
    console.error('获取钱包明细失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const search = function () {
  trimJwCode()
  getObj.value.pageNum = 1
  getWalletData()
}

// 重置
const reset = function () {
  selectData.value.jwcode = ''
  getObj.value.pageNum = 1
  getWalletData()
}

// 分页改变
const handlePageSizeChange = function (val) {
  getObj.value.pageSize = val
  getWalletData()
}
const handleCurrentChange = function (val) {
  getObj.value.pageNum = val
  getWalletData()
}

// 监听全局flag变化重新请求数据
watch(flag, (newFlag, oldFlag) => {
  if (newFlag !== oldFlag) {
    getWalletData()
  }
})

// 核心：监听路由参数变化
watch(
  () => route.query.type,
  (newType) => {
    if (newType) {
      selectData.value.walletId = newType
      getObj.value.pageNum = 1
      getWalletData()
    }
  },
  { immediate: true }
)
</script>

<template>
  <div style="display: flex; flex-direction: column; height: 100%;">
    <el-card class="card1" style="margin-bottom: 1vh;">
      <div class="head-card">
        <div class="head-card-element">
          <el-text class="mx-1" size="large">{{ $t('common_list.jwcode') }}：</el-text>
          <el-input v-model="selectData.jwcode" style="width: 240px" :placeholder="$t('common_list.jwcodePlaceholder')" clearable />
        </div>
        <div class="head-card-btn">
          <el-button type="default" @click="reset">{{ $t('common.reset') }}</el-button>
          <el-button type="primary" @click="search">{{ $t('common.search') }}</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="card2">
      <div style="height: 69vh; overflow-y: auto">
        <el-table ref="tableRef" :data="tableData" v-loading="loading" style="width: 100%; height: 69vh" :row-style="{ height: '50px' }">
          <el-table-column type="index" :label="$t('common_list.id')" width="80px" fixed="left">
            <template #default="scope">
              <span>{{ scope.$index + 1 + (getObj.pageNum - 1) * getObj.pageSize }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userName" :label="$t('common_list.name')" width="140" />
          <el-table-column prop="jwcode" :label="$t('common_list.jwcode')" width="140" />
          <el-table-column prop="time" :label="$t('clientCount.time')" align="center" width="180">
             <template #default="scope">{{ scope.row.time }}</template>
          </el-table-column>
          <el-table-column prop="typeText" :label="$t('clientCount.transactionType')" align="center" width="120" />
          <el-table-column prop="amount" :label="$t('common_list.money')" align="center" width="120">
            <template #default="scope">
              <span :style="{ color: scope.row.amount >= 0 ? '#67C23A' : '#F56C6C', fontWeight: 'bold' }">
                {{ scope.row.amount > 0 ? '+' + format3(scope.row.amount) : format3(scope.row.amount) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="desc" :label="$t('clientCount.transactionDesc')" align="center" min-width="150" />
          <el-table-column prop="orderNo" :label="$t('clientCount.transactionOrderNo')" align="center" width="220" />
          <el-table-column prop="status" :label="$t('clientCount.transactionStatus')" align="center" width="150" fixed="right">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : scope.row.status === 2 ? 'danger' : 'info'" :effect="scope.row.status === 1 ? 'light' : 'plain'">
                {{ scope.row.status === 1 ? t('common_list.normal') : scope.row.status === 2 ? t('common_list.refunded') : t('clientCount.exceptionData') }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination" style="margin-top: 20px">
        <el-pagination background :current-page="getObj.pageNum" :page-size="getObj.pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handlePageSizeChange"
          @current-change="handleCurrentChange"></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.card1 {
  background: #F3FAFE;
}

.card2 {
  background: #E7F4FD;
  flex: 1;
  display: flex;
  flex-direction: column;

   :deep(.el-card__body) {
    padding: 20px;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
}

:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__cell),
:deep(.el-table__body td) {
  background-color: #F3FAFE !important;
}

:deep(.el-table__header th) {
  background-color: #F3FAFE !important;
}

:deep(.el-table__row:hover > .el-table__cell) {
  background-color: #E5EBFE !important;
}

.pagination {
  display: flex;
}

.head-card {
  display: flex;
}

.head-card-element {
  margin-right: 20px;
}

.head-card-btn {
  margin-left: auto;
}
</style>