<script setup>
import {computed, onMounted, ref, watch, nextTick} 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";
// 国际化
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const adminStore = useAdminStore();
const {flag} = storeToRefs(adminStore);

// 监听全局flag状态变化
watch(flag, (newFlag, oldFlag) => {
  // 当flag状态改变时，重新发送请求
  if (newFlag !== oldFlag) {
    selectLiveBy()
  }
})

// 之后整理一下

/*
====================工具方法==============================
*/
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([])
const tableRef = ref(null)
const scrollTableTop = () => {
  tableRef.value?.setScrollTop?.(0)
}

// 搜索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: t('elmessage.getGiftListFailed')
    })
  }
}

// 频道列表
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: t('elmessage.getChannelListFailed')
    })
  }
}

// 抽离类型选项到响应式数组
const consumeTypes = ref([
  {label: t('consume.consumeTypes.1'), value: 1},
  {label: t('consume.consumeTypes.2'), value: 2},
  {label: t('consume.consumeTypes.3'), value: 3},
  {label: t('consume.consumeTypes.4'), value: 4},
  {label: t('consume.consumeTypes.5'), value: 5},
  {label: t('consume.consumeTypes.6'), 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: t('elmessage.getRegionListFailed')
    })
  }
}

// 新增排序字段和排序方式
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',
          flag: flag.value,
          roleId: adminData.value.roleId
        }
      }
    })

    console.log('请求成功2', sortField)
    console.log('接口响应结果', result); // 打印接口响应结果
    if (result.code === 200 && result.data && result.data.list) {
      tableData.value = result.data.list;
      await nextTick()
      scrollTableTop()
      total.value = result.data.total;
    }
    // 复制一份 beanConsumeLive.value 并设置固定的 payType 值 1是直播
    const sumConsumeParams = {
      payType: 1, // 固定传入 payType 值 1 是直播
      beanConsumeLive: {
        ...beanConsumeLive.value,
        roleId: adminData.value.roleId,
        flag: flag.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(t('elmessage.checkJwcodeFormat'))
      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 = '' // 清除激活状态

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

  // 点完重置后，重新请求数据
  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',
      roleId: adminData.value.roleId,
      flag: flag.value,


    }
  }
  // 打印请求参数，方便调试
  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(t('elmessage.exportSuccess'));
    } else {
      ElMessage.error(res.message || t('elmessage.exportFailed'));
    }
  } catch (error) {
    console.error('导出请求出错:', error);
    ElMessage.error(t('elmessage.exportFailed'));
  }
}
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; //6是直播
      });
      exportList.value = filteredData
    } else {
      ElMessage.error(result.msg || t('elmessage.getExportListError'))
    }
  } catch (error) {
    console.error('获取导出列表出错:', error)
    ElMessage.error(t('elmessage.getExportListError'))
  } 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(t('elmessage.exportingInProgress'))
  }
}
//根据状态返回对应的标签类型
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 t('elmessage.pendingExecution');
    case 1:
      return t('elmessage.executing');
    case 2:
      return t('elmessage.executed');
    case 3:
      return t('elmessage.errorExecution');
    default:
      return t('elmessage.unknownStatus');
  }
}
</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">{{ t('common.jwcode') }}：</el-text>
          <el-input class="selectContent" v-model="beanConsumeLive.jwcode" :placeholder="t('common.jwcodePlaceholder')" clearable/>
        </div>
        <div class="selectRow">
          <el-text class="text">{{ t('common.market') }}：</el-text>
          <el-select class="selectContent" v-model="beanConsumeLive.dept" :placeholder="t('common.marketPlaceholder')" clearable>
            <el-option v-for="(item, index) in dept" :key="index" :label="item" :value="item"/>
          </el-select>
        </div>
        <div class="selectRow" style="width: 14vw;">
          <el-text class="text">{{ t('common.giftName') }}：</el-text>
          <el-select class="selectContent" v-model="beanConsumeLive.gift" :placeholder="t('common.giftNamePlaceholder')" clearable
                     filterable
                     allow-create default-first-option>
            <el-option v-for="(item, index) in gifts" :key="index" :label="item" :value="item"/>
          </el-select>
        </div>
        <div class="selectRow" style="min-width: 12vw;">
          <el-text class="textB" size="large">{{ t('common.channel') }}：</el-text>
          <el-select class="selectContent" v-model="beanConsumeLive.liveChannel" :placeholder="t('common.channelPlaceholder')" clearable
                     filterable allow-create default-first-option>
            <el-option v-for="(item, index) in channels" :key="index" :label="item" :value="item"/>
          </el-select>
        </div>
        <div class="selectRow" style="min-width: 12vw;">
          <el-text class="textB" size="large">{{ t('common.liveRoom') }}：</el-text>
          <el-input class="selectContent" v-model="beanConsumeLive.liveName" :placeholder="t('common.liveRoomPlaceholder')" clearable/>
        </div>
      </div>
    </el-col>
    <el-col>
      <div class="select">
        <div class="selectRow" style="width: 35.4vw;">
          <el-text class="text">{{ t('common.consumetime') }}：</el-text>
          <el-date-picker class="selectContent" v-model="getTime" type="datetimerange" :range-separator="t('common.to')"
                          :start-placeholder="t('common.startTime')" :end-placeholder="t('common.endTime')" style="margin-right:1vw;width:480px"
                          @change="handleDatePickerChange" :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()">{{ t('common.search') }}</el-button>
          <el-button type="primary" @click="exportExcel()">{{ t('common.exportExcel') }}</el-button>
          <el-button type="primary" @click="openExportList">{{ t('common.viewExportList') }}</el-button>
          <el-button type="success" @click="reset()">{{ t('common.reset') }}</el-button>
        </div>
      </div>
    </el-col>
  </el-card>
  <el-card class="card2">
    <div class="goldStatistics">
      {{ t('common.totalGoldBean') }}{{ format3(Math.abs(permanentBean + freeBean)) }}&nbsp;&nbsp;&nbsp;&nbsp;
      {{ t('common.payGoldBean') }}{{ format3(Math.abs(permanentBean)) }}&nbsp;&nbsp;&nbsp;&nbsp;
      {{ t('common.freeGoldBean') }}{{ format3(Math.abs(freeBean)) }}
    </div>
    <div style="overflow-y: auto">
      <el-table ref="tableRef" :data="tableData" style="width: 82vw" height="65vh" @sort-change="handleSortChange"
                :row-style="{ height: '50px' }">
        <el-table-column type="index" :label="t('common_list.id')" 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="t('common_list.name')" width="150px" fixed="left" show-overflow-tooltip/>
        <!-- 固定精网号列 -->
        <el-table-column prop="jwcode" :label="t('common_list.jwcode')" width="110px" fixed="left"/>
        <el-table-column prop="dept" :label="t('common_list.market')" width="120px"/>
        <el-table-column prop="gift" :label="t('common_list.gift')" width="150px">
        </el-table-column>
        <el-table-column prop="beanNum" :label="t('common_list.beanNum')" sortable="custom" width="120px"/>
        <el-table-column prop="isBackpack" :label="t('common_list.isBackpack')" width="120px">
          <template #default="scope">
            {{ scope.row.isBackpack == 1 ? t('common_list.yes') : t('common_list.no') }}
          </template>
        </el-table-column>
        <el-table-column prop="buyBean" :label="t('common_list.permanentBean')" sortable="custom" width="170px"/>
        <el-table-column prop="freeBean" :label="t('common_list.freeBean')" sortable="custom" width="130px"/>
        <el-table-column prop="liveChannel" :label="t('common_list.channel')" width="120px" show-overflow-tooltip/>
        <el-table-column prop="liveName" :label="t('common_list.liveRoomName')" width="160px" show-overflow-tooltip/>
        <el-table-column prop="consumeTime" :label="t('common_list.consumetime')" sortable="custom" width="190px"/>
      </el-table>
    </div>
    <el-pagination background :current-page="getObj.pageNum" :page-size="getObj.pageSize"
                   :page-sizes="[5, 10, 20, 50, 100]" style="margin-top: 20px;"
                   layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handlePageSizeChange"
                   @current-change="handleCurrentChange"></el-pagination>
  </el-card>

  <!-- 导出弹窗 -->
  <el-dialog v-model="exportListVisible" :title="t('common_export.exportList')" width="80%">
    <el-table :data="exportList" style="width: 100% ;height: 60vh;" :loading="exportListLoading">
      <el-table-column prop="fileName" :label="t('common_export.fileName')"/>
      <el-table-column prop="state" :label="t('common_export.status')">
        <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="t('common_export.createTime')">
        <template #default="scope">
          {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column :label="t('common_export.operation')">
        <template #default="scope">
          <el-button type="primary" size="small" @click="downloadExportFile(scope.row)"
                     :disabled="scope.row.state !== 2">
            {{ t('common_export.download') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button text @click="exportListVisible = false">{{ t('common_export.close') }}</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: 14.7vw;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 0.5vw;

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

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