<template>
  <el-card class="card1" style="margin-bottom: 0.5vh;">
    <el-col style="margin-bottom: 1vh">
      <div class="select">
        <div class="selectRow">
          <el-text class="text" size="large">{{ $t('common.jwcode') }}：</el-text>
          <el-input class="selectContent" v-model="rechargeAudit.jwcode" :placeholder="$t('common.jwcodePlaceholder')" clearable />
        </div>
        <div class="selectRow">
          <el-text class="text" size="large">{{ $t('common.activityName') }}：</el-text>
          <el-select class="selectContent" v-model="rechargeAudit.activity" :placeholder="$t('common.activityNamePlaceholder')" clearable>
            <el-option v-for="item in activity" :key="item" :label="item" :value="item" />
          </el-select>
        </div>
        <div class="selectRow">
          <el-text class="text" size="large">{{ $t('common.payModel') }}：</el-text>
          <el-select class="selectContent" v-model="rechargeAudit.payModel" :placeholder="$t('common.payModelPlaceholder')" clearable>
            <el-option v-for="item in payModel" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="selectRow">
          <el-text class="text" size="large">{{ $t('common.market') }}：</el-text>
          <el-cascader class="selectContent" v-model="selectedMarketPath" :options="market" :placeholder="$t('common.marketPlaceholder')"
            clearable @change="handleMarketChange" />
        </div>
      </div>
    </el-col>
    <el-col>
      <div class="select">
        <div class="selectRow" style="width: 36vw;">
          <el-text class="text" size="large">
            {{ activeName === 'wait' ? $t('common.submitTime') : $t('common.auditTime') }}
          </el-text>
          <el-date-picker class="selectContent" v-model="getTime" type="datetimerange" :range-separator="$t('common.to')"
            :start-placeholder="$t('common.startTime')" :end-placeholder="$t('common.endTime')" style="margin-right:1vw;width:25vw"
            @change="handleDatePickerChange" :default-time="defaultTime" :disabled-date="disabledDate" />
          <div v-if="false">
            <el-button @click="getToday()" :type="activeTimeRange === 'today' ? 'primary' : ''">今</el-button>
            <el-button @click="getYesterday()" :type="activeTimeRange === 'yesterday' ? 'primary' : ''">昨</el-button>
            <el-button @click="get7Days()" :type="activeTimeRange === '7days' ? 'primary' : ''">近7天</el-button>
          </div>
        </div>
        <div class="selectRow" style="justify-content: flex-start;">
          
          <el-button @click="handleSearch" type="primary">{{ $t('common.search') }}</el-button>
          <el-button @click="resetSearch" type="success">{{ $t('common.reset') }}</el-button>
        </div>
      </div>
    </el-col>
  </el-card>
  <el-card class="card2">
    <div class="custom-button-group">
    <el-button 
      v-if="hasrechargeWait&&hasrechargeWaitShow"
      :type="activeName === 'wait' ? 'primary' : 'default'"
      @click="handleButtonClick('wait')"
      class="custom-tab-button"
    >
      {{ $t('audit.waitAudit') }}
    </el-button>
    <el-button 
      v-if="hasrechargeThrough"
      :type="activeName === 'pass' ? 'primary' : 'default'"
      @click="handleButtonClick('pass')"
      class="custom-tab-button"
    >
      {{ $t('audit.passed') }}
    </el-button>
    <el-button 
      v-if="hasrechargeReject"
      :type="activeName === 'reject' ? 'primary' : 'default'"
      @click="handleButtonClick('reject')"
      class="custom-tab-button"
    >
      {{ $t('audit.rejected') }}
    </el-button>
  </div>
      <div class="goldStatistics">

        <!--        总条数：{{ format3(stats.totalNum) }}条&nbsp;&nbsp;&nbsp;&nbsp;-->
        {{ $t('audit.rechargeSGD') }}：{{ format3(stats.permanentGolds) }} {{ $t('common.SGD') }}&nbsp;&nbsp;&nbsp;&nbsp;
        {{ $t('audit.totalGold') }}：{{ format3((stats.permanentGolds + stats.freeGolds + stats.taskGolds).toFixed(2))
        }}{{ $t('common.goldCoin') }}&nbsp;&nbsp;&nbsp;&nbsp;
        {{ $t('audit.permanentGold') }}：{{ format3(stats.permanentGolds.toFixed(2)) }}{{ $t('common.goldCoin') }}&nbsp;&nbsp;&nbsp;&nbsp;
        {{ $t('audit.freeGold') }}：{{ format3(stats.freeGolds.toFixed(2)) }}{{ $t('common.goldCoin') }}&nbsp;&nbsp;&nbsp;&nbsp;
      </div>

    <el-table ref="tableRef" :data="tableData" style="width: 82vw;height:61vh" @sort-change="handleSortChange"
      :row-style="{ height: '50px' }">
      <el-table-column type="index" :label="$t('audit.id')" width="100px" fixed="left">
        <template #default="scope">
          <span>{{ scope.$index + 1 + (getObj.pageNum - 1) * getObj.pageSize }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="left" prop="name" :label="$t('audit.name')" width="150px" show-overflow-tooltip />
      <el-table-column fixed="left" prop="jwcode" :label="$t('audit.jwcode')" width="110px" />
      <el-table-column prop="market" :label="$t('audit.market')" width="120px" />
      <el-table-column prop="activity" :label="$t('audit.activityName')" width="100px" show-overflow-tooltip />
      <el-table-column prop="rateName" :label="$t('audit.currencyName')" width="110px" />
      <el-table-column prop="money" :label="$t('audit.rechargeAmount')" sortable="custom" width="110px">
        <template #default="scope">{{ scope.row.money / 100 }}</template>
      </el-table-column>
      <el-table-column prop="permanentGold" :label="$t('audit.permanentGold')" width="130px" sortable="custom">
        <template #default="scope">{{ scope.row.permanentGold / 100 }}</template>
      </el-table-column>
      <el-table-column prop="freeGold" :label="$t('audit.freeGold')" sortable="custom" width="130px">
        <template #default="scope">{{ (scope.row.freeGold) / 100 }}</template>
      </el-table-column>
      <el-table-column prop="remark" :label="$t('audit.note')" width="180px" show-overflow-tooltip />
      <el-table-column prop="payModel" :label="$t('audit.payModel')" width="130px" />
      <el-table-column prop="voucher" :label="$t('audit.paymentVoucher')" width="110px">
        <template #default="scope">
          <div v-if="scope.row.voucher"
            style="display: flex; justify-content: center; align-items: center; cursor: pointer;"
            @click="previewImage(scope.row.voucher)">
            <img :src="scope.row.voucher" :alt="$t('audit.paymentVoucher')" style="width: auto; height: 40px;">
          </div>
          <div v-else style="display: flex; justify-content: center; align-items: center; height: 40px;">--</div>
        </template>
      </el-table-column>
      <el-table-column prop="adminName" :label="$t('audit.submitter')" width="100px" />
      <el-table-column prop="rejectReason" v-if="activeName === 'reject'" :label="$t('audit.rejectReason')" width="200px"
        show-overflow-tooltip />
      <el-table-column v-if="activeName !== 'wait'" prop="auditName" :label="$t('audit.auditor')" width="100px" />
      <el-table-column prop="payTime" sortable="custom" :label="$t('audit.paymentTime')" width="200px">
        <template #default="scope">
          {{ moment(scope.row.payTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" sortable="custom" :label="$t('audit.submitTime')" width="200px">
        <template #default="scope">
          <!--          {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}-->
          {{
            activeName === 'wait'
              ? moment(scope.row.auditTime).format('YYYY-MM-DD HH:mm:ss')
              : moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss')
          }}
        </template>
      </el-table-column>
      <el-table-column v-if="activeName !== 'wait'" prop="auditTime" sortable="custom" :label="$t('audit.auditTime')" width="200px">
        <template #default="scope">
          {{ moment(scope.row.auditTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column v-if="activeName === 'wait'&&(hasrechargeWaitThough||hasrechargeWaitReject)&&hasrechargeWaitShow" fixed="right" prop="operation" :label="$t('audit.operation')" width="150px">
        <template #default="scope">
          <div class="operation">
            <el-link :underline="false" class="pass-btn" v-if="hasrechargeWaitThough"
                     :disabled="clicked || cancelClicked" type="primary"
                     @click="showApproveDialog(scope.row)">
              {{ $t('common.pass') }}
            </el-link>
            <el-link :underline="false" class="reject-btn" v-if="hasrechargeWaitReject"
                     :disabled="clicked || cancelClicked" type="primary"
                     @click="showRejectDialog(scope.row)">
              {{ $t('common.reject') }}
            </el-link>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination background :current-page="getObj.pageNum" :page-size="getObj.pageSize" :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handlePagination('size', $event)"
        @current-change="handlePagination('page', $event)"></el-pagination>
    </div>
  </el-card>

  <el-dialog v-model="rejectReasonDialogVisible" :title="$t('audit.rejectReason')" width="400px" @close="handleRejectReasonCancel">
    <el-form>
      <el-form-item :label="$t('audit.rejectReason')" required>
        <el-input v-model="rejectReason" type="textarea" :rows="4" :placeholder="$t('audit.rejectReason')" maxlength="200"
          show-word-limit />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleRejectReasonCancel">{{ $t('common.cancel') }}</el-button>
        <el-button :disabled="cancelClicked" type="primary" @click="handleReject">{{ $t('common.confirm') }}</el-button>
      </span>
    </template>
  </el-dialog>
  <ConfirmDialog
    v-model="rejectDialogVisible"
    :message="$t('audit.rejectRecord')"
    @confirm="showRejectReasonInput"
    @cancel="handleRejectCancel"
    @close="handleRejectClose"
    />

  <!-- 新增：使用ConfirmDialog组件 -->
  <ConfirmDialog 
    v-model="approveDialogVisible"
    :message="$t('audit.passRecord')"
    @confirm="throttledHandleApproveConfirm"
    @cancel="handleApproveCancel"
    @close="handleApproveClose"
  />

</template>


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

import ConfirmDialog from '@/components/dialogs/ConfirmDialog.vue'

const adminStore = useAdminStore();
const { adminData, menuTree, flag } = storeToRefs(adminStore);
import { permissionMapping, hasMenuPermission } from "@/utils/menuTreePermission.js"
import dayjs from "dayjs";

import { useI18n } from 'vue-i18n';
import {reverseMarketMapping} from "@/utils/marketMap.js";
const { t } = useI18n();

// 监听全局flag状态变化
 watch(flag, (newFlag, oldFlag) => {
  // 当flag状态改变时，重新发送请求
  if (newFlag !== oldFlag) {
    // console.log('员工数据flag状态改变，重新加载数据', newFlag)
    getRecharge()
    console.log('flag10',flag.value)
    getStats()
    console.log('flag2',flag)
  }
})

//操作权限
const hasrechargeThrough = ref(false)  // 充值审核已通过
const hasrechargeReject = ref(false)  // 充值审核已驳回
const hasrechargeWait = ref(false)  // 充值审核待审核
const hasrechargeWaitShow = ref(false) // 充值审核待审核查看
const hasrechargeWaitThough = ref(false) // 充值审核通过
const hasrechargeWaitReject = ref(false) // 充值审核驳回

// 初始化权限状态
const initPermissions = async() => {
  if (!menuTree.value || !menuTree.value.length) return;
  hasrechargeThrough.value = hasMenuPermission(menuTree.value, permissionMapping.gold_coin_recharge_approved);
  hasrechargeReject.value = hasMenuPermission(menuTree.value, permissionMapping.gold_coin_recharge_rejected);
  hasrechargeWait.value = hasMenuPermission(menuTree.value, permissionMapping.gold_coin_recharge_pending);
  hasrechargeWaitShow.value = hasMenuPermission(menuTree.value, permissionMapping.view_gold_recharge_pending);
  hasrechargeWaitThough.value = hasMenuPermission(menuTree.value, permissionMapping.pass_gold_refund_audit);
  hasrechargeWaitReject.value = hasMenuPermission(menuTree.value, permissionMapping.reject_gold_refund_audit);
  console.log(hasrechargeWaitThough.value)
  console.log(hasrechargeWaitReject.value)

};
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
]
//无法选择的时间
const disabledDate = (time) => {
  const limitDate = new Date(2025, 0, 1);
  return time.getTime() < limitDate.getTime();
}
const tableData = ref([])
const tableRef = ref(null)
// 当前激活的时间按钮
const activeTimeRange = ref('')
const total = ref(50)
// 搜索对象时间
const getTime = ref([])
const activity = ref([])
const market = ref("")
const rejectDialogVisible = ref(false)
const rejectReasonDialogVisible = ref(false) // 驳回理由输入框显示状态
const rejectReason = ref('')

const approveDialogVisible = ref(false)
// 当前行信息
const currentRecord = ref(null)
// 标签页默认是待审批
const activeName = ref('wait')
const sortField = ref('')
const sortOrder = ref('')
// 存储地区选择变化
const selectedMarketPath = ref("")
// 搜索表单
const rechargeAudit = ref({
  jwcode: "", // 精网号
  activity: "", // 活动名称
  payModel: "", // 支付方式
  startTime: "", // 充值时间开始
  endTime: "", // 充值时间结束
  market: "", // 地区
  auditStatus: '0',
})
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 50
})



// 支付方式选项
const payModel = [
  {
    value: '银行转账',
    label: t('audit.payMethods.bankTransfer')
  },
  {
    value: '现金',
    label: t('audit.payMethods.cash')
  },
  {
    value: '支票',
    label: t('audit.payMethods.check')
  },
  {
    value: '刷卡',
    label: t('audit.payMethods.card')
  },
  {
    value: 'Grabpay',
    label: t('audit.payMethods.grabpay')
  },
  {
    value: 'Nets',
    label: t('audit.payMethods.nets')
  },
  {
    value: 'PayPal',
    label: t('audit.payMethods.paypal')
  },
  {
    value: 'Stripe',
    label: t('audit.payMethods.stripe')  
  },
  {
    value: 'Ipay88',
    label: t('audit.payMethods.ipay88')
  },
  {
    value: 'PaymentAsia',
    label: t('audit.payMethods.paymentAsia')
  },
  {
    value: '其他',
    label: t('audit.payMethods.other')
  }
]
// 统计合计数
const stats = ref({
  totalNum: 0,
  totalCoins: 0,
  permanentGolds: 0,
  freeGolds: 0,
  taskGolds: 0
})
// 表单验证
const rules = reactive({
  rejectReason: [{ required: true, message: t('audit.rejectReasonPlaceholder'), trigger: 'blur' }]
})
// 搜索方法
const getRecharge = async function (val) {

  if (!hasrechargeWaitShow) {
    ElMessage.error(t('elmessage.noPermission'))
    return
  }
  try {
    if (getTime.value && getTime.value.length === 2) {
      rechargeAudit.value.startTime = formatTime(getTime.value[0])
      rechargeAudit.value.endTime = formatTime(getTime.value[1])
    } else {
      rechargeAudit.value.startTime = ''
      rechargeAudit.value.endTime = ''
    }
    // if (rechargeAudit.value.market === '总部' || rechargeAudit.value.market === '研发部') {
    //   rechargeAudit.value.market = '';
    // }
    // 校验精网号（数字格式）
    if (rechargeAudit.value.jwcode) {
      // 纯数字
      const numberRegex = /^\d{1,9}$/;
      // 检查是否不是数字
      if (!numberRegex.test(rechargeAudit.value.jwcode)) {
        ElMessage.error(t('elmessage.checkJwcodeFormat'))
        return
      }
    }
    const result = await request({
      url: '/audit/selectRecharge',
      data: {
        pageNum: getObj.value.pageNum,
        pageSize: getObj.value.pageSize,
        rechargeAudit: {
          ...rechargeAudit.value,
          sortField: sortField.value,
          sortOrder: sortOrder.value,
          flag: flag.value
        }
      }
    })
    tableData.value = result.list
    total.value = result.total
  } catch (error) {
    console.log('请求失败', error)
  }

}

const getStats = async () => {
   if (!hasrechargeWaitShow) {
    return
  }
  try {
    const params = {
      pageNum: getObj.value.pageNum,
      pageSize: getObj.value.pageSize,
      rechargeAudit: {
        ...rechargeAudit.value,
        flag: flag.value
      }
    }
    // 校验精网号（数字格式）
    if (rechargeAudit.value.jwcode) {
      // 纯数字
      const numberRegex = /^\d{1,9}$/;
      // 检查是否不是数字
      if (!numberRegex.test(rechargeAudit.value.jwcode)) {
        // ElMessage.error('精网号必须为数字格式')
        // 上面提示过了
        return
      }
    }
    const res = await API({
      url: '/audit/sumRechargeGold',
      data: params
    })

    stats.value.totalNum = res.totalNum
    stats.value.permanentGolds = res.permanentGolds / 100
    stats.value.freeGolds = res.freeGolds / 100
    stats.value.taskGolds = res.taskGolds / 100
    console.log('see see stats和搜索对象', stats.value, params)
  } catch (error) {
    console.log('请求失败', error)
  }
}
// 搜索
const handleSearch = function () {
  trimJwCode();
  getObj.value.pageNum = 1
  getRecharge()
  getStats()
}

// 重置
const resetSearch = function () {
  rechargeAudit.value = {
    jwcode: "",
    activity: "",
    payModel: "",
    startTime: "",
    endTime: "",
    market: "",
    auditStatus: rechargeAudit.value.auditStatus
  }
  // 重置页码
  getObj.value.pageNum = 1
  selectedMarketPath.value = []
  getTime.value = []
  activeTimeRange.value = '' // 清除激活状态
  getRecharge()
  getStats()
}

// 今天
const getToday = function () {
  const today = dayjs()
  const startTime = today.startOf('day').format('YYYY-MM-DD HH:mm:ss')
  const endTime = today.endOf('day').format('YYYY-MM-DD HH:mm:ss')
  getTime.value = [startTime, endTime]
  console.log('getTime', getTime.value)
  activeTimeRange.value = 'today' // 标记当前激活状态
  getRecharge()
  getStats()
}

// 昨天
const getYesterday = function () {
  const today = dayjs()
  const startTime = today.subtract(1, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss')
  const endTime = today.subtract(1, 'day').endOf('day').format('YYYY-MM-DD HH:mm:ss')
  getTime.value = [startTime, endTime]
  console.log('getTime', getTime.value)
  activeTimeRange.value = 'yesterday' // 标记当前激活状态
  getRecharge()
  getStats()
}

// 近7天
const get7Days = function () {
  const today = dayjs()
  const startTime = today.subtract(6, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss')
  const endTime = today.endOf('day').format('YYYY-MM-DD HH:mm:ss')
  getTime.value = [startTime, endTime]
  console.log('getTime', getTime.value)
  activeTimeRange.value = '7days' // 标记当前激活状态
  getRecharge()
  getStats()
}

// 待审核充值明细
const adminWait = async function () {
  rechargeAudit.value.auditStatus = "0"
  getObj.value.pageNum = 1
  await getRecharge()
  await getStats()
  console.log('adminWait，这是点击待审核调用')
}

// 已通过充值明细
const adminPass = async function () {
  rechargeAudit.value.auditStatus = "1"
  getObj.value.pageNum = 1
  await getRecharge()
  await getStats()
  console.log('adminWait，这是点击已通过调用')
}

// 已驳回充值明细
const adminReject = async function () {
  rechargeAudit.value.auditStatus = "2"
  getObj.value.pageNum = 1
  await getRecharge()
  await getStats()
  console.log('adminWait，这是点击已驳回调用')
}

const handleButtonClick = function (name) {
  activeName.value = name
  if (name === 'wait') {
    if(!hasrechargeWait){
      ElMessage.error(t('elmessage.noPermission'))
      return
    }
    if(hasrechargeWaitShow){
      adminWait()
    }
  } else if (name === 'pass') {
    if(!hasrechargeThrough){
      ElMessage.error(t('elmessage.noPermission'))
      return
    }
    adminPass()
  } else if (name === 'reject') {
    if(!hasrechargeReject){
      ElMessage.error(t('elmessage.noPermission'))
      return
    }
    adminReject()
  }
}


// const handleClick = function (tab, event) {
//   activeName.value = tab.props.name
//   if (tab.props.name === 'wait') {
//     if(!hasrechargeWait){
//       ElMessage.error('暂无权限')
//       return
//     }
//     if(hasrechargeWaitShow){
//       adminWait()
//     }
//   } else if (tab.props.name === 'pass') {
//     if(!hasrechargeThrough){
//       ElMessage.error('暂无权限')
//       return
//     }
//     adminPass()
//   } else if (tab.props.name === 'reject') {
//     if(!hasrechargeReject){
//       ElMessage.error('暂无权限')
//       return
//     }
//     adminReject()
//   }
// }
const getActivity = async function () {
  try {
    const result = await request({
      url: '/general/activity',
      data: {}
    })
    activity.value = result.data
    console.log('activity', activity.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}
const handlePagination = (type, val) => {
  if (type === 'size') {
    getObj.value.pageSize = val
  } else {
    getObj.value.pageNum = val
  }
  tableRef.value.setScrollTop(0)
  getRecharge()
  getStats()
}
const clicked = ref(false);

// 显示通过确认对话框
const showApproveDialog = (row) => {
    if(!hasrechargeWaitThough){
      ElMessage.error(t('elmessage.noPermission'))
      return
    }
  currentRecord.value = row
  approveDialogVisible.value = true
}

// 使用handleApproveConfirm函数代替handleApprove
const handleApproveConfirm = async () => {
  clicked.value = true
  try {
    const params = {
      orderCode: currentRecord.value.orderCode,
      auditId: adminData.value.id,
      action: 1,
      rejectReason: ''
    }
    await request({ url: '/audit/audit', data: params })
    ElMessage.success(t('elmessage.approveSuccess'))
    approveDialogVisible.value = false
    await getRecharge()
    clicked.value = false
    await getStats()
  } catch (error) {
    console.error(t('elmessage.approveFailed'), error)
    ElMessage.error(t('elmessage.operationFailed'))
    clicked.value = false
  }
}

import _ from 'lodash';

// handleApproveConfirm
const throttledHandleApproveConfirm = _.throttle(handleApproveConfirm, 5000, {
  trailing: false
})
// 处理通过取消操作
const handleApproveCancel = () => {
  approveDialogVisible.value = false
}
// 处理通过关闭操作
const handleApproveClose = () => {
  approveDialogVisible.value = false
}
// 处理通过操作
// const handleApprove = async (row) => {
//     if(!hasrechargeWaitThough){
//       ElMessage.error('暂无权限')
//       return
//     }
//   clicked.value = true
//     try {
//       const params = {
//         orderCode: row.orderCode,
//         auditId: adminData.value.id,
//         action: 1,
//         rejectReason: ''
//       }
//       await request({ url: '/audit/audit', data: params })
//       ElMessage.success('审核通过成功')
//       await getRecharge()
//       clicked.value = false
//       await getStats()
//     } catch (error) {
//       console.error('审核通过失败', error)
//       ElMessage.error('操作失败')
//     }


// }
const showRejectDialog = (row) => {
    if(!hasrechargeWaitReject){
      ElMessage.error(t('elmessage.noPermission'))
      return
    }
  currentRecord.value = row
  rejectReason.value = ''
  rejectDialogVisible.value = true
}
//控制驳回确认按钮禁用状态
const cancelClicked = ref(false)
// 处理驳回操作
const handleReject = async () => {
  // 在showRejectDialog已经添加过了权限检查，此处应该是可以不用添加的
   if(!hasrechargeWaitReject){
      ElMessage.error(t('elmessage.noPermission'))
      return
    }
  cancelClicked.value = true

    if (!rejectReason.value.trim()) {
      ElMessage.warning(t('elmessage.rejectReasonPlaceholder'))
      cancelClicked.value = false // 重置按钮状态
      return
    }
    try {
      const params = {
        orderCode: currentRecord.value.orderCode,
        auditId: adminData.value.id,
        action: 2,
        rejectReason: rejectReason.value
      }

      await request({ url: '/audit/audit', data: params })
      ElMessage.success(t('elmessage.rejectSuccess'))
      rejectReasonDialogVisible.value = false
      await getRecharge()
      cancelClicked.value = false
      await getStats()
    } catch (error) {
      console.error(t('elmessage.rejectFailed'), error)
      ElMessage.error(t('elmessage.operationFailed'))
    }
}
// 确认驳回后显示理由输入框
const showRejectReasonInput = () => {
  rejectDialogVisible.value = false // 关闭确认对话框
  rejectReasonDialogVisible.value = true // 打开驳回理由输入框
}
// 处理驳回取消操作
const handleRejectCancel = () => {
  rejectDialogVisible.value = false
}
// 处理驳回关闭操作
const handleRejectClose = () => {
  rejectDialogVisible.value = false
}

// 处理驳回理由对话框关闭/取消操作
const handleRejectReasonCancel = () => {
  rejectReasonDialogVisible.value = false
  cancelClicked.value = false // 重置禁用状态
  rejectReason.value = '' // 清空驳回理由
}
// 处理排序事件
const handleSortChange = (column) => {
  console.log('排序字段：', column.prop)
  console.log('排序方式：', column.order)

  if (column.prop === 'money') {
    sortField.value = 'permanent_gold'
  } else if (column.prop === 'permanentGold') {
    sortField.value = 'permanent_gold'
  } else if (column.prop === 'freeGold') {
    sortField.value = 'freeGold'
  } else if (column.prop === 'createTime') {
    sortField.value = 'create_time'
  } else if (column.prop === 'payTime') {
    sortField.value = 'pay_time'
  } else if (column.prop === 'auditTime') {
    sortField.value = 'audit_time'
  }
  sortOrder.value = column.order === 'ascending' ? 'asc' : 'desc'
  getRecharge()
  getStats()
}
// 预览图片函数
const previewImage = (imageUrl) => {
  // 使用 element-plus 的 el-image 组件实现图片预览功能
  const imageElement = document.createElement('img');
  imageElement.src = imageUrl;
  imageElement.style.maxWidth = '80vw';
  imageElement.style.maxHeight = '80vh';

  const viewer = document.createElement('div');
  viewer.style.position = 'fixed';
  viewer.style.top = '0';
  viewer.style.left = '0';
  viewer.style.width = '100vw';
  viewer.style.height = '100vh';
  viewer.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
  viewer.style.display = 'flex';
  viewer.style.justifyContent = 'center';
  viewer.style.alignItems = 'center';
  viewer.style.zIndex = '9999';
  viewer.style.overflow = 'auto';

  viewer.appendChild(imageElement);
  document.body.appendChild(viewer);

  viewer.addEventListener('click', () => {
    document.body.removeChild(viewer);
  });
};
const handleMarketChange = (value) => {
  if (value && value.length > 0) {
    const lastValue = rechargeAudit.value.market = value[value.length - 1]
    rechargeAudit.value.market = reverseMarketMapping[lastValue]

  } else {
    rechargeAudit.value.market = ''
  }
}

const props = { multiple: true }
// 获取地区，修改为级联下拉框
const getMarket = async function () {
  try {
    const result = await API({
      url: '/market/selectMarket',
    });
    console.log('请求成功', result)
    // 递归转换树形结构为级联选择器需要的格式（跳过第一级节点）
    const transformTree = (nodes) => {
      // 直接处理第一级节点的子节点
      const allChildren = nodes.flatMap(node => node.children || []);
      return allChildren.map(child => {
        const grandchildren = child.children && child.children.length
          ? transformTree([child]) // 递归处理子节点
          : null;
        return {
          value: child.name,
          label: child.name,
          children: grandchildren
        };
      });
    };
    market.value = transformTree(result.data)
    console.log('转换后的地区树==============', market.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}
// 每三位添加逗号
const format3 = (num) => {
  return num.toLocaleString('en-US')
}
// 日期选择器变化时清除按钮激活状态
const handleDatePickerChange = () => {
  activeTimeRange.value = ''
}
// 精网号去空格
const trimJwCode = () => {
  if (rechargeAudit.value.jwcode) {
    rechargeAudit.value.jwcode = rechargeAudit.value.jwcode.replace(/\s/g, '');
  }
}
const cancelClick = () => {

}

const formatTime = (val) => val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ''
// 挂载
onMounted(async function () {
  await initPermissions()
  if(hasrechargeWaitShow.value){
    rechargeAudit.value.auditStatus = '0'
  }else if(hasrechargeThrough.value){
    rechargeAudit.value.auditStatus = '1'
  }else if(hasrechargeReject){
    rechargeAudit.value.auditStatus = '2'
  }
  await getActivity()
  await getMarket()
  await getRecharge()
  console.log("看看通信来的用户身份", adminData.value)
  await getStats()
})
</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  margin-top: 1vh;
}

.operation {
  display: flex;
}

// 搜索的卡片样式
.card1 {
  background: #F3FAFE;
}

// 表单的卡片样式
.card2 {
  background: #E7F4FD;
}

// 新币总数等等
.goldStatistics {
  margin-left: 1vw;
  margin-bottom: 1vh;
  color: #000000;
  font-family: "PingFang SC";
  font-size: 16px;
  font-style: normal;
  font-weight: 700;
  line-height: 20px;
}

// 表头背景等
: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;
}
/* 按钮组 */
/* 自定义按钮组布局 */
.custom-button-group {
  display: flex;
  margin-bottom: 16px;
}
:deep(.el-button.custom-tab-button) {
  border-radius: 4px;
  transition: all 0.3s ease;
}
/* 自定义激活状态样式 - 使用正确的Element Plus类选择器 */
// 使用了 .el-button--primary 类选择器，这是 Element Plus 按钮组件在设置 type="primary" 时实际添加的类名
:deep(.el-button.custom-tab-button.el-button--primary) {
  background-color: #2741DE !important;
  border-color: #2741DE !important;
  color: #F3FAFE !important;
}

/* 鼠标悬停效果 */
:deep(.el-button.custom-tab-button:hover:not(.is-disabled)) {
  opacity: 0.8;
}

.select {
  display: flex;

  .selectRow {
    width: 17vw;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 0.5vw;

    .text {
      width: 5vw;
      font-size: 15px;
    }

    .selectContent {
      flex: 1;
    }
  }
}
</style>