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

//新增复选框员工数据
// const showEmployeeData = ref(false)

// 监听全局flag状态变化
 watch(flag, (newFlag, oldFlag) => {
  // 当flag状态改变时，重新发送请求
  if (newFlag !== oldFlag) {
    console.log('员工数据flag状态改变，重新加载数据', newFlag)
    get()
  }
})


// 标记当前激活的时间范围按钮
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(t('elmessage.payPlatformError'))
    }

  } catch (error) {
    console.error('获取平台信息失败:', error);
    ElMessage.error(t('elmessage.payPlatformError'))
  } finally {
    isLoadingPlatform.value = false
  }
}

// 数量更新类型选项
const type = [
  {
    value: '0',
    label: t('clientCount.type.recharge')
  },
  {
    value: '1',
    label: t('clientCount.type.consume')
  },
  {
    value: '2',
    label: t('clientCount.type.refund')
  }
]

// 定义加载状态，获取地区数据
// 定义加载状态，获取地区数据
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.gold_coin_customer_bill)) {
    ElMessage.error(t('elmessage.noPermission'))
    return
  }
  try {
    // 搜索参数页码赋值
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }
    if (getTime.value && 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(t('elmessage.checkJwcodeFormat'))
        // 上面提示过了
        return
      }
    }
    const result = await API({
      url: '/goldDetail/getGoldDetail',
      method: 'post',
      data: { ...getObj.value, goldDetail: { ...goldDetail.value, 
        // flag: showEmployeeData.value ? 0 : 1 
        flag: flag.value
      } }
    })
    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 
          flag: flag.value
        },
        /* 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(t('elmessage.getTotalFailed'))
    }


  } 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 = '' // 清除激活状态

  //重置页码
  getObj.value.pageNum = 1
  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 参数
      flag: flag.value
    },

  }
  const res = await API({ url: '/goldDetail/export', data: params })
  if (res.code === 200) {
    ElMessage.success(t('elmessage.exportSuccess'))
  }
}

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 || 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');
  }
}


// 存储地区选择变化
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 class="card1" style="margin-bottom: 0.5vh;">
      <el-col style="margin-bottom: 1vh">
        <div class="select">
          <div class="selectRow">
            <el-text class="text" size="large">{{ $t('common.jwcode') }}：</el-text>
            <el-input class="selectContent" v-model="goldDetail.jwcode" :placeholder="$t('common.jwcodePlaceholder')" clearable />
          </div>
          <div class="selectRow">
            <el-text class="text" size="large">{{ $t('common.payPlatform') }}：</el-text>
            <el-select class="selectContent" v-model="goldDetail.payPlatform" :placeholder="$t('common.payPlatformPlaceholder')" style="width: 10vw;"
              clearable :loading="isLoadingPlatform">
              <el-option v-for="item in platform" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="selectRow">
            <el-text class="textB" size="large">{{ $t('common.updateType') }}：</el-text>
            <el-select v-model="goldDetail.type" :placeholder="$t('common.updateTypePlaceholder')" clearable>
              <el-option v-for="item in type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
          <div class="selectRow">
            <el-text  size="large">{{ $t('common.market') }}：</el-text>
            <el-cascader class="selectContent"  v-model="selectedMarketPath" :options="markets" :placeholder="$t('common.marketPlaceholder')"
              style="width:10vw" clearable @change="handleMarketChange" />
          </div>
          <!-- <div>
            <el-checkbox v-model="showEmployeeData" @change="search()">员工数据</el-checkbox>
          </div> -->
        </div>
      </el-col>

      <el-col>
        <div class="select">
          <div class="selectRow" style="width: 35vw">
            <el-text class="text" size="large">{{ $t('common.updateTime') }}：</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="width: 14.2vw" @change="handleDatePickerChange"
              :default-time="defaultTime" :disabled-date="disabledDate" />
            <el-button @click="getToday()" style="margin-left: 0.3vw"
              :type="activeTimeRange === 'today' ? 'primary' : ''">
              {{ $t('common.today') }}
            </el-button>
            <el-button @click="getYesterday()" style="margin-left: 0.3vw"
              :type="activeTimeRange === 'yesterday' ? 'primary' : ''">   
              {{ $t('common.yesterday') }}
            </el-button>
            <el-button @click="get7Days()" style="margin-left: 0.3vw"
              :type="activeTimeRange === '7days' ? 'primary' : ''">
              {{ $t('common.last7Days') }}
            </el-button>
          </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.netGoldChange') }}：{{ format3(totalGoldTotal || 0) }}&nbsp;&nbsp;&nbsp;&nbsp;
        {{ $t('common.permanentGold') }}：{{ format3(totalPermanentGold || 0) }}&nbsp;&nbsp;&nbsp;&nbsp;
        {{ $t('common.freeGold') }}：{{ format3(totalFreeGold || 0) }}&nbsp;&nbsp;&nbsp;&nbsp;
        {{ $t('common.taskGold') }}：{{ format3(totalTaskGold || 0) }}&nbsp;&nbsp;
        <a style="color:#b1b1b1; font-size: small;">{{ $t('common.netGoldChangeTip') }}</a>
      </div>
      <div style="height: 65vh; ">
        <el-table :data="tableData" style="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 fixed="left" prop="name" :label="$t('common_list.name')" width="150" show-overflow-tooltip />
          <el-table-column fixed="left" prop="jwcode" :label="$t('common_list.jwcode')" width="120" />
          <el-table-column prop="market" :label="$t('common_list.market')" width="120" />
          <el-table-column prop="payPlatform" :label="$t('common_list.payPlatform')" width="140" />
          <el-table-column prop="type" :label="$t('common_list.type')" width="130">
            <template #default="scope">
              <span v-if="scope.row.type === 0">{{ $t('clientCount.recharge') }}</span>
              <span v-if="scope.row.type === 1">{{ $t('clientCount.consume') }}</span>
              <span v-if="scope.row.type === 2">{{ $t('clientCount.refund') }}</span>
              <span v-if="scope.row.type === 3">{{ $t('clientCount.other') }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="sumGold" sortable="custom" :label="$t('common_list.Gold')" width="110">
            <template #default="scope">
              <span>{{ (scope.row.sumGold || 0) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="permanentGold" sortable="custom" :label="$t('common_list.permanentGold')" width="130">
            <template #default="scope">
              <span>{{ (scope.row.permanentGold || 0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="freeGold" sortable="custom" :label="$t('common_list.freeGold')" width="130">
            <template #default="scope">
              <span>{{ (calculateFreeGold(scope.row) || 0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="taskGold" sortable="custom" :label="$t('common_list.taskGold')" width="130">
            <template #default="scope">
              <span>{{ (scope.row.taskGold || 0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="adminName" :label="$t('common_list.submitter')" width="110" />
          <el-table-column prop="auditTime" sortable="custom" :label="$t('common_list.updateTime')" 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" >
        <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="$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>
  </div>
</template>

<style scoped lang="scss">

.pagination {
  display: flex;
  margin-top: 1vh;
}

// 搜索的卡片样式
.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;
}

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

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

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

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

    .textB {
      width: 9vw;
      font-size: 15px;
    }

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