
<script setup>
import { ref, onMounted, computed ,nextTick} from 'vue'

import { ElMessage } from 'element-plus'
import axios from 'axios'
import moment from 'moment'
import API from '@/util/http'
import { writeFile, utils } from 'xlsx'

// 变量
const adminData = ref({})
const getAdminData = async function () {
  try {
    const result = await API({
      url: '/admin/userinfo',
      method: 'post',
      data: {}
    })
    adminData.value = result
    console.log('请求成功', result)
    console.log('用户信息', adminData.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}

// 定义加载状态
const isLoadingArea = ref(false);
const area = ref([])
const getArea = async () => {
  isLoadingArea.value = true;
  try {
    const result = await API({
      url: '/detailY/getarea'
    });
    // 假设后端返回的是字符串数组，转换为 { value, label } 格式
    if (Array.isArray(result.data) && typeof result.data[0] === 'string') {
      area.value = result.data.map(item => ({ value: item, label: item }));
    } else {
      area.value = result.data;
    }
  } catch (error) {
    console.error('获取地区数据失败:', error);
    ElMessage.error('获取地区数据失败，请稍后重试');
    // 可以提供默认数据
    area.value = []; 
  } finally {
    isLoadingArea.value = false;
  }
};

// 充值明细表格
const tableData = ref([])
// 各金币总数
const rechargeCoin = ref(0)
const freeCoin = ref(0)
const taskCoin = ref(0)
// 搜索===========================================
//分页总条目
const total = ref(100)
// 搜索对象时间
const getTime = ref([])
// 搜索detailY
const detailY = ref({})
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 50
})
// 开启条件筛选导出excel
const getPutEX = ref(false)

// 支付方式选项
const num = [
  {
    value: '1',
    label: '增加'
  },
  {
    value: '2',
    label: '减少'
  }
]


// 方法
// 搜索===========================================================================
// 搜索方法
const get = async function (val) {
  try {
    // 地区赋值
    if (adminData.value.area === '泰国') {
      detailY.value.areas = ['泰国', '越南']
    } else if (adminData.value.area !== '总部') {
      detailY.value.area = adminData.value.area
    }
    // 搜索参数页码赋值
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }
    if (getTime.value.length === 2) {
      detailY.value.startDate = getTime.value[0]
      detailY.value.endDate = getTime.value[1]
    } else {
      detailY.value.startDate = ''
      detailY.value.endDate = ''
    }
    // 添加排序字段和排序方式到请求参数
    detailY.value.sortField = sortField.value
    detailY.value.sortOrder = sortOrder.value
    console.log('搜索参数', getObj.value)
    // 发送POST请求
    const result = await API({
      url: '/detailY',
      method: 'post',
      data: { ...getObj.value, detailY: { ...detailY.value } }
    })
    tableData.value = result.data.list
    total.value = result.data.total
  } catch (error) {
    console.log('请求失败', error)
  }
}
// 精网号去空格，处理 detailY 中的 jwcode
const trimJwCode = () => {
  if (detailY.value.jwcode) {
    detailY.value.jwcode = detailY.value.jwcode.replace(/\s/g, ''); 
  }
}

// 搜索
const search = function () {
  trimJwCode();
  getObj.value.pageNum = 1
  get()
}

// 重置
const reset = function () {
  delete detailY.value.jwcode
  delete detailY.value.num
  delete detailY.value.startDate
  delete detailY.value.endDate
  delete detailY.value.area
  delete sortField.value
  delete sortOrder.value
  getTime.value = []
  delete detailY.value.consumePlatform
}
// 今天
const getToday = function () {
  const today = moment()
  const startDate = today.startOf('day').toDate()
  const endDate = today.endOf('day').toDate()
  getTime.value = [startDate, endDate]
  search()
}

// 昨天
const getYesterday = function () {
  const yesterday = moment().subtract(1, 'day')
  const startDate = yesterday.startOf('day').toDate()
  const endDate = yesterday.endOf('day').toDate()
  getTime.value = [startDate, endDate]
  search()
}

// 近7天
const get7Days = function () {
  const startDate = moment().subtract(6, 'day').startOf('day').toDate()
  const endDate = moment().endOf('day').toDate()
  getTime.value = [startDate, endDate]
  search()
}

// 验证跳转输入框的数字是否合法
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 getArea()
  await getAdminData()
  await get()
})

// 导出Excel的方法
const headers = [
  '序号',
  '姓名',
  '精网号',
  '所属地区',
  '平台信息',
  '更新数量',
  '更新类型',
  '永久金币',
  '免费金币',
  '任务金币',
  '提交人',
  '更新时间'
]

const showExportInfoPanel = ref(false)

// 点击导出按钮直接显示信息面板
const exportExcel = async () => {
  try {
    console.log('点击导出按钮，尝试显示信息面板');
    showExportInfoPanel.value = true;
    await nextTick();//组件更新显示信息面板
  } catch (error) {
    console.error('显示信息面板失败:', error);
    ElMessage.error('显示信息面板失败，请稍后重试');
  }
};

// 新增导出状态相关变量
const exportProgress = ref(0)
const isExporting = ref(false)
const exportCancelToken = ref(null)

// 优化后的导出方法
const doExportExcel = async () => {
  try {
    isExporting.value = true
    exportProgress.value = 0
    showExportInfoPanel.value = false

    // 初始化Excel
    const wb = utils.book_new()
    const ws = utils.aoa_to_sheet([headers])
    utils.book_append_sheet(wb, ws, 'Sheet1')

    // 流式写入配置
    const writer = {
      write: (d, o) => {
        if (!d) return
        utils.sheet_add_aoa(ws, d, { origin: -1 })
      }
    }

    let page = 1
    let totalExported = 0
    const pageSize = 5000 // 每次请求5000条
    let totalRecords = 0

    // 首次请求获取总记录数
    const firstResult = await API({
      url: '/detailY',
      method: 'post',
      data: { 
        pageNum: 1,
        pageSize,
        detailY: { ...detailY.value }
      }
    })
    totalRecords = firstResult.data.total

    // 创建取消令牌
    const CancelToken = axios.CancelToken
    exportCancelToken.value = CancelToken.source()

    // 平台信息映射
    const platformMap = {
      0: '初始化金币',
      1: 'ERP系统',
      2: 'Homily Chart',
      3: 'Homily Link',
      4: '金币系统'
    };
    // 更新类型映射
    const updateTypeMap = {
      0: '充值',
      1: '消费',
      2: '退款',
      3: '其他'
    };

    // 处理首次请求的数据
    const firstData = firstResult.data.list
    if (firstData.length) {
      const rows = firstData.map((row, index) => [
        totalExported + index + 1,
        row.username || '',
        row.jwcode || '',
        row.area || '',
        platformMap[row.consumePlatform] || '',
        (row.gold).toFixed(2) || '0.00',
        updateTypeMap[row.updateType] || '',
        (row.rechargeCoin / 100).toFixed(2) || '0.00',
        (row.freeCoin / 100).toFixed(2) || '0.00',
        (row.taskCoin / 100).toFixed(2) || '0.00',
        row.name || '',
        moment(row.createTime).format('YYYY-MM-DD HH:mm:ss') || ''
      ])
      writer.write(rows)
      totalExported += firstData.length
      exportProgress.value = Math.round((totalExported / totalRecords) * 100)
      page++
    }

    while (totalExported < totalRecords) {
      const result = await API({
        url: '/detailY',
        method: 'post',
        data: { 
          pageNum: page,
          pageSize,
          detailY: { ...detailY.value }
        },
        cancelToken: exportCancelToken.value.token
      })

      const data = result.data.list
      if (!data.length) break

      // 转换数据
      const rows = data.map((row, index) => [
        totalExported + index + 1,
        row.username || '',
        row.jwcode || '',
        row.area || '',
        platformMap[row.consumePlatform] || '',
        (row.gold / 100).toFixed(2) || '0.00',
        updateTypeMap[row.updateType] || '',
        (row.rechargeCoin / 100).toFixed(2) || '0.00',
        (row.freeCoin / 100).toFixed(2) || '0.00',
        (row.taskCoin / 100).toFixed(2) || '0.00',
        row.name || '',
        moment(row.createTime).format('YYYY-MM-DD HH:mm:ss') || ''
      ])

      // 流式写入
      writer.write(rows)
      totalExported += data.length
      exportProgress.value = Math.round((totalExported / totalRecords) * 100)

      // 内存控制：每500页释放内存
      if (page % 500 === 0) {
        await new Promise(resolve => setTimeout(resolve, 0))
      }

      page++
    }

    // 生成最终文件
    writeFile(wb, '客户金币明细.xlsx')
    ElMessage.success(`导出成功，共${totalExported}条数据`)
  } catch (error) {
    if (!axios.isCancel(error)) {
      ElMessage.error(`导出失败: ${error.message}`)
    }
  } finally {
    isExporting.value = false
    exportCancelToken.value = null
  }
}

// 新增取消导出方法
const cancelExport = () => {
  if (exportCancelToken.value) {
    exportCancelToken.value.cancel('用户取消导出')
    ElMessage.warning('导出已取消')
    isExporting.value = false
  }
}

const putExcel = ref({
  startDate: new Date(),
  endDate: new Date(new Date().setDate(new Date().getDate() + 1))
})

// 新增校验精网号的方法
const checkJwCode = async (jwcode) => {
  try {
    const result = await API({
      url: '/recharge/user',
      method: 'post',
      data: {
        jwcode,
        area: adminData.value.area
      }
    })
    // 根据后端返回的 code 判断精网号是否存在
    return result.code !== 0 
  } catch (error) {
    console.log('校验精网号失败', error)
    return false
  }
}

// 选消费平台
const platform = [
  {
    value: '4',
    label: '金币系统'
  },
  {
    value: '1',
    label: 'ERP系统'
  },
  {
    value: '2',
    label: 'Homily Chart'
  },
  {
    value: '3',
    label: 'Homily Link'
  },
  {
    value: '0',
    label: '初始化金币'
  }
]

// 新增排序字段和排序方式
const sortField = ref('')
const sortOrder = ref('')
// 处理排序事件
const handleSortChange = (column) => {
  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 === 'gold') {
    sortField.value = 'gold'
  }
  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>
  <!-- 导出excel提前展示的信息面板 -->
  <el-dialog
    v-model="showExportInfoPanel"
    title="导出信息确认"
    width="400px"
    :close-on-click-modal="false"
  >
    <div class="info-panel-header">导出信息</div>
    <!-- 直接使用 detailY 显示信息，添加可选链操作符 -->
    <!-- detailY是一个ref，所以在模板中应该直接使用detailY.consumePlatform，
     而不是detailY.value.consumePlatform。
     因为在模板中，ref变量会自动解包，不需要.value。
     例如，在代码中，我们可能错误地在模板中使用了detailY.value，但实际上应该直接使用detailY。 -->
    <div v-if="!detailY.jwcode && !detailY.consumePlatform && !detailY.num && !detailY.area && (getTime.length < 2)">
      你正在导出所有数据
    </div>
    <div v-else>
      你正在导出以下数据
    </div>
    <div v-if="detailY.jwcode">精网号：{{ detailY.jwcode || '' }}</div>
    <div v-if="detailY.consumePlatform">平台信息：{{ detailY.consumePlatform ? (platform.find(item => item.value === detailY.consumePlatform)?.label) : '' }}</div>
    <div v-if="detailY.num">数量更新类型：{{ detailY.num ? (num.find(item => item.value === detailY.num)?.label || '') : '' }}</div>
    <div v-if="detailY.area">所属地区：{{ detailY.area || '' }}</div>
    <div v-if="Array.isArray(getTime) && getTime.length >= 2">
      <span>更新时间：</span>
      <!-- 直接使用 getTime 而非 getTime.value -->
      <span v-if="Array.isArray(getTime) && getTime.length >= 2">
        {{ moment(getTime[0]).format('YYYY-MM-DD') }} 至 {{ moment(getTime[1]).format('YYYY-MM-DD') }}
      </span>
      <span v-else></span>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showExportInfoPanel = false">取消</el-button>
        <el-button type="primary" @click="doExportExcel">导出</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 导出进度弹窗 -->
  <el-dialog
    v-model="isExporting"
    title="正在导出"
    width="400px"
    :close-on-click-modal="false"
    :show-close="false"
  >
    <el-progress 
      :percentage="exportProgress" 
      :stroke-width="15"
      striped
      animated
    />
    <div class="export-status">
      已导出 {{ Math.round((exportProgress / 100) * total) }} 条 / 共 {{ total }} 条
    </div>
    <template #footer>
      <el-button type="danger" @click="cancelExport">取消导出</el-button>
    </template>
  </el-dialog>

  <el-row>
    <el-col>
      <el-card style="margin-bottom: 20px">
        <el-row style="margin-bottom: 10px">
          <el-col :span="6">
            <div class="head-card-element">
              <el-text class="mx-1" size="large">精网号：</el-text>
              <el-input
                v-model="detailY.jwcode"
                style="width: 240px"
                placeholder="请输入精网号"
                clearable
              />
            </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="detailY.consumePlatform"
                placeholder="请选择平台信息"
                style="width: 200px"
                clearable
              >
                <el-option
                  v-for="item in platform"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </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="detailY.num"
                placeholder="请选择更新类型"
                style="width: 200px"
                clearable
              >
                <el-option
                  v-for="item in num"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </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="detailY.area"
                placeholder="请选择所属地区"
                style="width: 240px"
                clearable
                :loading="isLoadingArea"
              >
                <el-option
                  v-for="item in area"
                  :key="item.value || item"
                  :label="item.label || item"
                  :value="item.value || item"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>

        <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="结束时间"
            style="margin-right: 10px"
          />
          <el-button type="success" @click="getToday()">今</el-button>
          <el-button type="success" @click="getYesterday()">昨</el-button>
          <el-button type="success" @click="get7Days()">近7天</el-button>
          <el-button type="success" @click="exportExcel">导出Excel表格</el-button>
          <el-button type="success" @click="reset()">重置</el-button>
          <el-button type="primary" @click="search()">查询</el-button>
        </div>
      </el-card>
    </el-col>
  </el-row>
  <el-row>
    <el-col>
      <el-card>
        <div style="height: 584px; overflow-y: auto">
          <el-table
            :data="tableData"
            style="width: 100%"
            @sort-change="handleSortChange"
            height="584px"
          >
            <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
              fixed="left"
              prop="username"
              label="姓名"
              width="150"
            />
            <el-table-column
              fixed="left"
              prop="jwcode"
              label="精网号"
              width="120"
            />
            <el-table-column prop="area" label="所属地区" width="120" />
            <el-table-column
              prop="consumePlatform"
              label="平台信息"
              width="140"
            >
              <template #default="scope">
                <!-- 使用非严格相等比较 -->
                <span v-if="scope.row.consumePlatform == 0">初始化金币</span>
                <span v-if="scope.row.consumePlatform == 1">ERP系统</span>
                <span v-if="scope.row.consumePlatform == 3">Homily Link</span>
                <span v-if="scope.row.consumePlatform == 2">Homily Chart</span>
                <span v-if="scope.row.consumePlatform == 4">金币系统</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="gold"
              label="更新数量"
              width="120"
              sortable="custom"
            >
              <template #default="scope">
                <span>{{ scope.row.gold / 100 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="updateType" label="更新类型" width="110">
              <!-- 模板内容 -->
              <template #default="scope">
                <span v-if="scope.row.updateType == 1">消费</span>
                <span v-if="scope.row.updateType == 0">充值</span>
                <span v-if="scope.row.updateType == 2">退款</span>
                <span v-if="scope.row.updateType == 3">其他</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="rechargeCoin"
              sortable="custom"
              label="永久金币"
              width="110"
            >
              <template #default="scope">
                <span>{{ scope.row.rechargeCoin / 100 }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="freeCoin"
              sortable="custom"
              label="免费金币"
              width="110"
            >
              <template #default="scope">
                <span>{{ scope.row.freeCoin / 100 }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="taskCoin"
              sortable="custom"
              label="任务金币"
              width="110"
            >
              <template #default="scope">
                <span>{{ scope.row.taskCoin / 100 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="提交人" width="110" />
            <el-table-column
              prop="createTime"
              sortable="custom"
              label="更新时间"
              width="210"
              show-overflow-tooltip
            >
              <template #default="scope">
                <span>{{
                  moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss')
                }}</span>
              </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>
.pagination {
  display: flex;
}

.status {
  display: flex;
}

.head-card {
  display: flex;
}

.info-panel-header {
  font-weight: bold;
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.export-status {
  margin-top: 15px;
  text-align: center;
  color: #666;
}

.el-progress-bar__inner {
  transition: width 0.5s ease;
}

</style>
