<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import ElementPlus from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { AiFillRead } from 'vue-icons-plus/ai'
import axios from 'axios'
import moment from 'moment'
import API from '@/util/http'
//这是获取用户信息的接口
const adminData = ref({})
const getAdminData = async function () {
  try {
    const result = await API({ url: '/admin/userinfo', data: {} })
    adminData.value = result
    rechargeUser.value.adminId = adminData.value.id
    console.log('请求成功', result)
    console.log('用户信息', adminData.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}
// 变量
// 充值明细表格
const tableData = ref([])
// 搜索===========================================
// 搜索recharge
const rechargeUser = ref({
  adminId: adminData.value.id
})
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 50
})
//分页总条目
const total = ref(100)
// 搜索对象时间
const getTime = ref([])
// 搜索活动列表
const activity = ref([])
// 所有信息
const allData = ref([])
// 搜索地区列表
const market = ref([])
//时间格式化
const formatTime = (val) => val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ''
// 初始化 money 和 permanentGold 和 freeGold
const money = ref(0)
const permanentGold = ref(0)
const freeGold = ref(0)

// 定义响应式变量存储金币合计数
const permanentGolds = ref(0)
const freeGolds = ref(0)


// 支付方式选项
const payModel = [
  {
    value: '微信',
    label: '微信'
  },
  {
    value: '支付宝',
    label: '支付宝'
  },
  {
    value: '银联',
    label: '银联'
  },
  {
    value: '信用卡',
    label: '信用卡'
  },
  {
    value: '借记卡',
    label: '借记卡'
  },
  {
    value: '现金充值',
    label: '现金充值'
  }
]
// 删除==========================================================
// 删除对象
const delObj = ref({})

// 获取活动名称
const getActivity = async function () {
  try {
    // 发送POST请求
    const result = await API({ url: '/general/activity', data: {} })

    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)

    // 检查返回的数据是否为数组
    if (Array.isArray(result.data)) {
      // 将字符串数组转换为 { value, label } 格式
      activity.value = result.data.map(item => ({ value: item, label: item }));
    } else {
      console.error('活动数据格式错误', result)
      ElMessage.error('活动数据格式错误，请联系管理员')
    }

    console.log('activity', activity.value)
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}
// 获取地区
// 获取地区
const getArea = async function () {
  try {
    // 发送POST请求
    const result = await API({ url: '/general/market', data: {} })
    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)
    // 存储地区信息
    market.value = result.data
    console.log('地区', market.value)
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}

//定义充值类型的加载状态
const isLoadingPlatform = ref(false)
// 充值类型
const platform = ref([])
//获取充值类型的函数
const getPlatform = async () => {
  isLoadingPlatform.value = true;
  try {
    const result = await API({
      url: '/general/platform',
      method: 'post',
      data: {}// 这里添加参数
    })
    // 假设后端返回的是字符串数组，转换为 { value, label } 格式
    if (Array.isArray(result.data)) {
      platform.value = result.data.map(item => ({ value: item, label: item }));
    } else {
      console.error('充值类型格式错误', result)
      ElMessage.error('充值类型格式错误，请联系管理员')
    }
  } catch (error) {
    console.error('获取充值类型失败:', error);
    ElMessage.error('获取充值类型失败，请稍后重试');
  } finally {
    isLoadingPlatform.value = false
  }
}

// 搜索===========================================================================
// 搜索方法
const get = async function (val) {
  try {
    // 搜索参数页码赋值
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }
    // 搜索参数时间赋值
    if (getTime.value != null) {
      if (getTime.value.startTime != '' && getTime.value.endTime != '') {
        rechargeUser.value.startTime = formatTime(getTime.value[0])
        rechargeUser.value.endTime = formatTime(getTime.value[1])
      }
    } else {
      rechargeUser.value.startTime = ''
      rechargeUser.value.endTime = ''
    }
    // 搜索参数赋值
    rechargeUser.value.sortField = sortField.value
    rechargeUser.value.sortOrder = sortOrder.value
    console.log('搜索参数', getObj.value)
    // 发送POST请求
    const result = await API({
      url: '/recharge/selectBy',
      data: {
        ...getObj.value,
        rechargeUser: { ...rechargeUser.value }
      }
    })
    // 复制一份 rechargeUser.value 并移除排序字段和排序方式
    const detailWithoutSort = ref({
      market: rechargeUser.value.market,
      adminId: rechargeUser.value.adminId,
      startTime: rechargeUser.value.startTime,
      endTime: rechargeUser.value.endTime,
      jwcode: rechargeUser.value.jwcode,
      goodsName: rechargeUser.value.goodsName,
      payPlatform: rechargeUser.value.payPlatform
    })
    const resultTotalGold = await API({
      url: '/recharge/statsGold',
      data: {
        ...detailWithoutSort.value
      }
    })

    if (resultTotalGold.code === 200 && resultTotalGold.data) {
      const data = resultTotalGold.data
      console.log('获取到的金币数据:', data)

      permanentGolds.value = (Number(data.permanentGolds) || 0)
      freeGolds.value = (Number(data.freeGolds) || 0)

    }

    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)
    // 存储表格数据
    tableData.value = result.data.list
    // 处理表格中的充值金额、永久金币和免费金币数据，除以 100
    tableData.value = tableData.value.map(item => ({
      ...item,
      // 处理永久金币
      permanentGold: (Number(item.permanentGold) || 0) / 100,
      // 处理免费金币
      freeGold: (Number(item.freeGold) || 0) / 100,
      // 处理充值金额
      money: (Number(item.money) || 0) / 100
    }))
    console.log('tableData', tableData.value)
    // 存储分页总数
    total.value = result.data.total
    console.log('total', total.value)
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}
// 搜索
const search = function () {
  getObj.value.pageNum = 1
  get()
}
// 重置
const reset = function () {
  delete rechargeUser.value.jwcode
  delete rechargeUser.value.activity
  delete rechargeUser.value.payPlatform
  delete rechargeUser.value.market
  delete rechargeUser.value.startTime
  delete rechargeUser.value.endTime
  delete sortField.value
  delete sortOrder.value
  getTime.value = {}
  get()
}
// 今天
const getToday = function () {
  const today = new Date()
  const startTime = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate()
  )
  const endTime = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() + 1
  )
  getTime.value = [startTime, endTime]
  console.log('getTime', getTime.value)
  get()
}
const handlePageSizeChange = function (val) {
  getObj.value.pageSize = val
  get()
}
const handleCurrentChange = function (val) {
  getObj.value.pageNum = val
  get()
}
// 昨天
const getYesterday = function () {
  const yesterday = new Date()
  yesterday.setDate(yesterday.getDate() - 1)
  const startTime = new Date(
    yesterday.getFullYear(),
    yesterday.getMonth(),
    yesterday.getDate()
  )
  const endTime = new Date(
    yesterday.getFullYear(),
    yesterday.getMonth(),
    yesterday.getDate() + 1
  )
  getTime.value = [startTime, endTime]
  console.log('getTime', getTime.value)
  get()
}
// 近7天
const get7Days = function () {
  const today = new Date()
  const startTime = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() - 6
  )
  const endTime = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() + 1
  )
  getTime.value = [startTime, endTime]
  console.log('getTime', getTime.value)
  get()
}
const exportExcel = async function () { 
  const params = {
    text:'',
    deptid:'',
    sort:1,
    field:'',
    page:getObj.pageNum,
    size:getObj.pageSize
  }
  const res = await API({ url: '/export/exportRecharge', data: params })
  if (res.code === 200) { 
    ElMessage.success('导出成功')
  }
}

// 挂载
onMounted(async function () {
  await get()
  await getActivity()
  await getArea()
  await getPlatform()
})
// 新增排序字段和排序方式
const sortField = ref()
const sortOrder = ref(1)
// 处理排序事件
const handleSortChange = (column) => {

  console.log('排序字段：', column.prop)
  console.log('排序方式：', column.order)
  if (column.prop === 'money') {
    sortField.value = 'money'
  } else if (column.prop === 'freeGold') {
    sortField.value = 'freeGold'
  } else if (column.prop === 'payTime') {
    sortField.value = 'payTime'
  } else if (column.prop === 'createTime') {
    sortField.value = 'createTime'
  } else if (column.prop === 'permanentGold') {
    sortField.value = 'permanentGold'
  }
  sortOrder.value = column.order === 'ascending' ? 'ASC' : 'DESC'
  console.log('传递给后端的排序字段：', sortField.value)
  console.log('传递给后端的排序方式：', sortOrder.value)
  get()
}
</script>

<template>
  <el-row>
    <el-col>
      <el-card style="margin-bottom: 20px;margin-top: 10px">
        <el-row style="margin-bottom: 10px">
          <el-col :span="5">
            <div class="head-card-element">
              <el-text class="mx-1" size="large">精网号：</el-text>
              <el-input v-model="rechargeUser.jwcode" placeholder="请输入精网号" style="width: 150px" clearable />
            </div>
          </el-col>
          <el-col :span="6">
            <div class="head-card-element">
              <el-text class="mx-1" size="large">活动名称：</el-text>
              <el-select v-model="rechargeUser.activity" placeholder="请选择活动名称" style="width: 180px" clearable>
                <el-option v-for="item in activity" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="head-card-element">
              <el-text class="mx-1" size="large">所属地区：</el-text>
              <el-select v-model="rechargeUser.market" placeholder="请选择所属地区" style="width: 180px" clearable>
                <el-option v-for="item in market" :key="item" :label="item" :value="item" />
              </el-select>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="head-card-element">
              <el-text class="mx-1" size="large">充值类型：</el-text>
              <el-select v-model="rechargeUser.payPlatform" placeholder="请选择充值方式" style="width: 180px" clearable>
                <el-option v-for="item in platform" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="21">
            <div class="head-card-element">
              <el-text class="mx-1" size="large">充值时间：</el-text>
              <el-date-picker v-model="getTime" type="datetimerange" range-separator="至" start-placeholder="起始时间"
                end-placeholder="结束时间" />
              <el-button style="margin-left: 10px" @click="getToday()">今</el-button>
              <el-button @click="getYesterday()">昨</el-button>
              <el-button @click="get7Days()">近7天</el-button>
              <el-button type="success" @click="reset()">重置</el-button>
              <el-button type="primary" @click="search()">查询</el-button>
              <el-button type="primary" @click="exportExcel()">导出Excel</el-button>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </el-col>
  </el-row>
  <el-row>
    <el-col>
      <el-card>
        <div>
          充值金额：{{ (permanentGolds ) /100 }}新币，永久金币：{{
            permanentGolds /100
          }}金币，免费金币：{{ freeGolds /100 }}金币
        </div>
        <!-- 设置表格容器的高度和滚动样式 -->
        <div style="height: 520px; overflow-y: auto;margin-top: 10px;">
          <el-table :data="tableData" style="width: 100%" height="520px" @sort-change="handleSortChange">
            <el-table-column type="index" label="序号" width="80px" 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="姓名" width="80px" />
            <el-table-column fixed="left" prop="jwcode" label="精网号" width="80px" />
            <el-table-column prop="market" label="所属地区" width="100px" />
            <el-table-column prop="activity" label="活动名称" width="100px" />
            <el-table-column prop="rateName" label="货币名称" width="110px" />
            <el-table-column prop="money" sortable="custom" label="充值金额" width="110px" />
            <el-table-column prop="permanentGold" label="永久金币" sortable="custom" width="110px" />
            <el-table-column prop="freeGold" label="免费金币" sortable="custom" width="110px" />
            <el-table-column prop="payPlatform" label="充值方式" width="100px" />
            <el-table-column prop="payModel" label="支付方式" width="100px" />
            <el-table-column prop="remark" label="备注" width="150px" show-overflow-tooltip />
            <el-table-column prop="adminName" label="提交人" width="100px" />
            <el-table-column prop="payTime" sortable label="充值时间" width="200px">
              <template #default="scope">
                {{ moment(scope.row.payTime).format('YYYY-MM-DD HH:mm:ss') }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination" style="margin-top: 20px">
          <el-pagination background :page-size="getObj.pageSize" :page-sizes="[5, 10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handlePageSizeChange"
            @current-change="handleCurrentChange"></el-pagination>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>
<style scoped>
.pagination {
  display: flex;
}

.status {
  display: flex;
}

.head-card {
  display: flex;
}

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

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