<template>
    <el-card style="margin-bottom: 1vh;">
        <el-text size="large">精网号：</el-text>
        <el-input v-model="searchObj.jwcode" placeholder="请输入精网号" style="width: 240px" clearable />
        <el-text size="large" style="margin-left:20px">地区：</el-text>
        <el-select v-model="searchObj.dept" placeholder="请选择地区" style="width: 240px" clearable>
            <el-option v-for="item in marketOptions" :key="item" :label="item" :value="item" />
        </el-select>

        <div style="float: right;">
            <el-button type="success" @click="reset">重置</el-button>
            <el-button type="primary" @click="search">查询</el-button>
        </div>
    </el-card>

    <el-card>
        <div class="stats-card">
            现有金豆数：{{ format3(stats.sumBean) }}金豆&nbsp;&nbsp;&nbsp;&nbsp;
            付费金豆数：{{ format3(stats.permanentBean) }}金豆&nbsp;&nbsp;&nbsp;&nbsp;
            免费金豆数：{{ format3(stats.freeBean) }}金豆&nbsp;&nbsp;&nbsp;&nbsp;
            消费金豆总数：{{ format3(stats.consumeSum) }}金豆&nbsp;&nbsp;&nbsp;&nbsp;
        </div>
        <el-table :data="tableData" height="65vh" @sort-change="handleSortChange" :row-style="{ height: '60px' }">
            <el-table-column type="index" label="序号" width="100px" fixed="left">
              <template #default="scope">
                <span>{{
                    scope.$index + 1 + (pagination.pageNum - 1) *  pagination.pageSize
                  }}</span>
              </template>
            </el-table-column>
            <el-table-column label="姓名" style="width: 120px;" prop="name" show-overflow-tooltip />
            <el-table-column label="精网号" style="width: 120px;" prop="jwcode" />
            <el-table-column label="所属地区" style="width: 120px;" prop="dept" />
            <el-table-column label="现有金豆" style="width: 120px;" prop="beanNum" sortable="custom" />
            <el-table-column label="免费金豆" style="width: 120px;" prop="freeBean" sortable="custom" />
            <el-table-column label="付费金豆" style="width: 120px;" prop="buyBean" sortable="custom" />
            <el-table-column label="历史消费" style="width: 120px;" prop="totalCostBean" sortable="custom" />

        </el-table>
        <el-pagination class="pagination" v-model:current-page="pagination.pageNum"
            v-model:page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total" @size-change="handlePageSizeChange"
            @current-change="handleCurrentChange"></el-pagination>
    </el-card>

</template>
<script setup>
import { ref, onMounted } from 'vue'
import API from '@/util/http.js'
import { useAdminStore } from "@/store/index.js";
import { storeToRefs } from "pinia";
const adminStore = useAdminStore();
const { adminData, menuTree } = storeToRefs(adminStore);
import { permissionMapping, findMenuById } from "@/utils/menuTreePermission.js"
import { ElMessage } from 'element-plus';

const tableData = ref([])
const marketOptions = ref([])
const searchObj = ref({
    jwcode: '',
    dept: '',
    sortField: '',
    sortOrder: ''
})
const stats = ref({
    sumBean: 0,
    permanentBean: 0,
    freeBean: 0,
    consumeSum: 0
})
const pagination = ref({
    pageNum: 1,
    pageSize: 50,
    total: 0
})
const get = async function () {
    if(findMenuById(menuTree.value, permissionMapping.View_Golden_Bean_Balance)){
    try {
        trim()
         if(searchObj.value.jwcode){
        const numRef = /^\d{1,9}$/;
        if(!numRef.test(searchObj.value.jwcode)){
            ElMessage.error('请检查精网号格式')
            return 
        }
    }
        const params = {
            beanUser: {    //金豆客户列表
                jwcode: searchObj.value.jwcode,   //精网号
                dept: searchObj.value.dept,  //地区
                sortField: searchObj.value.sortField,//排序字段
                sortOrder: searchObj.value.sortOrder//正序倒序
            },
            pageNum: pagination.value.pageNum,
            pageSize: pagination.value.pageSize
        }
        const res = await API({
            url: '/beanUser/userBean',
            data: params
        })
        if (res.code === 200) {
            tableData.value = res.data.list
            pagination.value.total = res.data.total
        }
    } catch (error) {
        console.log(error)
    }
}else{
    ElMessage.error('无此权限')
}
}
const getStats = async () => {
    if (findMenuById(menuTree.value, permissionMapping.View_Golden_Bean_Balance)) {
        try {
            const params = {
                beanUser:{
                    jwcode: searchObj.value.jwcode,
                    dept: searchObj.value.dept
                }
            }
            const res = await API({
                url: '/beanUser/userBeanSum',
                data: params
            })

            stats.value.sumBean = res.data.sumBean
            stats.value.permanentBean = res.data.permanentBean
            stats.value.freeBean = res.data.freeBean
            stats.value.consumeSum = res.data.consumeSum
            console.log('see see stats和搜索对象', stats.value, params)
        } catch (error) {
            console.log('请求失败', error)
        }
    }else{
        ElMessage.error('无此权限')
    }
}
const handleSortChange = (column) => {
    if (column.prop === 'beanNum') {
        searchObj.value.sortField = 'jinbi'
    } else if (column.prop === 'freeBean') {
        searchObj.value.sortField = 'jinbi_free'
    } else if (column.prop === 'buyBean') {
        searchObj.value.sortField = 'jinbi_buy'
    } else if (column.prop === 'totalCostBean') {
        searchObj.value.sortField = 'jinbi_cost_total'
    } else {
        searchObj.value.sortField = ''
    }
    searchObj.value.sortOrder = column.order === 'ascending' ? 'asc' : 'desc'
    console.log('排序字段：', searchObj.value.sortField,'排序方式：', searchObj.value.sortOrder)
    search()
}
const getmarkets = async () => {
    try {
        const result = await API({ url: '/beanUser/getDept', data: {} })
        marketOptions.value = result.data || []
    } catch (error) {
        console.error('获取地区列表失败', error)
    }
}
// 精网号去空格
const trim = () => {
    if (searchObj.value.jwcode) {
        searchObj.value.jwcode = searchObj.value.jwcode.replace(/\s/g, '');
    }
}
const reset = function () {
    searchObj.value.jwcode = ''
    searchObj.value.dept = ''
    search()
}
const handlePageSizeChange = function (val) {
    pagination.value.pageSize = val
    search()
}
const handleCurrentChange = function (val) {
    pagination.value.pageNum = val
    search()
}
const format3 = (num) => {
    // 每三位添加逗号
    return num.toLocaleString('en-US')
}
const search = () => {
    get()
    getStats()
}

onMounted(() => {
    search()
    getmarkets()
    getStats()
    console.log('页面接收到的adminData:', adminData.value)
})
</script>

<style scoped>
</style>