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

import {ElMessage} from 'element-plus'
import moment from 'moment'
import API from '@/util/http.js'
import {reverseMarketMapping} from "../../../utils/marketMap.js";
import dayjs from "dayjs";
import { useAdminStore } from "@/store/index.js"
import { storeToRefs } from "pinia"
import { findMenuById, permissionMapping } from "@/utils/menuTreePermission.js"
const adminStore = useAdminStore()
const { adminData, menuTree } = storeToRefs(adminStore)
//新增复选框员工数据
const showEmployeeData = ref(false)


// 标记当前激活的时间范围按钮
const activeTimeRange = ref('')
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
]
// 日期选择器变化时清除按钮激活状态
const handleDatePickerChange = () => {
  activeTimeRange.value = ''
}

// 定义ref 变量来存储合计数据
const totalPermanentGold = ref(0)
const totalFreeGold = ref(0)
const totalTaskGold = ref(0)
const totalGoldTotal = ref(0)

// 变量
// 精网号去空格，处理 goldDetail 中的 jwcode
const trimJwCode = () => {
  if (goldDetail.value.jwcode) {
    goldDetail.value.jwcode = goldDetail.value.jwcode.replace(/\s/g, '');
  }
}


//定义平台信息的加载状态
const isLoadingPlatform = ref(false)
// 平台信息
const platform = ref([])
//获取平台信息的函数
const getPlatform = async () => {
  isLoadingPlatform.value = true;
  try {
    const result = await API({
      url: '/general/platform',
      method: 'post',
    })
    if (Array.isArray(result.data)) {
      platform.value = result.data.map(item => ({value: item, label: item}));
    } else {
      console.error('平台信息格式错误', result)
      ElMessage.error('平台信息格式错误，请联系管理员')
    }

  } catch (error) {
    console.error('获取平台信息失败:', error);
    ElMessage.error('获取平台信息失败，请稍后重试');
  } finally {
    isLoadingPlatform.value = false
  }
}

// 数量更新类型选项
const type = [
  {
    value: '0',
    label: '充值'
  },
  {
    value: '1',
    label: '消耗'
  },
  {
    value: '2',
    label: '退款'
  }
]

// 定义加载状态，获取地区数据
// 定义加载状态，获取地区数据
const isLoadingmarket = ref(false);
const markets = ref([])


// 充值明细表格
const tableData = ref([])
// 各金币字段变量
// const sumGoldTotal = ref(0)
const permanentGold = ref(0)
//const freeGold = ref(0)
const taskGold = ref(0)
// 搜索===========================================
//分页总条目
const total = ref(100)
// 搜索对象时间
const getTime = ref([])
// 搜索goldDetail
const goldDetail = ref({
  markets: [],
})
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 50
})

// 开启条件筛选导出excel
// const getPutEX = ref(false)


// 方法
// 搜索===========================================================================
// 搜索方法
const get = async function (val) {
  if(!findMenuById(menuTree.value, permissionMapping.coinCustomerDetail)){
    ElMessage.error('无此权限')
    return
  }
  try {
    // 搜索参数页码赋值
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }
    if (getTime.value.length === 2) {//检查是否同时选择了开始时间和结束时间，如果不是则置空
      goldDetail.value.startTime = moment(getTime.value[0]).format('YYYY-MM-DD HH:mm:ss');
      goldDetail.value.endTime = moment(getTime.value[1]).format('YYYY-MM-DD HH:mm:ss');
    } else {
      goldDetail.value.startTime = ''
      goldDetail.value.endTime = ''
    }
    // 添加排序字段和排序方式到请求参数
    goldDetail.value.sortField = sortField.value
    goldDetail.value.sortOrder = sortOrder.value
    console.log('搜索参数', getObj.value)
    console.log('jwcode 类型:', typeof goldDetail.value.jwcode);
    console.log('jwcode 值:', goldDetail.value.jwcode);

    const requestData = {...getObj.value, goldDetail: {...goldDetail.value}};
    console.log('最终请求参数', JSON.stringify(requestData, null, 2)); // 打印格式化后的请求参数

    // 检查markets数组中是否包含'总部'或'研发部'
    console.log('goldDetail.value.markets:', goldDetail.value.markets)
    // if (goldDetail.value.markets.includes('9') || goldDetail.value.markets.includes('9999')) {
    //   goldDetail.value.markets = [];
    // }
    if (goldDetail.value.jwcode) {
      // 纯数字
      const numberRegex = /^\d{1,9}$/;

      // 检查是否不是数字
      if (!numberRegex.test(goldDetail.value.jwcode)) {
        ElMessage.error('请检查精网号格式')
        // 上面提示过了
        return
      }
    }
    const result = await API({
      url: '/goldDetail/getGoldDetail',
      method: 'post',
      data: {...getObj.value, goldDetail: {...goldDetail.value, flag: showEmployeeData.value ? 0 : 1}}
    })
    console.log('响应数据', result)
    tableData.value = result.data.list
    total.value = result.data.total
    const totalResult = await API({
      url: '/goldDetail/getTotal',
      method: 'post',
      data: {
        goldDetail: {...goldDetail.value, flag: showEmployeeData.value ? 0 : 1},
        /* jwcode: goldDetail.value.jwcode || '',
         payPlatform: goldDetail.value.payPlatform || '',
         type: goldDetail.value.type || '',
         market: goldDetail.value.market || '',
         startTime: goldDetail.value.startTime || '',
         endTime: goldDetail.value.endTime || ''*/
      }
    })

    if (totalResult.code === 200) {
      const data = totalResult.data
      totalPermanentGold.value = data.permanentGolds
      totalFreeGold.value = data.freeGolds
      totalTaskGold.value = data.taskGolds
      totalGoldTotal.value = data.sumGolds
    } else if (totalResult.code === 0) {
      // 将表格数据设置为空数组
      tableData.value = []
      totalPermanentGold.value = 0
      totalFreeGold.value = 0
      totalTaskGold.value = 0
      totalGoldTotal.value = 0
    } else {
      ElMessage.error('获取合计数据失败')
    }


  } catch (error) {
    console.log('请求失败', error)
  }
}


// 重置
const reset = function () {
  goldDetail.value = {}
  goldDetail.value.markets = []
  selectedMarketPath.value = []
  delete sortField.value
  delete sortOrder.value
  getTime.value = []
  activeTimeRange.value = '' // 清除激活状态

  search()
}

// 搜索，点击查询按钮后触发
const search = function () {
  trimJwCode();
  getObj.value.pageNum = 1
  get()
}


// 今天
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]
  activeTimeRange.value = 'today' // 标记当前激活状态

  search()
}

// 昨天
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]
  activeTimeRange.value = 'yesterday' // 标记当前激活状态

  search()
}

// 近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]
  activeTimeRange.value = '7days' // 标记当前激活状态

  search()
}

// 计算每行免费金币6月+12月的方法
const calculateFreeGold = (row) => {
  const freeJune = row.freeJune || 0;
  const freeDecember = row.freeDecember || 0;
  return (freeJune + freeDecember);
}
// 新增排序字段和排序方式
const sortField = ref('')
const sortOrder = ref('')
// 处理排序事件
const handleSortChange = (column) => {
  if (column.prop === 'sumGold') {//新增金币总数字段排序
    sortField.value = 'sum_gold'
  } else if (column.prop === 'permanentGold') {
    sortField.value = 'permanent_gold'
  } else if (column.prop === 'taskGold') {
    sortField.value = 'task_gold'
  } else if (column.prop === 'freeGold') {
    sortField.value = 'freeGold'
  } else if (column.prop === 'auditTime') {//删除了更新时间的creatTime
    sortField.value = 'audit_time'
  }
  sortOrder.value = column.order === 'ascending' ? 'ASC' : 'DESC'
  //get（）要写在handleSortChange方法里面，不然会导致排序失效
  get()
}

const exportExcel = async function () {
  const params = {
    goldDetail: {
      jwcode: goldDetail.value.jwcode || '',
      payPlatform: goldDetail.value.payPlatform || '',
      type: goldDetail.value.type || '',
      markets: goldDetail.value.markets || [],
      startTime: goldDetail.value.startTime || '',
      endTime: goldDetail.value.endTime || '',
      sortField: goldDetail.value.sortField || '',
      sortOrder: goldDetail.value.sortOrder || '',
      flag: showEmployeeData.value ? 0 : 1 // 新增 flag 参数
    },

  }
  const res = await API({url: '/goldDetail/export', data: params})
  if (res.code === 200) {
    ElMessage.success('导出成功')
  }
}

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

const handleCurrentChange = function (val) {
  getObj.value.pageNum = val
  get()
}


// 挂载
onMounted(async function () {
  await get()
  await getMarket()

  await getPlatform() // 调用获取平台信息的函数
})

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 === 0; //0表示客户明细
      });
      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 '未知状态';
  }
}


// 存储地区选择变化
const selectedMarketPath = ref([])

const handleMarketChange = (value) => {
  if (value && value.length > 0) {
    const lastValue = value[value.length - 1];
    // 确保返回值是数组，如果不是则包装成数组
    const marketValue = reverseMarketMapping[lastValue];
    goldDetail.value.markets = Array.isArray(marketValue) ? marketValue : [marketValue];
  } else {
    // 保持[""]格式
    goldDetail.value.markets = [];
  }
};
// 获取地区，修改为级联下拉框
const getMarket = async function () {
  try {
    // 发送POST请求
    const result = await API({

      url: '/market/selectMarket',
    });
    // 将响应结果存储到响应式数据中
    console.log('请求成功', result)

    // 递归转换树形结构为级联选择器需要的格式（跳过第一级节点）
    const transformTree = (nodes) => {
      // 直接处理第一级节点的子节点
      const allChildren = nodes.flatMap(node => node.children || []);

      return allChildren.map(child => {
        const grandchildren = child.children && child.children.length
            ? transformTree([child]) // 递归处理子节点
            : null;

        return {
          value: child.name,
          label: child.name,
          children: grandchildren
        };
      });
    };
    // 存储地区信息
    markets.value = transformTree(result.data)
    console.log('转换后的地区树==============', markets.value)
  } catch (error) {
    console.log('请求失败', error)
  }
}
const format3 = (num) => {
  // 每三位添加逗号
  return num.toLocaleString('en-US')
}
</script>
<template>
  <div>
    <el-card style="margin-bottom: 1vh;">
      <el-row style="margin-bottom: 10px">
        <el-col :span="5">
          <div class="head-card-element">
            <el-text class="mx-1" size="large">精网号：</el-text>
            <el-input v-model="goldDetail.jwcode" style="width: 150px" placeholder="请输入精网号" clearable/>
          </div>
        </el-col>
        <el-col :span="5">
          <div class="head-card-element">
            <el-text class="mx-1" size="large">平台信息：</el-text>
            <el-select v-model="goldDetail.payPlatform" placeholder="请选择平台信息" style="width: 160px" clearable
                       :loading="isLoadingPlatform">
              <el-option v-for="item in platform" :key="item.id" :label="item.label" :value="item.value"/>
            </el-select>
          </div>
        </el-col>
        <el-col :span="5">
          <div class="head-card-element">
            <el-text class="mx-1" size="large">数量更新类型：</el-text>
            <el-select v-model="goldDetail.type" placeholder="请选择更新类型" style="width: 160px" clearable>
              <el-option v-for="item in type" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </div>
        </el-col>
        <el-col :span="5">
          <div class="head-card-element">
            <el-text class="mx-1" size="large">所属地区：</el-text>
            <el-cascader
                v-model="selectedMarketPath"
                :options="markets"
                placeholder="请选择所属地区"
                clearable
                style="width:180px"
                @change="handleMarketChange"
            />
          </div>
        </el-col>
        <el-col :span="3">
          <div class="head-card-element">
            <el-checkbox v-model="showEmployeeData" @change="search()">员工数据</el-checkbox>
          </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="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-card>
    <el-card>
      <div>
        金币净变化：{{ format3(totalGoldTotal || 0) }}&nbsp;&nbsp;&nbsp;&nbsp;
        永久金币：{{ format3(totalPermanentGold || 0) }}&nbsp;&nbsp;&nbsp;&nbsp;
        免费金币：{{ format3(totalFreeGold || 0) }}&nbsp;&nbsp;&nbsp;&nbsp;
        任务金币：{{ format3(totalTaskGold || 0) }}&nbsp;&nbsp;
        <a style="color:#b1b1b1; font-size: small;">当前合计仅显示筛选范围内的金币净变化（充值总额 - 消费总额 + 退款总额)</a>
      </div>
      <div style="height: 55vh; overflow-y: auto">
        <el-table :data="tableData" style="width: 82vw" @sort-change="handleSortChange" height="55vh">
          <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="name" label="姓名" width="150" show-overflow-tooltip/>
          <el-table-column fixed="left" prop="jwcode" label="精网号" width="120"/>
          <el-table-column prop="market" label="所属地区" width="120"/>
          <el-table-column prop="payPlatform" label="平台信息" width="140"/>
          <el-table-column prop="type" label="更新类型" width="110">
            <template #default="scope">
              <span v-if="scope.row.type === 0">充值</span>
              <span v-if="scope.row.type === 1">消耗</span>
              <span v-if="scope.row.type === 2">退款</span>
              <span v-if="scope.row.type === 3">其他</span>
            </template>
          </el-table-column>

          <el-table-column prop="sumGold" sortable="custom" label="金币数量" width="110">
            <template #default="scope">
              <span>{{ (scope.row.sumGold || 0) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="permanentGold" sortable="custom" label="永久金币" width="110">
            <template #default="scope">
              <span>{{ (scope.row.permanentGold || 0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="freeGold" sortable="custom" label="免费金币" width="110">
            <template #default="scope">
              <span>{{ (calculateFreeGold(scope.row) || 0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="taskGold" sortable="custom" label="任务金币" width="110">
            <template #default="scope">
              <span>{{ (scope.row.taskGold || 0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="adminName" label="提交人" width="110"/>
          <el-table-column prop="auditTime" sortable="custom" label="更新时间" width="210" show-overflow-tooltip>
            <template #default="scope">
                  <span>{{
                      moment(scope.row.auditTime).format('YYYY-MM-DD HH:mm:ss')
                    }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 此处分页 -->
      <div class="pagination" style="margin-top: 20px;display: flex;">
        <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-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>
  </div>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
