<script setup>
import { computed, onMounted, ref } from 'vue'
import { dayjs, ElMessage } from 'element-plus'
import request from '@/util/http'
import API from '@/util/http'
// 之后整理一下

/*
====================工具方法==============================
*/

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

/*
====================数据=================================
*/
//这是获取用户信息的接口
const adminData = ref({})
// 充值明细表格
const tableData = ref([])

// 搜索consumeUser 表单
const consumeUser = ref({
  jwcode: null,
  payPlatform: "",
  market: "",

  startTime: '',
  endTime: '',

  goodsName: '',


})


// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 50
})

//分页总条目
const total = ref(100)

// 搜索对象时间
const getTime = ref({
  startTime: '',
  endTime: ''
})
// 搜索活动列表
const activity = ref([])

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

// 新增排序字段和排序方式
const sortField = ref('')
const sortOrder = ref('')

// 消费平台选项
const consumePlatform = [
  {
    value: '金币系统',
    label: '金币系统'
  },

  {
    value: 'Homily Chart',
    label: 'Homily Chart'
  },
  {
    value: 'Homily Link',
    label: 'Homily Link'
  },
  {
    value: 'ERP',
    label: 'ERP'
  }
]

// 合计数的显示数据
const tableDataTotal = ref({})

const permanentGold = ref(0)
const freeGold = ref(0)
const taskGold = ref(0)
const totalGold = ref(0)
// 定义响应式变量存储金币合计数
const permanentGolds = ref(0)
const freeGolds = ref(0)
const taskGolds = ref(0)
// 查询商品的接口的表单
const goods = ref([])

const totalGoldSearch = ref({
  jwcode: null,
  payPlatform: "",
  market: "",
  startTime: "",
  endTime: "",
  goodsName: ""
})

/*
====================方法=================================
*/
// 获取登录用户信息
const getAdminData = async function () {
  try {
    const result = await request({
      url: '/admin/userinfo',
      data: {}
    })
    adminData.value = result
    console.log('请求成功', result)
    console.log('用户信息', adminData.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}


const ConsumeSelectBy = async function (val) {
  try {

    // 搜索参数页码赋值
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }
    // 搜索参数时间赋值

    if (getTime.value != null) {
      if (getTime.value.startTime != '' && getTime.value.endTime != '') {
        consumeUser.value.startTime = formatTime(getTime.value[0])
        consumeUser.value.endTime = formatTime(getTime.value[1])
      }
    } else {
      consumeUser.value.startTime = ''
      consumeUser.value.endTime = ''
    }
    consumeUser.value.sortField = sortField.value
    consumeUser.value.sortOrder = sortOrder.value

    console.log('搜索参数_时间', consumeUser.value.startTime)

    console.log('搜索参数1', getObj.value)

    console.log('搜索参数2', consumeUser.value)

    // 发送POST请求
    const result = await request({
      url: '/consume/selectBy',
      data: {
        pageNum: getObj.value.pageNum,
        pageSize: getObj.value.pageSize,
        consumeUser: {
          ...consumeUser.value,
          sortField: sortField.value,
          sortOrder: sortOrder.value
        }
      }
    })

    console.log('请求成功2', sortField)

    // 合计数的接口
    // 复制一份 detail.value 并移除排序字段和排序方式
    const detailWithoutSort = { ...consumeUser.value }
    delete detailWithoutSort.sortField
    delete detailWithoutSort.sortOrder


    // 赋值
    totalGoldSearch.value.startTime = consumeUser.value.startTime
    totalGoldSearch.value.endTime = consumeUser.value.endTime
    totalGoldSearch.value.payPlatform = consumeUser.value.payPlatform
    totalGoldSearch.value.market = consumeUser.value.market
    totalGoldSearch.value.goodsName = consumeUser.value.goodsName
    totalGoldSearch.value.jwcode = consumeUser.value.jwcode
    //
    const resultTotalGold = await request({
      // url: '/consume/statsGold',
      url: '/consume/statsGold',
      data: totalGoldSearch.value

    })

    console.log("总计", resultTotalGold)

    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
    tableDataTotal.value = resultTotalGold.data
    if (resultTotalGold.data == null) {
      console.log('请求成功2', resultTotalGold)
      // 这是啥东西啊
      tableDataTotal.value = resultTotalGold.data
    }

    const sumGoldList = tableData.value.map(item => item.sumGold);
    console.log("sumGold", sumGoldList); // 输出包含所有 sumGold 值的数组

    console.log('@@@@@@@@@@tableDataT', tableDataTotal.value.list)


    // totalGold.value = tableData.value.sum

    // // 修改为保留两位小数
    // permanentGold.value = parseFloat(
    //     (tableDataTotal.value.list.sumGold / 100).toFixed(2)
    // )
    // freeGold.value = parseFloat(
    //     (tableDataTotal.value.sumFcion / 100).toFixed(2)
    // )
    // taskGold.value = parseFloat(
    //     (tableDataTotal.value.sumTcion / 100).toFixed(2)
    // )
    // totalGold.value = parseFloat(
    //     (tableDataTotal.value.sumcion / 100).toFixed(2)
    // )
    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
  ConsumeSelectBy()
}
// 重置
const reset = function () {
  console.log('兄弟，你点了重置')

  consumeUser.value.goodsName = ''

  consumeUser.value.market = ''

  consumeUser.value.payPlatform = ''

  consumeUser.value.startTime = ''

  consumeUser.value.endTime = ''
  consumeUser.value.jwcode = null


  sortField.value = ''
  sortOrder.value = ''
  getTime.value = {}

  // 点完重置后，重新请求数据
  ConsumeSelectBy()
  console.log('consumeUser', consumeUser.value)
}
// 今天
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)
  ConsumeSelectBy()
}
// 昨天
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)
  ConsumeSelectBy()
}
// 近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)
  ConsumeSelectBy()
}
// 获取商品列表
const getGoods = async function () {
  try {
    // 发送POST请求
    const result = await request({
      url: '/general/goods',
      data: {}
    })
    // 将响应结果存储到响应式数据中
    console.log('请求成功product', result)
    // 存储全部数据
    goods.value = result.data
    console.log('goods 数据', goods.value) // 修改日志输出
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}

// 获取地区列表的方法
const getMarket = async function () {
  try {
    // 发送请求获取地区列表
    const result = await request({
      // url: '/general/market',
      url: '/general/market', // todo 换成实际接口地址
      data: {}
    })
    console.log('请求地区列表成功', result)
    // 存储地区数据
    market.value = result.data
    console.log('地区数据', market.value)
  } catch (error) {
    console.log('请求地区列表失败', error)
    ElMessage({
      type: 'error',
      message: '获取地区列表失败，请稍后重试'
    })
  }
}

// 处理排序事件
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'
  }
  sortOrder.value = column.order === 'ascending' ? 'DESC' : 'ASC'
  ConsumeSelectBy()
}
const exportExcel = async function () {
  const params = {
    consumUser :{
      jwcode:consumeUser.value.jwcode || '',
      payPlatform:consumeUser.value.payPlatform || '',
      market:consumeUser.value.market || '',
      startTime:consumeUser.value.startTime || '',
      endTime:consumeUser.value.endTime || '',
      goodsName:consumeUser.value.goodsName || ''
    },
    page:getObj.pageNum,
    size:getObj.pageSize
  }
  const res = await API({ url: '/export/exportConsume', data: params })
  if (res.code === 200) { 
    ElMessage.success('导出成功')
  }
}
const handlePageSizeChange = function (val) {
  getObj.value.pageSize = val
  ConsumeSelectBy()
}

const handleCurrentChange = function (val) {
  getObj.value.pageNum = val
  ConsumeSelectBy()
}
/*
====================计算属性=================================
*/

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

/*
====================监听=================================
*/

/*
====================挂载=================================
*/


onMounted(async function () {
  await getAdminData()
  await ConsumeSelectBy()
  // getActivity();
  await getMarket()
  await getGoods()
})


</script>

<template>
  <el-row>
    <el-col>
      <el-card style="margin-bottom: 20px;margin-top:10px">
        <el-row style="margin-bottom: 10px">
          <el-col :span="6">
            <div class="head-card-element">
              <el-text size="large">精网号：</el-text>
              <el-input v-model="consumeUser.jwcode" placeholder="请输入精网号" size="large" style="width: 240px"
                         clearable>
              </el-input>
            </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="consumeUser.goodsName" placeholder="请选择商品名称" size="large" style="width: 180px"
                clearable>
                <!-- 修改 v-for 绑定逻辑 -->
                <el-option v-for="(item, index) in goods" :key="index" :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="consumeUser.market" placeholder="请选择所属地区" size="large" style="width: 180px" clearable>
                <el-option v-for="(item, index) in market" :key="index" :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="consumeUser.payPlatform" placeholder="请选择消耗平台" size="large" style="width: 180px"
                clearable>
                <el-option v-for="item in consumePlatform" :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>
              <!-- </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>

              <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(sumGold) / 100 }}新币，永久金币：{{ Math.abs(permanentGolds) / 100 }}，免费金币：{{
            Math.abs(freeGolds) / 100
          }}，任务金币：{{ Math.abs(taskGolds) / 100 }}
        </div>
        <!-- 设置表格容器的高度和滚动样式 -->
        <div style="height: 576px; overflow-y: auto">
          <el-table :data="tableData" style="width: 100%" height="576px" @sort-change="handleSortChange">
            <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="姓名" width="150px" fixed="left" />
            <!-- 固定精网号列 -->
            <el-table-column prop="jwcode" label="精网号" width="110px" fixed="left" />
            <el-table-column prop="market" label="所属地区" width="110px" />
            <el-table-column prop="goodsName" label="商品" width="160px" show-overflow-tooltip />
            <el-table-column prop="payPlatform" label="消费平台" width="120px">
              <template #default="scope">
                <!-- 使用非严格相等比较 -->
                {{ scope.row.payPlatform }}
                <!--                <span scope.row.consumePlatform == 1">Homily Chart</span>-->

              </template>
            </el-table-column>
            <!-- <el-table-column
              prop="consumeType"
              label="消费类型"
              width="120px"
            /> -->
            <el-table-column prop="sumGold" label="消费金币总数" width="120px">
              <template #default="scope">
                {{
                  (scope.row.taskGold +
                    scope.row.freeGold +
                    scope.row.permanentGold) / 100
                }}
              </template>
            </el-table-column>

            <el-table-column prop="permanentGold" label="永久金币" sortable="“custom”" width="110px">
              <template #default="scope">
                {{ scope.row.permanentGold / 100 }}
              </template>
            </el-table-column>
            <el-table-column prop="freeGold" label="免费金币" sortable="“custom”" width="110px">
              <template #default="scope">
                {{ scope.row.freeGold / 100 }}
              </template>
            </el-table-column>
            <el-table-column prop="taskGold" label="任务金币" sortable="“custom”" width="110px">
              <template #default="scope">
                {{ scope.row.taskGold / 100 }}
              </template>
            </el-table-column>

            <el-table-column prop="remark" label="备注" width="200px" show-overflow-tooltip />
            <el-table-column prop="adminName" label="提交人" width="110px" />
            <el-table-column prop="createTime" label="消费时间" sortable="custom" width="180px" />
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <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>
