<script setup>
// 这是客户金币余额页面
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)
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";

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


// 变量
const dialogVisible = ref(false)

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


// 充值明细表格
const tableData = ref([])

// 新增金币总数变量
const goldtotal = ref(0)

// 计算用户各金币总数的不分页对象
const tableAllData = ref([])
// 各金币字段
const permanentGold = ref(0) // 修改为 currentPermanentGold 对应字段
const freeJuneGold = ref(0) // 修改为 currentFreeJune 对应字段
const freeDecemberGold = ref(0) // 修改为 currentFreeDecember 对应字段
const taskGold = ref(0) // 修改为 currentTaskGold 对应字段
const freeGold = ref(0) // 计算免费金币总数
//客户消费记录
const tableCountData = ref([])
const userInfo = ref({})

// 搜索===========================================
//分页总条目
const total = ref(100)
// 搜索对象时间
const getTime = ref([])
// 搜索User
const user = ref({
  markets: [],
})
// 不分页的搜索对象
const getAllObj = ref({})
// 搜索对象
const getObj = ref({
  pageNum: 1,
  pageSize: 50
})
// 新增排序字段和排序方式
const sortField = ref('')
const sortOrder = ref('')

// 方法
// 搜索===========================================================================
// 搜索方法
const get = async function (val) {
  if(!findMenuById(menuTree.value, permissionMapping.coinCustomerMoney)){
    ElMessage.error('无此权限')
    return
  }
  try {
    // 搜索参数页码赋值
    if (typeof val === 'number') {
      getObj.value.pageNum = val
    }

    // 添加排序字段和排序方式到请求参数
    user.value.sortField = sortField.value
    user.value.sortOrder = sortOrder.value
    console.log('搜索参数', getObj.value)

    // 发送POST请求
    const requestData = {...getObj.value, user: {...user.value}};//控制台打印请求的参数
    console.log('最终请求参数', JSON.stringify(requestData, null, 2)); // 打印格式化后的请求参数
    //console.log('请求参数', requestData);
    // 检查markets数组中是否包含'总部'或'研发部'
    // if (user.value.markets.includes('9') || user.value.markets.includes('9999')) {
    //   user.value.markets = [];
    // }
    if (user.value.jwcode) {
      // 纯数字
      const numberRegex = /^\d{1,9}$/;

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

    console.log('兄弟你是什么 user', user.value)
    // 获取合计数
    const resultGoldTotal = await API({
      url: '/goldDetail/goldTotal',
      data: {
        jwcode: user.value.jwcode,
        markets: user.value.markets,
      flag: showEmployeeData.value? 0 : 1
      }
    })
    // 判断精网号是否存在，假设精网号不存在时 result.data.list 为空数组
    if (result.data.list.length === 0) {
      // 将表格数据设置为空数组
      tableData.value = []
      // 将合计数设置为 0
      permanentGold.value = 0
      freeJuneGold.value = 0
      freeDecemberGold.value = 0
      taskGold.value = 0
      goldtotal.value = 0
      freeGold.value = 0

      // // 新增金币总数变量
      // const goldtotal = ref(0)
      // 分页总数设置为 0
      total.value = 0
      // ElMessage.warning('精网号不存在，请检查输入')
    }
    // 判断合计数是否存在,不存在时 result.data.list 为空数组
    else if(resultGoldTotal.data===0){
      // 将表格数据设置为空数组
      tableData.value = []
      // 将合计数设置为 0
      permanentGold.value = 0
      freeJuneGold.value = 0
      freeDecemberGold.value = 0
      taskGold.value = 0
      goldtotal.value = 0
      freeGold.value = 0
    }
    else {
      // 将响应结果存储到响应式数据中
      console.log('总数据请求成功', result)
      // 存储表格数据
      tableData.value = result.data.list
      console.log('tableData', tableData.value)

      // 从接口返回数据中获取各金币数值
      if (resultGoldTotal.data) {
        permanentGold.value = parseFloat(resultGoldTotal.data.permanentGold.toFixed(2))
        freeGold.value = parseFloat(resultGoldTotal.data.freeGold.toFixed(2))
        taskGold.value = parseFloat(resultGoldTotal.data.taskGold.toFixed(2))
        goldtotal.value = parseFloat(resultGoldTotal.data.goldtotal.toFixed(2))
      } else {
        console.error('合计数数据格式错误', resultGoldTotal)
        ElMessage.error('获取合计数失败，请稍后重试')
      }
      // 存储分页总数
      total.value = result.data.total
      console.log('total', total.value)
    }
  } catch (error) {
    console.log('请求失败', error)
    // 在这里可以处理错误逻辑，比如显示错误提示等
  }
}
// 精网号去空格，同时处理 user 和 putExcel 中的 jwcode
const trimJwCode = () => {
  if (user.value.jwcode) {
    user.value.jwcode = user.value.jwcode.replace(/\s/g, '');
  }

}
// 搜索
const search = function () {
  trimJwCode();
  getObj.value.pageNum = 1
  get()
}
// 重置
const reset = function () {
  user.value = {
    jwcode: '',
    markets: [],
  }
  sortField.value = ''
  sortOrder.value = ''
  get()
  selectedMarketPath.value = []
}
const cellClick = function (row, column) {
  console.log('cellClick', column.label)
  if (column.label === '姓名') {
    dialogVisible.value = true

    userInfo.value = row
  }
}
// 处理排序事件
const handleSortChange = (column) => {
  console.log('排序字段：', column.prop)
  console.log('排序方式：', column.order)
  if (column.prop === 'currentPermanentGold') {
    sortField.value = 'current_permanent_gold'
  } else if (column.prop === 'currentTaskGold') {
    sortField.value = 'current_task_gold'
  } else if (column.prop === 'currentFreeJune') {
    sortField.value = 'current_free_june'
  } else if (column.prop === 'currentFreeDecember') {
    sortField.value = 'current_free_december'
  }
  sortOrder.value = column.order === 'ascending' ? 'ASC' : 'DESC'
  get()
}

// 挂载
onMounted(async function () {
  await get()
  await getMarket()
  await getExportList()
})
const handlePageSizeChange = function (val) {
  getObj.value.pageSize = val
  get()
}
const handleCurrentChange = function (val) {
  getObj.value.pageNum = val
  get()
}
const exportExcel = async function () {
  const params = {
    user: {
      jwcode: user.value.jwcode || '',
      markets: user.value.markets || [],
    flag: showEmployeeData.value? 0 : 1
    }

  }
  const res = await API({url: '/goldDetail/exportGold', 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 === 1; //返回type為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];
    user.value.markets = Array.isArray(marketValue) ? marketValue : [marketValue];
  } else {
    // 保持[]格式
    user.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>
      <el-card style="margin-bottom: 1vh;">
        <div class="head-card">
          <div class="head-card-element">
            <el-text class="mx-1" size="large">精网号：</el-text>
            <el-input v-model="user.jwcode" style="width: 160px" placeholder="请输入精网号" clearable/>
          </div>
          <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>
            <div class="head-card-element">
              <el-checkbox v-model="showEmployeeData" @change="search()">员工数据</el-checkbox>
            </div>
          <el-button type="primary" @click="search()">查询</el-button>
          <el-button @click="reset" type="success">重置</el-button>
          <el-button type="primary" @click="exportExcel()">导出Excel</el-button>
          <el-button type="primary" @click="openExportList">查看导出列表</el-button>
        </div>
        <!-- </div> -->
      </el-card>
      <el-card>
        <div>
          金币总数：{{ format3(goldtotal || 0) }}&nbsp;&nbsp;&nbsp;&nbsp;
          永久金币：{{ format3(permanentGold  || 0) }}&nbsp;&nbsp;&nbsp;&nbsp;
          免费金币：{{ format3(freeGold  || 0) }}&nbsp;&nbsp;&nbsp;&nbsp;
          任务金币：{{ format3(taskGold  || 0) }}
        </div>
        <!-- 设置表格容器的高度和滚动样式 -->
        <div style="height: 60vh; overflow-y: auto">
          <el-table :data="tableData" @cellClick="cellClick" style="width: 82vw;"height="60vh"
                    @sort-change="handleSortChange">
            <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 prop="name" label="姓名" width="140"/>
            <el-table-column prop="jwcode" label="精网号" width="160"/>
            <el-table-column prop="market" label="所属地区" width="140"/>
            <el-table-column prop="sumGold" label="金币总数" width="140" aligh="center">
              <!-- <template #default="scope">
                <span>{{
                    ((scope.row.currentPermanentGold || 0) +
                        (scope.row.currentFreeJune || 0) +
                        (scope.row.currentFreeDecember || 0) +
                        (scope.row.currentTaskGold || 0)) 
                  }}</span>
              </template> -->
            </el-table-column>
            <el-table-column prop="currentPermanentGold" label="永久金币" sortable="custom" width="150">
              <template #default="scope">
                <span>{{ (scope.row.currentPermanentGold || 0)  }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="currentFreeJune" label="6月份到期免费金币" sortable="custom" width="170">
              <template #default="scope">
                <span>{{ (scope.row.currentFreeJune || 0)  }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="currentFreeDecember" label="12月份到期免费金币" sortable="custom" width="180">
              <template #default="scope">
                <span>{{ (scope.row.currentFreeDecember || 0)  }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="currentTaskGold" label="任务金币" sortable="custom" width="180">
              <template #default="scope">
                <span>{{ (scope.row.currentTaskGold || 0)  }}</span>
              </template>
            </el-table-column>
<!--            <el-table-column prop="rcoin" label="历史金币总额" width="150">
              <template #default="scope">
                <el-popover trigger="hover" placement="left" width="150">
                  <template #default>
                    <div>
                      <div>永久金币：{{ (scope.row.sumPermanentGold || 0)  }}</div>
                      <div>免费金币：{{ ((scope.row.sumFreeJune || 0) + (scope.row.sumFreeDecember || 0))  }}</div>
                      <div>任务金币：{{ (scope.row.sumTaskGold || 0)  }}</div>
                    </div>
                  </template>
                  <template #reference>
                    <span>
                      {{
                        (scope.row.sumPermanentGold || 0)  +
                        (scope.row.sumFreeJune || 0)  +
                        (scope.row.sumFreeDecember || 0)  +
                        (scope.row.sumTaskGold || 0) 
                      }}</span>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="sumConsume" label="历史消费" width="150">
              <template #default="scope">
                <el-popover trigger="hover" placement="left" width="150">
                  <template #default>
                    <div>
                      <div>永久金币：{{ (scope.row.sumConsumeGold || 0)  }}</div>
                      <div>免费金币：{{
                          ((scope.row.sumConsumeJune || 0) + (scope.row.sumConsumeDecember || 0)) 
                        }}
                      </div>
                      <div>任务金币：{{ (scope.row.sumConsumeJune || 0)  }}</div>
                    </div>
                  </template>
                  <template #reference>
                    <span>
                      {{
                        (scope.row.sumConsumeGold || 0)  +
                        (scope.row.sumConsumeTaskGold || 0)  +
                        (scope.row.sumConsumeJune || 0)  +
                        (scope.row.sumConsumeDecember || 0) 
                      }}</span>
                  </template>
                </el-popover>
              </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-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">
.pagination {
  display: flex;
}

.status {
  display: flex;
}

.head-card {
  display: flex;
}

.head-card-element {
  margin-right: 20px;
}

.head-card-btn {
  margin-left: auto;
}

.custom-box {
  display: flex;
  flex-wrap: wrap;
  row-gap: 5px;

  div:nth-child(1) {
    flex: 1 0 100%;
  }

  div {
    margin-right: 20px;
  }
}
</style>