<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { dayjs, ElMessage } from 'element-plus'
import request from '@/util/http.js'
import API from '@/util/http.js'
import moment from 'moment'
import { useAdminStore } from "@/store/index.js";
import { storeToRefs } from "pinia";
const adminStore = useAdminStore();
const { flag } = storeToRefs(adminStore);
// 监听全局flag状态变化
 watch(flag, (newFlag, oldFlag) => {
  // 当flag状态改变时，重新发送请求
  if (newFlag !== oldFlag) {
    ConsumeSelectBy()
  }
})

// 之后整理一下

/*
====================工具方法==============================
*/
const format3 = (num) => {
  // 每三位添加逗号
  return num.toLocaleString('en-US')
}
// 时间格式化
const formatTime = (val) => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : ''
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
]
/*
====================数据=================================
*/
//这是获取用户信息的接口
const adminData = ref({})
// 充值明细表格
const tableData = ref([])

// 搜索beanConsumeFan 表单
const beanConsumeFan = ref({
  jwcode: null,
  dept: "",
  type: "",
  gift: "",
  channel: "",
  liveRoom: "",
  startTime: '',
  endTime: '',

})
// 频道列表
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 filterChannel = (query) => {
//   if (query) {
//     return channels.value.filter(item => item.toLowerCase().includes(query.toLowerCase()));
//   }
//   return channels.value;
// };

// 抽离类型选项到响应式数组
const consumeTypes = ref([
  { label: '发礼物', value: 1 },
  { label: '发红包', value: 2 },
  { label: '发福袋', value: 3 },
  { label: '付费直播', value: 4 },
  { label: '加入粉丝团', value: 5 },
  { label: '发弹幕', value: 6 },
  { label: '单次付费', value: 7 },
  { label: '连续包月', value: 8 }
])

// // 处理类型选择变化
// const handleTypeChange = (value) => {
//   if (value !==  1) {
//     beanConsumeFan.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 activity = ref([])

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


// 新增排序字段和排序方式
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 ConsumeSelectBy = async function (val) {
  try {

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

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

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

    // 发送POST请求
    const result = await request({
      url: '/beanConsume/selectFanBy',
      data: {
        pageNum: getObj.value.pageNum,
        pageSize: getObj.value.pageSize,
        beanConsumeFan: {
          ...beanConsumeFan.value,
          jwcode: beanConsumeFan.value.jwcode ? String(beanConsumeFan.value.jwcode) : '',
          dept: beanConsumeFan.value.dept || '',
          channel: beanConsumeFan.value.channel || '',
          startTime: beanConsumeFan.value.startTime || '',
          endTime: beanConsumeFan.value.endTime || '',
          sortField: beanConsumeFan.value.sortField || 'consumeTime',
          sortOrder: beanConsumeFan.value.sortOrder || 'desc',
          flag: flag.value,
          roleId: adminData.value.roleId
        }
      }
    })

    console.log('请求成功3', sortField)
    console.log('接口响应结果', result);
    if (result.code === 200 && result.data && result.data.list) {
      tableData.value = result.data.list;
      total.value = result.data.total;
    }

    // 合计数的接口
    // 复制一份 beanConsumeFan.value 并设置固定的 payType 值 1是直播 7是铁粉
    const sumConsumeParams = {
      payType: 7, // 固定传入 payType 值 7
      beanConsumeFan: {
        ...beanConsumeFan.value,
        flag: flag.value 
      }
    };
    // 发送 POST 请求获取合计数
    const resultTotalGold = await request({
      url: '/beanConsume/sumConsumeGold',
      data: sumConsumeParams
    });

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

    const data = resultTotalGold.data || resultTotalGold;
    console.log('请求成功2', resultTotalGold.data)
    console.log('permanentBean2', 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 (beanConsumeFan.value.jwcode) {
    const numRef = /^\d{1,9}$/;
    if (!numRef.test(beanConsumeFan.value.jwcode)) {
      ElMessage.error('请检查精网号格式')
      return
    }
  }
  ConsumeSelectBy()
}
// 重置
const reset = function () {
  console.log('兄弟，你点了重置')

  beanConsumeFan.value.jwcode = null

  beanConsumeFan.value.type = ''
  beanConsumeFan.value.gift = ''
  beanConsumeFan.value.channel = ''
  beanConsumeFan.value.liveRoom = ''

  beanConsumeFan.value.dept = ''

  beanConsumeFan.value.startTime = ''

  beanConsumeFan.value.endTime = ''


  sortField.value = ''
  sortOrder.value = ''
  getTime.value = {}
  activeTimeRange.value = '' // 清除激活状态

  // 重置页码
  getObj.value.pageNum = 1

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

  ConsumeSelectBy()
}
// 昨天
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' // 标记当前激活状态
  console.log('昨', getTime.value)
  ConsumeSelectBy()
}
// 近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' // 标记当前激活状态

  ConsumeSelectBy()
}


// 获取地区列表的方法
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 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'
  ConsumeSelectBy()
}

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

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

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

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

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


onMounted(async function () {
  await getAdminData()
  await ConsumeSelectBy()
  await getChannel()
  await getDept()

})


const exportExcel = async function () {
  const params = { //需要修改
    ...getObj.value,
    "beanConsumeFan": {
      ...beanConsumeFan.value,
      sortField: sortField.value,
      sortOrder: sortOrder.value,
      flag: flag.value,
      roleId: adminData.value.roleId

    },
  }
  const res = await API({ url: '/export/exportFan', data: params })
  if (res.code === 200) {
    ElMessage.success('导出成功')
  }
}
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 === 7; //7是铁粉
      });
      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-card class="card1" style="margin-bottom: 0.5vh;">
    <el-col style="margin-bottom: 1vh">
      <div class="select">
        <div class="selectRow">
          <el-text class="text">精网号：</el-text>
          <el-input class="selectContent" v-model="beanConsumeFan.jwcode" placeholder="请输入精网号" clearable />
        </div>
        <div class="selectRow">
          <el-text class="text">地区：</el-text>
          <el-select class="selectContent" v-model="beanConsumeFan.dept" placeholder="请选择地区" clearable>
            <el-option v-for="(item, index) in dept" :key="index" :label="item" :value="item" />
          </el-select>
        </div>
        <div class="selectRow">
          <el-text class="text">频道：</el-text>
          <el-select class="selectContent" v-model="beanConsumeFan.channel" placeholder="请选择频道" clearable filterable>
            <el-option v-for="(item, index) in channels" :key="index" :label="item" :value="item" />
          </el-select>
        </div>
      </div>
    </el-col>
    <el-col>
      <div class="select">
        <div class="selectRow" style="width: 36vw;">
          <el-text class="text" size="large">消费时间：</el-text>
          <el-date-picker class="selectContent" v-model="getTime" type="datetimerange" range-separator="至"
            start-placeholder="起始时间" end-placeholder="结束时间" style="margin-right:1vw;width:25vw"
            @change="handleDatePickerChange" value-format="YYYY-MM-DD HH:mm:ss" :default-time="defaultTime" />
          <div v-if="false">
            <el-button @click="getToday()" :type="activeTimeRange === 'today' ? 'primary' : ''">今</el-button>
            <el-button @click="getYesterday()" :type="activeTimeRange === 'yesterday' ? 'primary' : ''">昨</el-button>
            <el-button @click="get7Days()" :type="activeTimeRange === '7days' ? 'primary' : ''">近7天</el-button>
          </div>
        </div>
        <div class="selectRow" style="justify-content: flex-start;">
          <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>
          <el-button type="success" @click="reset()">重置</el-button>
        </div>
      </div>
    </el-col>
  </el-card>
  <el-card class="card2">
    <div class="goldStatistics">
      金豆总数：{{ format3(Math.abs(permanentBean + freeBean)) }}&nbsp;&nbsp;&nbsp;&nbsp;
      付费金豆数：{{ format3(Math.abs(permanentBean)) }}&nbsp;&nbsp;&nbsp;&nbsp;
      免费金豆数：{{ format3(Math.abs(freeBean)) }}
    </div>
    <div style="overflow-y: auto">
      <el-table :data="tableData" style="width: 82vw" height="69vh" @sort-change="handleSortChange"
      :row-style="{ height: '50px' }">
        <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" show-overflow-tooltip />
        <!-- 固定精网号列 -->
        <el-table-column prop="jwcode" label="精网号" width="110px" fixed="left" />
        <el-table-column prop="dept" label="地区" width="110px" />
        <el-table-column prop="beanNum" label="金豆数量" sortable="custom" width="120px" />
        <el-table-column prop="buyBean" label="付费金豆数" sortable="custom" width="120px" />
        <el-table-column prop="freeBean" label="免费金豆数" sortable="custom" width="120px" />
        <el-table-column prop="channel" label="频道" width="190px" show-overflow-tooltip />
        <el-table-column prop="type" label="会员类型" width="120px">
          <template #default="scope">
            {{consumeTypes.find(item => item.value === Number(scope.row.type))?.label || '未知类型'}}
          </template>
        </el-table-column>
        <el-table-column prop="consumeTime" label="加入时间" sortable="custom" width="180px" />
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination background :current-page="getObj.pageNum" :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-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 lang="scss">
// 搜索的卡片样式
.card1 {
  background: #F3FAFE;
}

// 表单的卡片样式
.card2 {
  background: #E7F4FD;
}

// 新币总数等等
.goldStatistics {
  margin-left: 1vw;
  margin-bottom: 1vh;
  color: #000000;
  font-family: "PingFang SC";
  font-size: 16px;
  font-style: normal;
  font-weight: 700;
  line-height: 20px;
}

// 表头背景等
:deep(.el-table__header-wrapper),
:deep(.el-table__body-wrapper),
:deep(.el-table__cell),
/* 表格 */
:deep(.el-table__body td) {
  background-color: #F3FAFE !important;
}

/* 表头 */
:deep(.el-table__header th) {
  background-color: #F3FAFE !important;
}

/* 鼠标悬停 */
:deep(.el-table__row:hover > .el-table__cell) {
  background-color: #E5EBFE !important;
}

.pagination {
  display: flex;
  margin-top: 20px;
}


/** 搜索的样式 */
.select {
  display: flex;

  .selectRow {
    width: 17vw;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 0.5vw;

    .text {
      width: 5vw;
      font-size: 15px;
    }

    .selectContent {
      flex: 1;
    }
  }
}
</style>
