<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import ElementPlus from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { AiFillRead } from 'vue-icons-plus/ai'
import axios from 'axios'
import moment from 'moment'
import API from '@/util/http.js'
const selectData = ref({
    jwcode: '',
    market: '',
    startTime: '',
    endTime: '',
})
const permanentBeans = ref(0)
const freeBean = ref(0)
const beanNum = ref(0)
const money = ref(0)
const defaultTime = [
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
]
//时间格式化
const formatTime = (val) => val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : ''
const tableData = ref([])
//存储所有的地区数据
const market = ref([])
const getTime = ref([])
//记录当前选中时间按钮状态
const activeTimeRange = ref('')
const handleDatePickerChange = () => {
    activeTimeRange.value = ''
}
//获取当齐全条件的金豆总数
const getTotalBeans = async () => {
    try {
        const result = await API({
            url: '/beanRecharge/statsSystemBean',
            data: {
                ...selectData.value,
            }
        })
        if (result.code == 200) {
            if (result.data) {
                permanentBeans.value = result.data.permanentBean
                freeBean.value = result.data.freeBean
                beanNum.value = result.data.beanNum
                money.value = result.data.money
            }else{
                permanentBeans.value = 0
                freeBean.value = 0
                beanNum.value = 0
                money.value = 0
            }

            console.log('金豆总数获取成功');
        }
        console.log('获取金豆总数失败：', result.msg);
    } catch (error) {
        console.log('获取金豆总数出错');
    }
}
//获取所有地区
const getArea = async () => {
    const result = await API({
        url: '/beanRecharge/systemMarket',
        data: {}
    })
    if (result.code == 200) {
        market.value = result.data
        console.log('系统充值地区获取成功', market.value)
    } else {
        ElMessage.error('系统充值地区获取失败')
    }
}
//获取今天日期
const getToday = () => {
    const today = new Date()
    const startTime = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate(),
    )
    const endTime = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate(),
        23, 59, 59
    )
    getTime.value = [startTime, endTime]
    activeTimeRange.value = 'today'
    search()
}

const getYesterday = () => {
    const yesterday = new Date()
    yesterday.setDate(yesterday.getDate() - 1)
    const startTime = new Date(
        yesterday.getFullYear(),
        yesterday.getMonth(),
        yesterday.getDate()
    )
    const endTime = new Date(
        yesterday.getFullYear(),
        yesterday.getMonth(),
        yesterday.getDate(),
        23, 59, 59
    )
    getTime.value = [startTime, endTime]
    activeTimeRange.value = 'yesterday'
    search()

}

const get7Days = function () {
    const today = new Date()
    const startTime = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate() - 6
    )
    const endTime = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate(),
        23, 59, 59
    )
    getTime.value = [startTime, endTime]
    activeTimeRange.value = '7days'
    search()

}

const reset = () => {
    selectData.value = {
        jwcode: '',
        market: '',
        startTime: '',
        endTime: '',
    }
    getTime.value = []
    activeTimeRange.value = ''
    search()
}

//查询
const search = () => {
    //判断精网号查询是否为数字
    getObj.value.pageNum = 1
    if (selectData.value.jwcode) {
        const numRef = /^\d{1,9}$/;
        if (!numRef.test(selectData.value.jwcode)) {
            ElMessage.error('请检查精网号格式')
            return
        }
    }
    get()
    getTotalBeans()
}
//获取表格数据
const get = async () => {
    try {
        if (getTime.value != null) {
            selectData.value.startTime = formatTime(getTime.value[0])
            selectData.value.endTime = formatTime(getTime.value[1])
        } else {
            selectData.value.startTime = ''
            selectData.value.endTime = ''
        }
        const data = {
            ...getObj.value,
            "beanSystemRechargeInfo": {
                ...selectData.value,
                sortField: sortField.value,
                sortOrder: sortOrder.value,
            },
        }
        console.log('请求参数：', data);
        const result = await API({
            url: '/beanRecharge/selectBySystem',
            data: data
        })
        if (result.code == 200) {
            tableData.value = result.data.list
            total.value = result.data.total
        } else {
            ElMessage.error(result.message)
        }
    } catch (error) {
        console.log('搜索失败', error);
    }
}
//排序字段
//处理表格排序事件
const sortField = ref('')
const sortOrder = ref('')
const handleSortChange = (column) => {
    console.log('排序字段：', column.prop)
    console.log('排序方式：', column.order)

    // 直接使用允许的排序字段列表进行过滤
    const allowedFields = ['money', 'freeBean', 'rechargeTime', 'createTime', 'permanentBean'];
    if (allowedFields.includes(column.prop)) {
        sortField.value = column.prop;
    }

    sortOrder.value = column.order === 'ascending' ? 'ASC' : 'DESC';

    console.log('传递给后端的排序字段：', sortField.value)
    console.log('传递给后端的排序方式：', sortOrder.value)

    get();
}
//========================分页===========================
// 搜索对象
const total = ref(0)
const getObj = ref({
    pageNum: 1,
    pageSize: 50
})
const handlePageSizeChange = (value) => {
    getObj.value.pageSize = value
    get()
}
const handleCurrentChange = (value) => {
    getObj.value.pageNum = value
    get()
}

//==========================导出=======================
const exportExcel = async () => {
    const params = {
        ...getObj.value,
        "beanSystemRechargeInfo": {
            ...selectData.value,
            sortField: sortField.value,
            sortOrder: sortOrder.value,
        },
    }
    try {
        const res = await API({ url: '/export/exportBean', data: params })
        console.log('系统充值导出的参数为：', params);

        if (res.code === 200) {
            ElMessage.success('导出成功')
        } else {
            ElMessage.error(res.message || '导出失败，请稍后重试')
        }
    } catch (error) {
        console.log('请求失败', error)
        ElMessage.error('导出失败，请稍后重试')
    }
}
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 === 9;
            });
            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 format3 = (num) => {
    // 每三位添加逗号
    return num.toLocaleString('en-US')
}
onMounted(async function () {
    await get()
    await getArea()
    await getTotalBeans()
})
</script>
<template>
    <el-card class="condition">
        <div>
            <el-text size="large">精网号：</el-text>
            <el-input v-model="selectData.jwcode" placeholder="请输入精网号" style="width: 9vw;margin-right:1vw" clearable />

            <el-text size="large">所属地区：</el-text>
            <el-select v-model="selectData.market" placeholder="请选择所属地区" clearable style="width: 9vw;margin-right:1vw">
                <el-option v-for="item in market" :key="item" :label="item" :value="item" />
            </el-select>
        </div>
        <div style="margin-top: 1vh;">
            <el-text size="large">充值时间：</el-text>
            <el-date-picker v-model="getTime" type="datetimerange" range-separator="至" start-placeholder="起始时间"
                end-placeholder="结束时间" style="width: 20vw" @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" style="width: 80px;" @click="exportExcel()">导出Excel</el-button>
            <el-button type="primary" style="width: 95px;" @click="openExportList">查看导出列表</el-button>
        </div>
    </el-card>
    <el-card>
        <div>
            金豆总数：{{ format3(beanNum) }}&nbsp;&nbsp;&nbsp;&nbsp;
            付费金豆数：{{ format3(permanentBeans) }}&nbsp;&nbsp;&nbsp;&nbsp;
            免费金豆数：{{ format3(freeBean) }}
        </div>
        <div>
            <el-table :data="tableData" style="width: 82vw;height:60vh;" @sort-change="handleSortChange">
                <el-table-column type="index" label="序号" 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="姓名" min-width="100" show-overflow-tooltip />
                <el-table-column fixed="left" prop="jwcode" label="精网号" min-width="110px" />
                <el-table-column prop="market" label="所属地区" min-width="100px" />
                <el-table-column prop="permanentBean" label="付费金豆" sortable="custom" min-width="110px" />
                <el-table-column prop="freeBean" label="免费金豆" sortable="custom" min-width="110px" />
                <el-table-column prop="remark" label="备注" min-width="150px" show-overflow-tooltip />
                <el-table-column prop="rechargeTime" label="充值时间" min-width="200px">
                    <template #default="scope">
                        {{ moment(scope.row.rechargeTime).format('YYYY-MM-DD HH:mm:ss') }}
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination" style="margin-top: 1vw">
            <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="80vw">
        <el-table :data="exportList" style="width: 80vw;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>
.condition {
    height: 6vw;
    margin-bottom: 0.5vh;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>