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

/*
====================工具方法==============================
*/
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1,23 , 59, 59),
]
const format3 = (num) => {
    // 每三位添加逗号
    return num.toLocaleString('en-US')
}
// 时间格式化
const formatTime = (val) => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : ''

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

// 搜索beanConsumeLive 表单
const beanConsumeLive = ref({
  jwcode: null,
  dept: "",
  type: "",
  gift: "",
  liveChannel: "",
  liveName: "",
  startTime: '',
  endTime: '',
  sortField: '',
  sortOrder: ''

})
// 礼物列表
const gifts = ref([])
// 获取礼物列表的方法
const getGift = async function () {
  try {
    const result = await request({
      url: '/beanConsume/getLiveGift', // todo 换成实际接口地址
      data: {account:adminData.value.account}
    })
    console.log('请求礼物列表成功', result)
    // 存储礼物数据
    gifts.value = result.data
    console.log('礼物数据', gifts.value)
  } catch (error) {
    console.log('请求礼物列表失败', error)
    ElMessage({
      type: 'error',
      message: '获取礼物列表失败，请稍后重试'
    })
  }
}

// 频道列表
const channels = ref([])
// 获取频道列表的方法
const getChannel = async function () {
  try {
    const result = await request({
      url: '/beanConsume/getLiveChannel', // todo 换成实际接口地址
      data: {account:adminData.value.account}
    })
    console.log('请求频道列表成功', result)
    // 存储频道数据
    channels.value = result.data
    console.log('频道数据', channels.value)
  } catch (error) {
    console.log('请求频道列表失败', error)
    ElMessage({
      type: 'error',
      message: '获取频道列表失败，请稍后重试'
    })
  }
}

// 抽离类型选项到响应式数组
const consumeTypes = ref([
  { label: '发礼物', value: 1 },
  { label: '发红包', value: 2 },
  { label: '发福袋', value: 3 },
  { label: '付费直播', value: 4 },
  { label: '加入粉丝团', value: 5 },
  { label: '发弹幕', value: 6 }
])
// 处理类型选择变化
const handleTypeChange = (value) => {
  if (value !==  1) {
    beanConsumeLive.value.gift = ''
  }
}

//------------------------

// 标记当前激活的时间范围按钮
const activeTimeRange = ref('')
// 日期选择器变化时清除按钮激活状态
const handleDatePickerChange = () => {
  activeTimeRange.value = ''
}
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 50
})

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

// 搜索对象时间
const getTime = ref({
  startTime: '',
  endTime: ''
})


// 搜索地区列表
const dept = ref([])
// 获取地区列表的方法
const getDept = async function () {
  try {
    // 发送请求获取地区列表
    const result = await request({
      // url: '/general/dept',

      url: '/beanConsume/getDept', // todo 换成实际接口地址
      data: {account:adminData.value.account}
    })
    console.log('请求地区列表成功', result)
    // 存储地区数据
    dept.value = result.data
    console.log('地区数据', dept.value)
  } catch (error) {
    console.log('请求地区列表失败', error)
    ElMessage({
      type: 'error',
      message: '获取地区列表失败，请稍后重试'
    })
  }
}

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

// 合计数
const permanentBean = ref(0)
const freeBean = ref(0)
const totalNum = ref(0)

/*
====================方法=================================
*/
// 获取登录用户信息
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 selectLiveBy = async function (val) {
  try {

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

    // 修复时间范围处理
    if (Array.isArray(getTime.value) && getTime.value.length === 2) {
      beanConsumeLive.value.startTime = formatTime(getTime.value[0])
      beanConsumeLive.value.endTime = formatTime(getTime.value[1])
    } else {
      beanConsumeLive.value.startTime = ''
      beanConsumeLive.value.endTime = ''
    }
    
    // 设置排序参数
    beanConsumeLive.value.sortField = sortField.value
    beanConsumeLive.value.sortOrder = sortOrder.value

    console.log('搜索参数_时间',  beanConsumeLive.value.startTime)
    console.log('搜索参数1', getObj.value)
    console.log('搜索参数2',  beanConsumeLive.value)

    // 发送POST请求
    const result = await request({
      url: '/beanConsume/selectLiveBy',
      data: {
        pageNum: getObj.value.pageNum,
        pageSize: getObj.value.pageSize,
        beanConsumeLive: {
          ...beanConsumeLive.value,
          jwcode: beanConsumeLive.value.jwcode ? String(beanConsumeLive.value.jwcode) : '',
          dept: beanConsumeLive.value.dept || '',
          type: beanConsumeLive.value.type || '',
          gift: beanConsumeLive.value.gift || '',
          beanNum: beanConsumeLive.value.beanNum || '',
          isBackpack: beanConsumeLive.value.isBackpack || '',
          liveChannel: beanConsumeLive.value.liveChannel || '',
          liveName: beanConsumeLive.value.liveName || '',
          startTime: beanConsumeLive.value.startTime || '',
          endTime: beanConsumeLive.value.endTime || '',
          sortField: beanConsumeLive.value.sortField || 'consumeTime',
          sortOrder: beanConsumeLive.value.sortOrder || 'desc'
        }
      }
    })

    console.log('请求成功2', sortField)
     console.log('接口响应结果', result); // 打印接口响应结果
     if (result.code === 200 && result.data && result.data.list) {
      tableData.value = result.data.list;
      total.value = result.data.total;
    }
     // 复制一份 beanConsumeLive.value 并设置固定的 payType 值 1是直播
    const sumConsumeParams = {
      payType: 1, // 固定传入 payType 值 1 是直播
      beanConsumeLive: {
        ...beanConsumeLive.value,
        
      }
    };

    // 发送 POST 请求获取合计数
    const resultTotalGold = await request({
      url: '/beanConsume/sumConsumeGold',
      data: sumConsumeParams
    });

    console.log("总计", resultTotalGold);

    const data = resultTotalGold.data || resultTotalGold;
    console.log('请求成功1', resultTotalGold.data) //undifined
    console.log('permanentBean1',data.permanentBean)
      // 返回字段为 permanentBean、freeBean、totalNum
      permanentBean.value = Number(data.permanentBean) || 0;
      freeBean.value = Number(data.freeBean) || 0;
      totalNum.value = Number(data.totalNum) || 0;
    


    // 存储分页总数
    total.value = result.data.total
    console.log('total', total.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}
// 搜索
const search = function () {
  getObj.value.pageNum = 1
  if(beanConsumeLive.value.jwcode){
        const numRef = /^\d{1,9}$/;
        if(!numRef.test(beanConsumeLive.value.jwcode)){
            ElMessage.error('请检查精网号格式')
            return 
        }
    }
   selectLiveBy() 
}
// 重置
const reset = function () {
  console.log('直播的重置')

  beanConsumeLive.value.jwcode = null
   beanConsumeLive.value.type = ''
   beanConsumeLive.value.gift = ''
   beanConsumeLive.value.liveChannel = ''
   beanConsumeLive.value.liveName = ''
   beanConsumeLive.value.dept = ''
   beanConsumeLive.value.startTime = ''
   beanConsumeLive.value.endTime = ''
  sortField.value = ''
  sortOrder.value = ''
  getTime.value = {}
  activeTimeRange.value = '' // 清除激活状态


  // 点完重置后，重新请求数据
  selectLiveBy() 
  console.log(' beanConsumeLive',  beanConsumeLive.value)
}
// 今天
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' // 标记当前激活状态

   selectLiveBy()
}
// 昨天
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' // 标记当前激活状态

   selectLiveBy() 
}
// 近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' // 标记当前激活状态

  selectLiveBy() 
}




// 处理排序事件
const handleSortChange = (column) => {
  console.log('排序字段：', column.prop)
  console.log('排序方式：', column.order)
  if (column.prop === 'beanNum') {
    sortField.value = 'beanNum'
  } else if (column.prop === 'consumeTime') {
    sortField.value = 'consumeTime'
  } else if(column.prop === 'buyBean') {
    sortField.value = 'buyBean'
  } else if(column.prop === 'freeBean') {
    sortField.value = 'freeBean'
  }
  sortOrder.value = column.order === 'ascending' ? 'DESC' : 'ASC'
  selectLiveBy()
}

const handlePageSizeChange = function (val) {
  getObj.value.pageSize = val
  selectLiveBy()
}

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

// 计算总金币数
// const totalBean = computed(() => permanentBean.value + freeBean.value)

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

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


onMounted(async function () {
  await getAdminData()
  await selectLiveBy()
  await getDept()
  await getGift()
  await getChannel()
})


const exportExcel = async function () {
  console.log('1')
  const params = {
    ...getObj.value,
    "beanConsumeLive": {
      ...beanConsumeLive.value,
      jwcode: beanConsumeLive.value.jwcode ? String(beanConsumeLive.value.jwcode) : '',
      dept: beanConsumeLive.value.dept || '',
      type: beanConsumeLive.value.type || '',
      gift: beanConsumeLive.value.gift || '',
      liveChannel: beanConsumeLive.value.liveChannel || '',
      liveName: beanConsumeLive.value.liveName || '',
      startTime: beanConsumeLive.value.startTime || '',
      endTime: beanConsumeLive.value.endTime || '',
      sortField: sortField.value || 'consumeTime',
      sortOrder: sortOrder.value || 'desc'
    }
  }
  // 打印请求参数，方便调试
  console.log('导出请求参数:', params);

  try {
    console.log('2')
    const res = await API({ url: '/export/exportLive', data: params });
    console.log('导出请求响应:', res);
    if (res.code === 200) {
      ElMessage.success('导出成功');
    } else {
      ElMessage.error(res.message || '导出失败，请稍后重试');
    }
  } catch (error) {
    console.error('导出请求出错:', error);
    ElMessage.error('导出失败，请稍后重试');
  }
}
const exportListVisible = ref(false)

// 打开导出列表弹窗
const openExportList = () => {
  getExportList()
  exportListVisible.value = true
}

// 导出列表数据
const exportList = ref([])
// 导出列表加载状态
const exportListLoading = ref(false)

// 获取导出列表
const getExportList = async () => {
  exportListLoading.value = true
  try {
    const result = await API({ url: '/export/export' })
    if (result.code === 200) {
      const filteredData = result.data.filter(item => {
        return item.type === 6; //4表示金币消耗列表 // todo 修改对应type 6是直播
      });
      exportList.value = filteredData
    } else {
      ElMessage.error(result.msg || '获取导出列表失败')
    }
  } catch (error) {
    console.error('获取导出列表出错:', error)
    ElMessage.error('获取导出列表失败，请稍后重试')
  } finally {
    exportListLoading.value = false
  }
}
// 下载导出文件
const downloadExportFile = (item) => {
  if (item.state === 2) {
    const link = document.createElement('a')
    link.href = item.url
    link.download = item.fileName
    link.click()
  } else {
    ElMessage.warning('文件还在导出中，请稍后再试')
  }
}
//根据状态返回对应的标签类型
const getTagType = (state) => {
  switch (state) {
    case 0:
      return 'info';
    case 1:
      return 'primary';
    case 2:
      return 'success';
    case 3:
      return 'danger';
    default:
      return 'info';
  }
}
//根据状态返回对应的标签文案
const getTagText = (state) => {
  switch (state) {
    case 0:
      return '待执行';
    case 1:
      return '执行中';
    case 2:
      return '执行完成';
    case 3:
      return '执行出错';
    default:
      return '未知状态';
  }
}
</script>

<template>
  <el-row>
    <el-col>
      <el-card style="margin-bottom: 20px;margin-top:10px">
        <el-row style="margin-bottom: 10px">
          <el-col :span="4">
            <div class="head-card-element">
              <el-text class="mx-1">精网号：</el-text>
              <el-input v-model="beanConsumeLive.jwcode" placeholder="请输入精网号" style="width: 140px" clearable />
            </div>
          </el-col>
          <el-col :span="4">
            <div class="head-card-element">
              <el-text class="mx-1">地区：</el-text>
              <el-select v-model="beanConsumeLive.dept" placeholder="请选择地区" style="width: 140px" clearable>
                <el-option v-for="(item, index) in dept" :key="index" :label="item" :value="item" />
              </el-select>
            </div>
          </el-col>
          <!-- <el-col :span="4">
            <div class="head-card-element">
              <el-text class="mx-1">类型：</el-text>
              <el-select v-model="beanConsumeLive.type" placeholder="请选择类型" style="width: 140px" clearable @change="handleTypeChange">
                <el-option v-for="(item, index) in consumeTypes" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </el-col> -->
          <el-col :span="4" >
            <div class="head-card-element">
              <el-text class="mx-1">礼物名称：</el-text>
              <el-select v-model="beanConsumeLive.gift" placeholder="请选择礼物名称" style="width: 140px" clearable
                filterable
                allow-create
                default-first-option
              >
                <el-option v-for="(item, index) in gifts" :key="index" :label="item" :value="item" />
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="head-card-element">
              <el-text class="mx-1">频道：</el-text>
              <el-select
                v-model="beanConsumeLive.liveChannel"
                placeholder="请选择频道"
                style="width: 150px"
                clearable
                filterable
                allow-create
                default-first-option
              >
                <el-option v-for="(item, index) in channels" :key="index" :label="item" :value="item" />
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="head-card-element">
              <el-text class="mx-1">直播间：</el-text>
              <el-input v-model="beanConsumeLive.liveName" placeholder="请输入直播间" style="width: 150px" clearable />
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <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="结束时间" style="width: 400px" @change="handleDatePickerChange" :default-time="defaultTime"/>
              <el-button @click="getToday()" style="margin-left: 10px"
                :type="activeTimeRange === 'today' ? 'primary' : ''"> 今</el-button>
              <el-button @click="getYesterday()" style="margin-left: 10px"
                :type="activeTimeRange === 'yesterday' ? 'primary' : ''"> 昨</el-button>
              <el-button @click="get7Days()" style="margin-left: 10px"
                :type="activeTimeRange === '7days' ? 'primary' : ''"> 近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>
              <el-button type="primary" @click="openExportList">查看导出列表</el-button>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </el-col>
  </el-row>
  <el-row>
    <el-col>
      <el-card>
        <div>
          金豆总数：{{ format3(Math.abs(permanentBean+freeBean)) }}&nbsp;&nbsp;&nbsp;&nbsp;
          付费金豆数：{{ format3(Math.abs(permanentBean)) }}&nbsp;&nbsp;&nbsp;&nbsp;
          免费金豆数：{{ format3(Math.abs(freeBean)) }}
        </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="80px" 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="dept" label="地区" width="110px" />
            <el-table-column prop="gift" label="礼物" width="140px" >
              
            </el-table-column>
            <el-table-column prop="beanNum" label="金豆数量" sortable="custom" width="120px"/>
            <el-table-column prop="isBackpack" label="背包礼物" width="120px">
              <template #default="scope"> 
                {{ scope.row.isBackpack == 1 ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column prop="buyBean" label="付费金豆数" sortable="custom" width="120px"/>
            <el-table-column prop="freeBean" label="免费金豆数" sortable="custom" width="120px"/>
            <el-table-column prop="liveChannel" label="频道" width="180px" />
            <el-table-column prop="liveName" label="直播间名称" width="160px" show-overflow-tooltip />
            <el-table-column prop="consumeTime" 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>

  <!-- 导出弹窗 -->
  <el-dialog v-model="exportListVisible" title="导出列表" width="80%">
        <el-table :data="exportList" style="width: 100% ;height: 60vh;" :loading="exportListLoading">
      <el-table-column prop="fileName" label="文件名" />
      <el-table-column prop="state" label="状态">
        <template #default="scope">
          <el-tag :type="getTagType(scope.row.state)" :effect="scope.row.state === 3 ? 'light' : 'plain'">
            {{ getTagText(scope.row.state) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间">
        <template #default="scope">
          {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="downloadExportFile(scope.row)"
            :disabled="scope.row.state !== 2">
            下载
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button text @click="exportListVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</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>
