<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>退款统计报表</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}">
    <link rel="stylesheet" th:href="@{/css/common.css}">
    <!-- 引入组件库 -->
    <script th:src="@{/layui/jquery-3.4.1.min.js}"></script>
    <script th:src="@{/layui/layui.js}"></script>
    <script th:src="@{/js/echarts/echarts.common.min.js}"></script>
    <script th:src="@{/js/common.js}"></script>

    <style>
        body {
            background: #f2f2f2
        }

        #boxDiv {
            background: #ffffff
        }

        #titleDiv {
            overflow: visible;
        }

        .content {
            padding: 0 8px;
        }

        .tableTitle {
            height: 20px;
            margin-top: 10px;
            margin-bottom: 10px;
        }

        .tableTitle > * {
            height: 20px;
            line-height: 20px;
            display: inline-block;
            margin-right: 5px;
        }

        .tableName {
            border-left: 3px solid #0000FF;
            padding-left: 5px;
            font-size: 16px;
            font-weight: bold;
        }

        .selectDate {
            font-size: 14px;
            color: rgba(0, 0, 0, 0.65)
        }

        .layui-table-page {
            height: 81px;
        }

        .summary-card {
            background: #fff;
            padding: 15px;
            margin-bottom: 15px;
            border-radius: 4px;
            box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        }

        .summary-item {
            display: inline-block;
            margin-right: 30px;
            padding: 10px 0;
        }

        .summary-label {
            font-size: 14px;
            color: #666;
        }

        .summary-value {
            font-size: 24px;
            font-weight: bold;
            color: #333;
            margin-top: 5px;
        }

        .chart-container {
            background: #fff;
            padding: 15px;
            margin-bottom: 15px;
            border-radius: 4px;
            box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        }

        #trendChart {
            width: 100%;
            height: 400px;
        }
    </style>
</head>
<body class="layui-layout-body">
<div id="boxDiv" style="left:8px;right: 8px;bottom:8px;top:8px;position:absolute;overflow-y: auto;">
    <div class="toolbar" id="titleDiv">
        <div style="display: inline-block;">
            <form class="layui-form">
                <div class="layui-inline">
                    <label class="layui-form-label">支付方式</label>
                    <div class="layui-input-inline">
                        <select id="searchPayType" lay-filter="searchPayType">
                            <option value="">全部</option>
                            <option th:each="payTypeObj : ${payTypeList}" th:value="${payTypeObj.dicvalue}"
                                    th:text="${payTypeObj.dicname}"></option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">退款类型</label>
                    <div class="layui-input-inline">
                        <select id="searchRefundType" lay-filter="searchRefundType">
                            <option value="">全部</option>
                            <option th:each="refundTypeObj : ${refundTypeList}" th:value="${refundTypeObj.dicvalue}"
                                    th:text="${refundTypeObj.dicname}"></option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">业务类型</label>
                    <div class="layui-input-inline">
                        <select id="searchBizType" lay-filter="searchBizType">
                            <option value="">全部</option>
                            <option th:each="bizTypeObj : ${bizTypeList}" th:value="${bizTypeObj.dicvalue}"
                                    th:text="${bizTypeObj.dicname}"></option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">日期选择</label>
                    <div class="layui-input-inline">
                        <input type="text" class="layui-input formWidthTwo" id="searchDate" placeholder=" ~ "
                               th:value="${startTime+' ~ '+endTime}">
                    </div>
                </div>
                <div class="layui-inline">
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" onclick="search()"><i
                            class="layui-icon layui-icon-search"></i>查询
                    </button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" onclick="exportExcel()"><i
                            class="layui-icon">&#xe67d;</i>导出
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 汇总数据卡片 -->
    <div class="content">
        <div class="summary-card">
            <div class="summary-item">
                <div class="summary-label">退款总笔数</div>
                <div class="summary-value" id="totalRefundCount">0</div>
            </div>
            <div class="summary-item">
                <div class="summary-label">退款总金额（元）</div>
                <div class="summary-value" id="totalRefundAmount">0.00</div>
            </div>
            <div class="summary-item">
                <div class="summary-label">平均退款金额（元）</div>
                <div class="summary-value" id="avgRefundAmount">0.00</div>
            </div>
            <div class="summary-item">
                <div class="summary-label">涉及患者数</div>
                <div class="summary-value" id="uniquePatients">0</div>
            </div>
            <div class="summary-item">
                <div class="summary-label">操作员数</div>
                <div class="summary-value" id="uniqueOperators">0</div>
            </div>
        </div>

        <!-- 趋势图表 -->
        <div class="chart-container">
            <div class="tableTitle">
                <span class="tableName">退款趋势分析</span>
            </div>
            <div id="trendChart"></div>
        </div>

        <!-- 统计维度选择 -->
        <div class="layui-tab layui-tab-brief" lay-filter="dimensionTab">
            <ul class="layui-tab-title">
                <li class="layui-this" lay-id="all">全部统计</li>
                <li lay-id="time">按日期统计</li>
                <li lay-id="payType">按支付方式统计</li>
                <li lay-id="bizType">按业务类型统计</li>
                <li lay-id="refundType">按退款类型统计</li>
            </ul>
        </div>

        <!-- 详细数据表格 -->
        <div class="tableTitle">
            <span class="tableName">退款统计明细</span>
            <span class="selectDate">&nbsp;</span>
        </div>
        <table id="demo" lay-filter="test"></table>
    </div>

</div>
</body>
<script th:inline="javascript">
    let payTypeList = [[${payTypeList}]];
    let refundTypeList = [[${refundTypeList}]];
    let bizTypeList = [[${bizTypeList}]];
    let layer, laydate, table, form, element;
    let currentDimension = 'all'; // 当前统计维度
    let trendChart; // ECharts实例

    layui.use(['element', 'table', 'laydate', 'layer', 'form'], function () {
        layer = layui.layer;
        table = layui.table;
        laydate = layui.laydate;
        form = layui.form;
        element = layui.element;

        // 初始化ECharts
        trendChart = echarts.init(document.getElementById('trendChart'));

        //表格加载
        table.render({
            elem: '#demo',
            height: 500,
            title: '退款统计明细',
            page: true,//开启分页
            limit: 20,
            limits: [20, 30, 50, 100],
            defaultToolbar: [],
            id: 'test',
            even: 'true',
            cols: [
                [
                    {field: 'DIMENSION_NAME', align: 'center', title: '统计维度', width: 120},
                    {field: 'DIMENSION_VALUE', align: 'center', title: '维度值', width: 180, templet: function(d){
                        function getDicName(list, val){
                            if(!list || !val) return val;
                            for(let i=0;i<list.length;i++){
                                if(list[i].dicvalue === val){ return list[i].dicname; }
                            }
                            return val;
                        }
                        if(currentDimension === 'payType'){
                            return getDicName(payTypeList, d.DIMENSION_VALUE);
                        } else if(currentDimension === 'refundType'){
                            return getDicName(refundTypeList, d.DIMENSION_VALUE);
                        } else if(currentDimension === 'bizType'){
                            return getDicName(bizTypeList, d.DIMENSION_VALUE);
                        }
                        return d.DIMENSION_VALUE;
                    }},
                    {field: 'REFUND_COUNT', align: 'center', title: '退款笔数', width: 120, sort: true},
                    {
                        field: 'TOTAL_REFUND_AMOUNT',
                        align: 'center',
                        title: '退款总金额（元）',
                        width: 150,
                        sort: true,
                        templet: function (d) {
                            return d.TOTAL_REFUND_AMOUNT ? parseFloat(d.TOTAL_REFUND_AMOUNT).toFixed(2) : '0.00';
                        }
                    },
                    {
                        field: 'AVG_REFUND_AMOUNT',
                        align: 'center',
                        title: '平均退款金额（元）',
                        width: 150,
                        sort: true,
                        templet: function (d) {
                            return d.AVG_REFUND_AMOUNT ? parseFloat(d.AVG_REFUND_AMOUNT).toFixed(2) : '0.00';
                        }
                    },
                    {
                        field: 'MAX_REFUND_AMOUNT',
                        align: 'center',
                        title: '最大退款金额（元）',
                        width: 150,
                        sort: true,
                        templet: function (d) {
                            return d.MAX_REFUND_AMOUNT ? parseFloat(d.MAX_REFUND_AMOUNT).toFixed(2) : '0.00';
                        }
                    },
                    {
                        field: 'MIN_REFUND_AMOUNT',
                        align: 'center',
                        title: '最小退款金额（元）',
                        width: 150,
                        sort: true,
                        templet: function (d) {
                            return d.MIN_REFUND_AMOUNT ? parseFloat(d.MIN_REFUND_AMOUNT).toFixed(2) : '0.00';
                        }
                    },
                    {field: 'UNIQUE_PATIENTS', align: 'center', title: '涉及患者数', width: 120, sort: true},
                    {field: 'UNIQUE_OPERATORS', align: 'center', title: '操作员数', width: 120, sort: true}
                ]
            ],
            data: []
        });

        //时间控件
        laydate.render({
            elem: '#searchDate',
            type: 'date',
            range: '~'
        });

        // 监听维度切换
        element.on('tab(dimensionTab)', function (data) {
            currentDimension = this.getAttribute('lay-id');
            search();
        });

        // 初始化加载数据
        search();
        loadSummaryData();
        loadTrendData();
    });

    //查询
    function search(num) {
        num = num || 1;
        let url = "/refundStatistics/findRefundStatistics";
        let param = getSearchParams();
        param.dimension = currentDimension;

        console.log('查询参数:', param); // 调试日志

        table.reload('test', {
            method: 'get',
            url: url,
            where: param,
            page: {
                curr: num
            },
            done: function(res, curr, count) {
                console.log('查询结果:', res); // 调试日志
                console.log('数据条数:', count); // 调试日志
            }
        });

        // 更新日期显示
        let date = $("#searchDate").val();
        if (date !== '') {
            $(".selectDate").text(date);
        }

        // 同时更新汇总数据和趋势图
        loadSummaryData();
        loadTrendData();
    }

    // 加载汇总数据
    function loadSummaryData() {
        let url = "/refundStatistics/getRefundSummary";
        let param = getSearchParams();

        console.log('加载汇总数据，参数:', param); // 调试日志

        $.ajax({
            url: url,
            type: 'get',
            data: param,
            success: function (data) {
                console.log('汇总数据返回:', data); // 调试日志
                if (data.code === 0) {
                    let summaryData = data.data;
                    $("#totalRefundCount").text(summaryData.TOTAL_REFUND_COUNT || 0);
                    $("#totalRefundAmount").text(summaryData.TOTAL_REFUND_AMOUNT ? parseFloat(summaryData.TOTAL_REFUND_AMOUNT).toFixed(2) : '0.00');
                    $("#avgRefundAmount").text(summaryData.AVG_REFUND_AMOUNT ? parseFloat(summaryData.AVG_REFUND_AMOUNT).toFixed(2) : '0.00');
                    $("#uniquePatients").text(summaryData.UNIQUE_PATIENTS || 0);
                    $("#uniqueOperators").text(summaryData.UNIQUE_OPERATORS || 0);
                } else {
                    console.error('汇总数据查询失败:', data.msg);
                }
            },
            error: function(xhr, status, error) {
                console.error('汇总数据请求失败:', error);
            }
        });
    }

    // 加载趋势数据
    function loadTrendData() {
        let url = "/refundStatistics/getRefundTrend";
        let param = getSearchParams();

        console.log('加载趋势数据，参数:', param); // 调试日志

        $.ajax({
            url: url,
            type: 'get',
            data: param,
            success: function (data) {
                console.log('趋势数据返回:', data); // 调试日志
                if (data.code === 0) {
                    let trendData = data.data;
                    console.log('趋势数据条数:', trendData.length); // 调试日志
                    renderTrendChart(trendData);
                } else {
                    console.error('趋势数据查询失败:', data.msg);
                }
            },
            error: function(xhr, status, error) {
                console.error('趋势数据请求失败:', error);
            }
        });
    }

    // 渲染趋势图表
    function renderTrendChart(data) {
        let dates = [];
        let counts = [];
        let amounts = [];

        for (let i = 0; i < data.length; i++) {
            dates.push(data[i].TREND_DATE);
            counts.push(data[i].DAILY_REFUND_COUNT);
            amounts.push(data[i].DAILY_REFUND_AMOUNT ? parseFloat(data[i].DAILY_REFUND_AMOUNT).toFixed(2) : 0);
        }

        let option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999'
                    }
                }
            },
            legend: {
                data: ['退款笔数', '退款金额']
            },
            xAxis: [
                {
                    type: 'category',
                    data: dates,
                    axisPointer: {
                        type: 'shadow'
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '退款笔数',
                    min: 0,
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                {
                    type: 'value',
                    name: '退款金额（元）',
                    min: 0,
                    axisLabel: {
                        formatter: '{value}'
                    }
                }
            ],
            series: [
                {
                    name: '退款笔数',
                    type: 'bar',
                    data: counts,
                    itemStyle: {
                        color: '#5470c6'
                    }
                },
                {
                    name: '退款金额',
                    type: 'line',
                    yAxisIndex: 1,
                    data: amounts,
                    itemStyle: {
                        color: '#ee6666'
                    }
                }
            ]
        };

        trendChart.setOption(option);
    }

    // 获取查询参数
    function getSearchParams() {
        let param = {};
        param.payType = $("#searchPayType").val();
        param.bizType = $("#searchBizType").val();
        param.refundType = $("#searchRefundType").val();

        let date = $("#searchDate").val();
        if (date !== '') {
            let time = date.split("~");
            param.startTime = time[0].trim();
            param.endTime = time[1].trim();
        }

        return param;
    }

    //导出
    function exportExcel() {
        let url = "/refundStatistics/exportRefundStatistics";
        let param = getSearchParams();
        param.dimension = currentDimension;

        let load = layer.load();
        $.ajax({
            url: url,
            type: 'get',
            data: param,
            success: function (data) {
                layer.close(load);
                if (data.code === 0) {
                    let fileName = data.fileName;
                    let dowloadName = "退款统计报表";
                    location.href = '/download?fileName=' + fileName + '&dowloadName=' + dowloadName;
                } else {
                    layer.alert(data.msg);
                }
            },
            error: function () {
                layer.close(load);
                layer.alert('导出失败，请稍后重试');
            }
        });
    }

    // 窗口大小改变时重新渲染图表
    window.addEventListener('resize', function () {
        if (trendChart) {
            trendChart.resize();
        }
    });
</script>
</html>
