<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'
// 变量
//这是获取用户信息的接口
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 detail = ref({})
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 50
})
//分页总条目
const total = ref(100)
// 搜索对象时间
const getTime = ref([])
// 所有信息
const allData = ref([])
// 搜索地区列表
const area = ref([])

//标签页默认高亮选项
const activeName = ref('all')

// 退款类型
const consumeType = [
  {
    value: '退款商品',
    label: '退款商品'
  }
]

// //表格高度
// const tableHeight = computed(function () {
//   return (getObj.value.pageSize + 2) * 45 + "px";
// });

// 方法
// 统计合计数
const trueGold = ref(0)
const trueRgold = ref(0)
const trueFgold = ref(0)
const trueTgold = ref(0)
// 待审核各种类金币数
const pendingRgold = ref(0)
const pendingFgold = ref(0)
const pendingTgold = ref(0)
// 待审核金币数
const pendingGold = ref(0)
// 已通过各种类金币数
const approvedRgold = ref(0)
const approvedFgold = ref(0)
const approvedTgold = ref(0)
// 已通过金币数
const approvedGold = ref(0)
// 已驳回各种类金币数
const rejectedRgold = ref(0)
const rejectedFgold = ref(0)
const rejectedTgold = ref(0)
// 已驳回金币数
const rejectedGold = ref(0)
// 搜索==============================================================
// 搜索方法
const get = async function (val) {
  try {
    // 地区赋值
    if (adminData.value.area === '泰国') {
      detail.value.areas = ['泰国', '越南']
    } else if (adminData.value.area !== '总部') {
      detail.value.area = adminData.value.area
    }
    // 搜索参数页码赋值
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }
    // 搜索参数时间赋值
    if (getTime.value != null) {
      if (getTime.value.startDate != '' && getTime.value.endDate != '') {
        detail.value.startDate = getTime.value[0]
        detail.value.endDate = getTime.value[1]
      }
    } else {
      detail.value.startDate = ''
      detail.value.endDate = ''
    }
    // 添加排序字段和排序方式到请求参数
    detail.value.sortField = sortField.value
    detail.value.sortOrder = sortOrder.value
    console.log('搜索参数', getObj.value)
    // 发送POST请求
    const result = await API({
      url: '/refund/search',
      data: {
        ...getObj.value,
        detail: { ...detail.value }
      }
    })
    // 复制一份 detail.value 并移除排序字段和排序方式
    const detailWithoutSort = { ...detail.value }
    delete detailWithoutSort.sortField
    delete detailWithoutSort.sortOrder

    const result2 = await API({
      url: '/refund/RefundA',
      data: {
        ...detailWithoutSort
      }
    })
    // 统计合计数
    if (result2.data) {
      result2.data.forEach((item) => {
        switch (item.status) {
          case '待审核':
            // 若 item.raudit 为空则赋值为 0
            pendingRgold.value = item.sumRaudit1 || 0
            pendingFgold.value = item.sumRaudit2 || 0
            pendingTgold.value = item.sumRaudit3 || 0
            // 若 item.sumRaudit 为空则赋值为 0
            pendingGold.value = item.sumRaudit || 0
            break
          case '已通过':
            approvedRgold.value = item.sumRaudit1 || 0
            approvedFgold.value = item.sumRaudit2 || 0
            approvedTgold.value = item.sumRaudit3 || 0
            approvedGold.value = item.sumRaudit || 0
            break
          case '已驳回':
            rejectedRgold.value = item.sumRaudit1 || 0
            rejectedFgold.value = item.sumRaudit2 || 0
            rejectedTgold.value = item.sumRaudit3 || 0
            rejectedGold.value = item.sumRaudit || 0
            break
        }
      })
    }

    trueFgold.value =
      pendingFgold.value + approvedFgold.value + rejectedFgold.value
    trueRgold.value =
      pendingRgold.value + approvedRgold.value + rejectedRgold.value
    trueTgold.value =
      pendingTgold.value + approvedTgold.value + rejectedTgold.value
    trueGold.value = pendingGold.value + approvedGold.value + rejectedGold.value
    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)
    // 存储表格数据
    tableData.value = result.data.list
    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
  get()
}
// 重置
const reset = function () {
  detail.value.refundGoods = ''
  detail.value.refundType = ''
  detail.value.area = ''
  detail.value.startDate = ''
  detail.value.endDate = ''
  sortField.value = ''
  sortOrder.value = ''
  getTime.value = {}
}
// 今天
const getToday = function () {
  const today = new Date()
  const startDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate()
  )
  const endDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() + 1
  )
  getTime.value = [startDate, endDate]
  console.log('getTime', getTime.value)
  get()
}
// 昨天
const getYesterday = function () {
  const yesterday = new Date()
  yesterday.setDate(yesterday.getDate() - 1)
  const startDate = new Date(
    yesterday.getFullYear(),
    yesterday.getMonth(),
    yesterday.getDate()
  )
  const endDate = new Date(
    yesterday.getFullYear(),
    yesterday.getMonth(),
    yesterday.getDate() + 1
  )
  getTime.value = [startDate, endDate]
  console.log('getTime', getTime.value)
  get()
}
// 近7天
const get7Days = function () {
  const today = new Date()
  const startDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() - 6
  )
  const endDate = new Date(
    today.getFullYear(),
    today.getMonth(),
    today.getDate() + 1
  )
  getTime.value = [startDate, endDate]
  console.log('getTime', getTime.value)
  get()
}
//全部充值明细
const adminAll = function () {
  console.log('adminAll')
  detail.value.status = ''
  getObj.value.pageNum = 1

  get()
  trueFgold.value =
    pendingFgold.value + approvedFgold.value + rejectedFgold.value
  trueRgold.value =
    pendingRgold.value + approvedRgold.value + rejectedRgold.value
  trueTgold.value =
    pendingTgold.value + approvedTgold.value + rejectedTgold.value
  trueGold.value = pendingGold.value + approvedGold.value + rejectedGold.value
}
//待审核充值明细
const adminWait = async function () {
  detail.value.status = 0
  getObj.value.pageNum = 1
  await get()
  console.log('adminWait')
  trueFgold.value = pendingFgold.value
  trueRgold.value = pendingRgold.value
  trueTgold.value = pendingTgold.value
  trueGold.value = pendingGold.value
}
//已通过充值明细
const adminPass = async function () {
  detail.value.status = 1
  getObj.value.pageNum = 1
  await get()
  console.log('adminPass')
  trueFgold.value = approvedFgold.value
  trueRgold.value = approvedRgold.value
  trueTgold.value = approvedTgold.value
  trueGold.value = approvedGold.value
}
//已驳回充值明细
const adminReject = async function () {
  detail.value.status = 2
  getObj.value.pageNum = 1
  await get()
  console.log('adminReject')
  trueFgold.value = rejectedFgold.value
  trueRgold.value = rejectedRgold.value
  trueTgold.value = rejectedTgold.value
  trueGold.value = rejectedGold.value
}
//点击标签页
// 设置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 getArea = async function () {
  try {
    // 发送POST请求
    const result = await API({ url: '/recharge/user/search', data: {} })
    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)
    // 存储地区信息
    area.value = result.data
    console.log('地区', area.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)
    // 刷新表格数据
    get()
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}

// 查询商品的接口
const goods = ref([])
const getGoods = async function () {
  try {
    // 发送POST请求
    const result = await API({ url: '/product', data: {} })
    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)
    // 存储全部数据
    goods.value = result.data
    console.log('allData', allData.value)
    console.log('地区', area.value)
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}
getGoods()

// 验证跳转输入框的数字是否合法
const checkNumber = function () {
  if (typeof parseInt(getObj.value.pageNum) === 'number') {
    console.log('总共有多少页' + Math.ceil(total.value / getObj.value.pageSize))
    if (
      getObj.value.pageNum > 0 &&
      getObj.value.pageNum <= Math.ceil(total.value / getObj.value.pageSize)
    ) {
      getObj.value.pageNum = parseInt(getObj.value.pageNum)
      console.log('输入的数字合法')
      get()
    } else {
      //提示
      ElMessage({
        type: 'error',
        message: '请检查输入内容'
      })
    }
  } else {
    //提示
    ElMessage({
      type: 'error',
      message: '请检查输入内容'
    })
  }
}
// 挂载
onMounted(async function () {
  await getAdminData()
  await get()
  await getArea()
})
// 新增排序字段和排序方式
const sortField = ref('')
const sortOrder = ref('')
// 处理排序事件
const handleSortChange = (column) => {
  console.log('排序字段：', column.prop)
  console.log('排序方式：', column.order)
  if (column.prop === 'rechargeCoin') {
    sortField.value = 'recharge_coin'
  } else if (column.prop === 'taskCoin') {
    sortField.value = 'task_coin'
  } else if (column.prop === 'freeCoin') {
    sortField.value = 'free_coin'
  } else if (column.prop === 'createTime') {
    sortField.value = 'create_time'
  } else if (column.prop === 'auditTime') {
    sortField.value = 'audit_time'
  }
  sortOrder.value = column.order === 'ascending' ? 'ASC' : 'DESC'
  get()
}
const handlePageSizeChange = function (val) {
  getObj.value.pageSize = val
  get()
}
const handleCurrentChange = function (val) {
  getObj.value.pageNum = val
  get()
}
</script>

<template>
  <el-row>
    <el-col>
      <el-card style="margin-bottom: 20px">
        <el-row style="margin-bottom: 10px">
          <el-col :span="8">
            <div class="head-card-element">
              <el-text class="mx-1" size="large">退款类型：</el-text>
              <el-select
                v-model="detail.refundType"
                placeholder="请选择退款类型"
                size="large"
                style="width: 240px"
                clearable
              >
                <el-option
                  v-for="item in consumeType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="head-card-element">
              <el-text class="mx-1" size="large">退款商品：</el-text>
              <el-select
                v-model="detail.refundGoods"
                placeholder="请选择退款商品"
                size="large"
                style="width: 240px"
                clearable
                
              >
                <el-option
                  v-for="item in goods"
                  :key="item.value"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="head-card-element" v-if="adminData.area == '总部'">
              <el-text class="mx-1" size="large">所属地区：</el-text>
              <el-select
                v-model="detail.area"
                placeholder="请选择所属地区"
                size="large"
                style="width: 240px"
                clearable
              >
                <el-option
                  v-for="item in area"
                  :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" 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>
            </div>
          </el-col>
          <el-col :span="3">
            <div class="head-card-btn">
              <el-button type="success" @click="reset()">重置</el-button>
              <el-button type="primary" @click="search()">查询</el-button>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </el-col>
  </el-row>
  <el-row>
    <el-col>
      <el-card>
        <el-tabs
          v-model="activeName"
          type="card"
          class="demo-tabs"
          @tab-click="handleClick"
        >
          <el-tab-pane label="全部" name="all"></el-tab-pane>
          <el-tab-pane label="待审核" name="wait"></el-tab-pane>
          <el-tab-pane label="已通过" name="pass"></el-tab-pane>
          <el-tab-pane label="已驳回" name="reject"></el-tab-pane>
        </el-tabs>

        <div>
          退款金币总数：{{ Math.abs(trueGold) }}，永久金币：{{
            Math.abs(trueRgold)
          }}，免费金币：{{ Math.abs(trueFgold) }}，任务金币：{{
            Math.abs(trueTgold)
          }}
        </div>
        <!-- 设置表格容器的高度和滚动样式 -->
        <div style="height: 520px; overflow-y: auto">
          <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="username"
              label="姓名"
              fixed="left"
              width="150px"
            />
            <el-table-column
              prop="jwcode"
              label="精网号"
              fixed="left"
              width="110px"
            />
            <el-table-column prop="area" label="所属地区" width="110px" />
            <el-table-column prop="refundType" label="退款类型" width="100px" />
            <el-table-column prop="refundGoods" label="退款商品" width="110px">
            </el-table-column>
            <el-table-column label="退款金币数" width="110px">
              <template #default="scope">
                {{
                  scope.row.rechargeCoin +
                  scope.row.freeCoin +
                  scope.row.taskCoin
                }}
              </template>
            </el-table-column>
            <el-table-column
              prop="rechargeCoin"
              label="永久金币"
              width="110px"
              sortable="“custom”"
            />
            <el-table-column
              prop="freeCoin"
              sortable="“custom”"
              label="免费金币"
              width="110px"
            />
            <el-table-column
              prop="taskCoin"
              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="status" label="审核状态" width="120px">
              <!-- 模板内容 -->
              <template #default="scope">
                <span v-if="scope.row.status == 1">
                  <div class="status">
                    <span class="green-dot"></span>
                    <span>已通过</span>
                  </div>
                </span>
                <span v-if="scope.row.status == 0">
                  <div class="status">
                    <span class="grey-dot"></span>
                    <span>待审核</span>
                  </div>
                </span>
                <span v-if="scope.row.status == 2">
                  <div class="status">
                    <span class="red-dot"></span>
                    <span>已驳回</span>
                  </div>
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="reson"
              label="驳回理由"
              width="200px"
              show-overflow-tooltip
            />
            <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-column
              prop="auditTime"
              sortable="custom"
              label="审核时间"
              width="180px"
            >
              <template #default="scope">
                {{ moment(scope.row.auditTime).format('YYYY-MM-DD HH:mm:ss') }}
              </template>
            </el-table-column>
            <el-table-column
              prop="operation"
              label="操作"
              fixed="right"
              width="120px"
            >
              <template #default="scope">
                <el-popconfirm
                  title="确定将此条活动删除吗？"
                  @confirm="delConfirm"
                >
                  <template #reference>
                    <el-button type="primary" text @click="del(scope.row)">
                      删除
                    </el-button>
                  </template>
                  <template #actions="{ delConfirm, cancel }">
                    <el-button size="small" @click="cancel">取消</el-button>
                    <el-button type="primary" size="small" @click="delConfirm">
                      确定
                    </el-button>
                  </template>
                </el-popconfirm>
              </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>
.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>
