<script setup>
// 这是退款明细页面
import {ref, onMounted, reactive, computed} from 'vue'
import ElementPlus from 'element-plus'
import {AiFillRead} from 'vue-icons-plus/ai'
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from 'axios'
import moment from 'moment'
import API from '@/util/http'
import request from '@/util/http'

// 精网号去空格
const trimJwCode = () => {
  if (refundUser.value.jwcode) {
    // 去除所有空格，并尝试转换为整数
    const trimmed = refundUser.value.jwcode.toString().replace(/\s/g, '');
    const numeric = Number(trimmed);

    // 如果转换为数字成功，保存为数字，否则提示错误
    if (!isNaN(numeric)) {
      refundUser.value.jwcode = numeric;
    } else {
      ElMessage.error("精网号格式不正确，请输入数字");
    }
  }
}

// 变量
//这是获取用户信息的接口
const adminData = ref({})
const getAdminData = async function () {
  try {
    const result = await API({url: '/admin/userinfo', data: {}})

    adminData.value = result
    console.log('请求成功', result)
    console.log('用户信息', adminData.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}
// 充值明细表格
const tableData = ref([])
// 搜索======================================
// 搜索detail
const refundUser = ref({})
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 50
})
//分页总条目
const total = ref(100)
// 搜索对象时间
const getTime = ref([])

// 搜索地区列表
const market = ref([])

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

// 计算总金币数
const sumGolds = computed(() => permanentGolds.value + freeGolds.value + taskGolds.value)

// 退款类型
const refundType = ref([])

//时间格式化
const formatTime = (val) => val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ''

// 获取退款类型
const getRefundTypes = async function () {
  try {
    // 发送请求获取退款类型
    const result = await API({ 
      url: '/refund/refundType', //这里应该写上一个退款类型的接口
      data: {} })
    console.log('退款类型请求成功', result)
    // 检查返回的数据是否为数组
    if (Array.isArray(result.data)) {
      // 将字符串数组转换为 { value, label } 格式
      refundType.value = result.data.map(item => ({ value: item, label: item }));
    } else {
      console.error('退款类型数据格式错误', result)
      ElMessage.error('退款类型数据格式错误，请联系管理员')
    }
    console.log('退款类型', refundType.value)
  } catch (error) {
    console.log('退款类型请求失败', error)
  }
}

// 搜索==============================================================
// 搜索方法
const getSelectBy = async function (val) {
  try {
    // 搜索参数页码赋值
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }

    // todo 时间格式化
    // 搜索参数时间赋值
    if (getTime.value != null) {
      if (getTime.value.startTime != '' && getTime.value.endTime != '') {
        refundUser.value.startTime = formatTime(getTime.value[0])
        refundUser.value.endTime = formatTime(getTime.value[1])
      }
    } else {
      refundUser.value.startTime = ''
      refundUser.value.endTime = ''
    }

    // todo 排序后端还没有弄
    // 添加排序字段和排序方式到请求参数
    refundUser.value.sortField = sortField.value
    refundUser.value.sortOrder = sortOrder.value
    console.log('搜索参数', getObj.value)
    // 发送POST请求
    const result = await API({
      url: '/refund/selectBy',
      data: {
        ...getObj.value,
        refundUser: { ...refundUser.value }
      }
    })
    // 复制一份 refundUser.value 并移除排序字段和排序方式
    const detailWithoutSort = { ...refundUser.value }
    delete detailWithoutSort.sortField
    delete detailWithoutSort.sortOrder

    const resultTotalGold = await API({
      url: '/refund/statsGold',
      data: {
         ...detailWithoutSort
      }
    })
    // 将响应结果存储到响应式数据中
     console.log('resultTotalGold请求成功', resultTotalGold)
    // 检查响应的 code 是否为 200 且 data 存在
    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) 
      taskGolds.value = (Number(data.taskGolds) || 0) 
    }

    // 存储表格数据
    tableData.value = result.data.list
    // 对表格中的金币数据除以 100
    tableData.value = tableData.value.map(item => ({
      ...item,
      sumGold: (Number(item.sumGold) || 0) / 100,
      permanentGold: (Number(item.permanentGold) || 0) / 100,
      freeGold: (Number(item.freeGold) || 0) / 100,
      taskGold: (Number(item.taskGold) || 0) / 100
    }))
    console.log('tableData', tableData.value)
    // 存储分页总数
    total.value = result.data.total
    console.log('total', total.value)
    // 调用分类的方法
    handleClick()
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}
// 搜索
const search = function () {
  getObj.value.pageNum = 1
  getSelectBy()
}
// 重置
const reset = function () {
  refundUser.value = {}
  sortField.value = ''
  sortOrder.value = ''
  getTime.value = {}
  getSelectBy()
}
// 今天
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)
  getSelectBy()
}
// 昨天
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)
  getSelectBy()
}
// 近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)
  getSelectBy()
}

//点击标签页
// 设置tab.props.name默认为all
const tabName = ref('all')
const handleClick = function (tab, event) {
  if (tab.props.name === 'all') {
    adminAll()
  } else if (tab.props.name === 'wait') {
    adminWait()
  } else if (tab.props.name === 'pass') {
    adminPass()
  } else if (tab.props.name === 'reject') {
    adminReject()
  }
}

// 获取地区列表的方法
const getMarket = 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 delObj = ref({})
const del = function (row) {
  delObj.value.detailId = row.detailId
  console.log('delObj', delObj.value)
}
// 删除按钮的气泡弹出框确认按钮
const delConfirm = async function () {
  try {
    console.log('delObj', delObj.value)
    // 发送POST请求
    const result = await API({
      url: '/refund/softDelete?detailId=' + delObj.value.detailId,
      data: {}
    })
    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)
    // 刷新表格数据
    getSelectBy()
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}

// 查询商品的接口
const goods = ref([])
const getGoods = async function () {
  try {
    // 发送POST请求
    const result = await request({
      url: '/general/goods',
      data: {}
    })
    // 将响应结果存储到响应式数据中
    console.log('请求成功product', result)
    if (Array.isArray(result.data)) {
      // 过滤掉空字符串和 null 值
      const validGoods = result.data.filter(item => item && item.trim() !== '');
      // 直接使用后端返回的字符串作为 value 和 label
      goods.value = validGoods.map(item => ({
        value: item,
        label: item
      }));
    }
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}
const exportExcel = async function () { 
  const params = {
    text:'',
    deptid:'',
    sort:1,
    field:'',
    page:getObj.pageNum,
    size:getObj.pageSize
  }
  const res = await API({ url: '/export/exportRefund', data: params })
  if (res.code === 200) { 
    ElMessage.success('导出成功')
  }
}
// 挂载
onMounted(async function () {
  await getAdminData()
  await getSelectBy()
  await getMarket()
  await getRefundTypes()
  await getGoods()
})
// 新增排序字段和排序方式
const sortField = ref('')
const sortOrder = ref('')
// 处理排序事件
const handleSortChange = (column) => {
  console.log('排序字段：', column.prop)
  console.log('排序方式：', column.order)
  if (column.prop === 'permanentGold') {
    sortField.value = 'permanentGold'
  } else if (column.prop === 'taskGold') {
    sortField.value = 'taskGold'
  } else if (column.prop === 'freeGold') {
    sortField.value = 'freeGold'
  } else if (column.prop === 'createTime') {
    sortField.value = 'createTime'
  } else if (column.prop === 'auditTime') {
    sortField.value = 'auditTime'
  } else if (column.prop === 'sumGold') { 
    sortField.value = 'sumGold'
  }
  sortOrder.value = column.order === 'ascending' ? 'ASC' : 'DESC'
  getSelectBy()
}
const handlePageSizeChange = function (val) {
  getObj.value.pageSize = val
  getSelectBy()
}
const handleCurrentChange = function (val) {
  getObj.value.pageNum = val
  getSelectBy()
}
</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"  >精网号：</el-text>

              <el-input
                v-model="refundUser.jwcode"
                placeholder="请输入精网号"
                 
                style="width: 150px"
                clearable
              />
            </div>
          </el-col>
          <el-col :span="6">
            <div class="head-card-element">
              <el-text class="mx-1"  >退款类型：</el-text>
              <el-select
                v-model="refundUser.refundType"
                placeholder="请选择退款类型"
                 
                style="width: 180px"
                clearable
              >
<!--                todo 这需要改-->
                <el-option
                  v-for="item in refundType"
                  :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"  >退款商品：</el-text>
              <el-select
                v-model="refundUser.goodsName"
                placeholder="请选择退款商品"
                 
                style="width: 180px"
                clearable
                
              >
                <el-option
                    v-for="item in goods"
                    :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"  >所属地区：</el-text>
              <el-select
                v-model="refundUser.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-row>
        <el-row>
          <el-col :span="21">
            <div class="head-card-element">
              <el-text class="mx-1"  >退款时间：</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>
          退款金币总数：{{ Math.abs(sumGolds) / 100 }}，永久金币：{{
            Math.abs(permanentGolds) / 100
          }}，免费金币：{{ Math.abs(freeGolds) / 100 }}，任务金币：{{
            Math.abs(taskGolds) / 100
          }}
        </div>
        <!-- 设置表格容器的高度和滚动样式 -->
        <div style="height: 520px; overflow-y: auto;margin-top:10px">
          <el-table
              :data="tableData"
              style="width: 100%"
              @sort-change="handleSortChange"
              height="520px"
          >
            <el-table-column
                type="index"
                label="序号"
                width="100px"
                fixed="left"
            >
              <template #default="scope">
                <span>{{
                    scope.$index + 1 + (getObj.pageNum - 1) * getObj.pageSize
                  }}</span>

              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="姓名"
              fixed="left"
              width="100px"
            />
            <el-table-column
                prop="jwcode"
                label="精网号"
                fixed="left"
                width="110px"
            />
            <el-table-column prop="market" label="所属地区" width="110px" />
            <el-table-column prop="goodsName" label="商品名称" width="100px" />
            <el-table-column prop="refundType" label="退款类型" width="100px" />

            <!-- <el-table-column label="金额总数" width="110px">
              <template #default="scope">
                {{
                  scope.row.sumGold
                }}
              </template>
            </el-table-column> -->

            <el-table-column
              prop="sumGold"
              label="金额总数"
              width="110px"
              sortable="custom"
            />

            <el-table-column prop="refundModel" label="退款方式" width="110px">
              <template #default="scope">
                {{ scope.row.refundModel === 0 ? '全部退款' : scope.row.refundModel === 1 ? '部分退款' : '' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="permanentGold"
              label="永久金币"
              width="110px"
              sortable="custom"
            />
            <el-table-column
              prop="freeGold"
              sortable="custom"
              label="免费金币"
              width="110px"
            />
            <el-table-column
              prop="taskGold"
              sortable="custom"
              label="任务金币"
              width="110px"
            />
            <!-- 修改prop为taskGold -->
            <el-table-column
                prop="remark"
                label="退款原因"
                width="160px"
                show-overflow-tooltip
            />
            <el-table-column prop="adminName" label="提交人" width="100px" />
             
            <el-table-column
              prop="createTime"
              sortable="custom"
              label="提交时间"
              width="180px"
            >
              <template #default="scope">
                {{ moment(scope.row.createTime).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"
              @jump="checkPageNumber"
          ></el-pagination>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<style scoped>
.status {
  display: flex;
}

.head-card {
  display: flex;
}

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

.head-card-btn {
  margin-left: auto;
}

.pagination {
  display: flex;
  margin-top: 20px;
}
</style>
