<!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/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)
        }
    </style>
</head>
<body class="layui-layout-body">
<div id="boxDiv" style="left:8px;right: 8px;bottom:8px;top:8px;position:absolute;">
    <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">
                        <input type="text" class="layui-input formWidthTwo" id="searchDate" placeholder=" ~ ">
                    </div>
                </div>
                
                <div class="layui-inline">
                    <label class="layui-form-label">险种类型</label>
                    <div class="layui-input-inline">
                        <select id="insutype" class="layui-input formWidth">
                            <option value="">全部</option>
                            <option value="310">职工基本医疗保险</option>
                            <option value="340">新农合</option>
                            <option value="390">城乡居民基本医疗保险</option>
                            <option value="510">公务员医疗补助</option>
                            <option value="99410">工伤保险</option>
                        </select>
                    </div>
                </div>

                <div class="layui-inline">
                    <label class="layui-form-label">清算类别</label>
                    <div class="layui-input-inline">
                        <select id="clrType" class="layui-input formWidth">
                            <option value="">全部</option>
                            <option value="11">普通门诊</option>
                            <option value="21">住院</option>
                            <option value="31">门诊慢特病</option>
                            <option value="6101">门诊慢特病（高血压）</option>
                            <option value="6102">门诊慢特病（糖尿病）</option>
                            <option value="999913">居民门诊统筹</option>
                            <option value="999914">职工医保门诊共济</option>
                            <option value="999916">其他/非专项医疗费用</option>
                        </select>
                    </div>
                </div>

                <div class="layui-inline">
                    <label class="layui-form-label">对账结果</label>
                    <div class="layui-input-inline">
                        <select id="stmtRslt" class="layui-input formWidth">
                            <option value="">全部</option>
                            <option value="0">平</option>
                            <option value="1">不平</option>
                        </select>
                    </div>
                </div>
            </form>
        </div>
        <div class="layui-inline">
            <button class="layui-btn layui-btn-sm layui-btn-normal" data-type="search" id="search" onclick="search()">
                <i class="layui-icon layui-icon-search"></i>查询
            </button>
            <button class="layui-btn layui-btn-sm layui-btn-warm" onclick="executeReconciliation()">
                <i class="layui-icon layui-icon-refresh"></i>执行对账
            </button>
            <button class="layui-btn layui-btn-sm layui-btn-normal" onclick="exportExcel()">
                <i class="layui-icon">&#xe67d;</i>导出
            </button>
        </div>
    </div>
    <div class="content">
        <div class="tableTitle">
            <span class="tableName">医保对账结果</span>
            <span class="selectDate">&nbsp;</span>
        </div>
        <table id="demo" lay-filter="test"></table>
    </div>

</div>

<!-- 详情弹窗 -->
<div id="detailDialog" style="display:none; padding: 20px;">
    <table class="layui-table" lay-skin="line">
        <tbody>
        <tr>
            <td style="width: 150px; font-weight: bold;">对账日期</td>
            <td id="detail_trade_date"></td>
        </tr>
        <tr>
            <td style="font-weight: bold;">险种类型</td>
            <td id="detail_insutype"></td>
        </tr>
        <tr>
            <td style="font-weight: bold;">清算类别</td>
            <td id="detail_clr_type"></td>
        </tr>
        <tr>
            <td style="font-weight: bold;">医疗费用总额</td>
            <td id="detail_medfee_sumamt"></td>
        </tr>
        <tr>
            <td style="font-weight: bold;">基金支付总额</td>
            <td id="detail_fund_pay_sumamt"></td>
        </tr>
        <tr>
            <td style="font-weight: bold;">账户支付金额</td>
            <td id="detail_acct_pay"></td>
        </tr>
        <tr>
            <td style="font-weight: bold;">结算笔数</td>
            <td id="detail_fixmedins_setl_cnt"></td>
        </tr>
        <tr>
            <td style="font-weight: bold;">对账结果</td>
            <td id="detail_stmt_rslt"></td>
        </tr>
        <tr>
            <td style="font-weight: bold;">对账结果描述</td>
            <td id="detail_stmt_rslt_dscr"></td>
        </tr>
        <tr>
            <td style="font-weight: bold;">接口调用结果</td>
            <td id="detail_api_result"></td>
        </tr>
        <tr>
            <td style="font-weight: bold;">备注</td>
            <td>
                <div id="detail_remark_flag" style="margin-bottom: 6px;"></div>
                <textarea id="detail_remark_input" class="layui-textarea" style="min-height: 80px;"></textarea>
                <div style="margin-top: 6px;">
                    <button type="button" class="layui-btn layui-btn-sm" onclick="saveDetailRemark()">保存备注</button>
                </div>
            </td>
        </tr>
        <tr>
            <td style="font-weight: bold;">创建时间</td>
            <td id="detail_create_time"></td>
        </tr>
        </tbody>
    </table>
</div>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="getInfo">详细信息</a>
    <a class="layui-btn layui-btn-xs layui-btn-primary" lay-event="editRemark">编辑备注</a>
</script>
</body>
<script th:inline="javascript">
    let layer, laydate, table, form;
    let currentDetailId = null;

    function escapeHtml(value) {
        if (value === null || value === undefined) return '';
        return String(value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    function buildRemarkDisplay(data) {
        let parts = [];
        if (data.recheck_flag === '1') {
            parts.push('<span style="color:#409EFF;">二次核对</span>');
        }
        if (data.recheck_user) {
            parts.push('<span>' + escapeHtml(data.recheck_user) + '</span>');
        }
        return parts.join(' / ');
    }

    function updateRemark(id, remark, onSuccess) {
        let load = layer.load(1, {shade: [0.3, '#000']});
        $.ajax({
            url: '/medicalInsuranceReconciliation/updateMedicalInsuranceReconciliationRemark',
            type: 'POST',
            data: {id: id, remark: remark},
            success: function (data) {
                layer.close(load);
                if (data.code === 0) {
                    layer.msg('保存成功！', {icon: 1, time: 1500});
                    if (onSuccess) onSuccess();
                } else {
                    layer.alert('保存失败：' + (data.msg || ''), {icon: 2});
                }
            },
            error: function () {
                layer.close(load);
                layer.alert('保存失败，请检查网络连接！', {icon: 2});
            }
        });
    }

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

        //表格加载
        table.render({
            elem: '#demo',
            height: 'full-' + ($(".toolbar").height() + 60),
            url: '/medicalInsuranceReconciliation/findMedicalInsuranceReconciliationResult',
            title: '医保对账结果记录',
            page: true,//开启分页
            limit: 20,
            limits: [20, 30, 50],
            defaultToolbar: [],
            id: 'test',
            even: 'true',
            cols: [
                [
                    {type: 'numbers', title: '序号', width: 60},
                    {field: 'trade_date', title: '对账日期', align: 'center', width: 120},
                    {field: 'insutype', title: '险种类型', align: 'center', width: 100, templet: function(d){
                        if(d.insutype === '310') return '职工医保';
                        if(d.insutype === '340') return '新农合';
                        if(d.insutype === '390') return '居民医保';
                        if(d.insutype === '510') return '公务员补助';
                        if(d.insutype === '99410') return '工伤保险';
                        return d.insutype;
                    }},
                    {field: 'clr_type', title: '清算类别', align: 'center', width: 100, templet: function(d){
                        if(d.clr_type === '11') return '普通门诊';
                        if(d.clr_type === '21') return '住院';
                        if(d.clr_type === '31') return '门诊慢特病';
                        if(d.clr_type === '6101') return '门诊慢特病（高血压）';
                        if(d.clr_type === '6102') return '门诊慢特病（糖尿病）';
                        if(d.clr_type === '999913') return '居民门诊统筹';
                        if(d.clr_type === '999914') return '职工医保门诊共济';
                        if(d.clr_type === '999916') return '其他/非专项医疗费用';
                        return d.clr_type;
                    }},
                    {field: 'medfee_sumamt', title: '医疗费用总额', align: 'center', width: 130},
                    {field: 'fund_pay_sumamt', title: '基金支付总额', align: 'center', width: 130},
                    {field: 'acct_pay', title: '账户支付金额', align: 'center', width: 130},
                    {field: 'fixmedins_setl_cnt', title: '结算笔数', align: 'center', width: 100},
                    {field: 'recheck_user', title: '备注', align: 'center', width: 220, templet: function(d){
                        return buildRemarkDisplay(d);
                    }},
                    {field: 'stmt_rslt', title: '对账结果', align: 'center', width: 100, templet: function(d){
                        if(d.stmt_rslt === '0') {
                            return '<span style="color: green;">平</span>';
                        } else if(d.stmt_rslt === '1') {
                            return '<span style="color: red;">不平</span>';
                        } else {
                            return '<span style="color: orange;">异常</span>';
                        }
                    }},
                    {field: 'create_time', title: '创建时间', align: 'center', width: 160},
                    {title: '操作', align: 'center', width: 120, toolbar: '#barDemo', fixed: 'right'},
                ]
            ],
            done: function (res, curr, count) {
                // 表格加载完成后的回调
            }
        });

        //时间控件
        laydate.render({
            elem: '#searchDate',
            type: 'date',
            range: '~',
            done: function(value, date, endDate) {
                console.log("laydate选择完成:", value); // 调试日志
            }
        });

        // 表格工具栏事件
        table.on('tool(test)', function (obj) {
            let data = obj.data;

            if (obj.event === 'getInfo') {
                showDetail(data);
            }
            if (obj.event === 'editRemark') {
                layer.prompt({
                    title: '请输入备注',
                    formType: 2,
                    value: data.recheck_user || '',
                    btn: ['保存', '取消']
                }, function (value, index, elem) {
                    layer.close(index);
                    updateRemark(data.id, value, function () {
                        table.reload('test');
                    });
                });
            }
        });

        // 初始化：设置默认日期为前一天
        let yesterday = getYesterdayDate();
        console.log("初始化前一天日期:", yesterday); // 调试日志
        
        // 直接设置日期值
        $("#searchDate").val(yesterday + " ~ " + yesterday);
        
        // 确保DOM更新后再查询
        setTimeout(function() {
            let currentVal = $("#searchDate").val();
            console.log("延迟执行查询，当前日期输入框值:", currentVal);
            
            // 如果日期设置失败，强制设置
            if (!currentVal || currentVal.indexOf("~") === -1) {
                console.log("日期设置失败，强制重新设置");
                $("#searchDate").val(yesterday + " ~ " + yesterday);
            }
            
            search();
        }, 200);
    });

    // 查询
    function search(num) {
        num = num === null ? 1 : num;
        let url = "/medicalInsuranceReconciliation/findMedicalInsuranceReconciliationResult";
        let param = {};

        let date = $("#searchDate").val();
        console.log("搜索日期:", date); // 调试日志
        
        if (date !== '' && date.indexOf("~") > -1) {
            let time = date.split("~");
            let startDate = time[0].trim();
            let endDate = time[1].trim();

            param.startDate = startDate;
            param.endDate = endDate;

            console.log("日期参数:", param); // 调试日志
            $(".selectDate").text(startDate + " ~ " + endDate);
        } else if (date !== '' && date.indexOf("~") === -1) {
            // 如果只有一个日期，设置为当天
            param.startDate = date.trim();
            param.endDate = date.trim();
            console.log("单日期参数:", param); // 调试日志
            $(".selectDate").text(date + " ~ " + date);
        } else {
            // 如果没有日期，默认使用前一天
            let yesterday = getYesterdayDate();
            param.startDate = yesterday;
            param.endDate = yesterday;
            console.log("默认前一天参数:", param); // 调试日志
            $(".selectDate").text(yesterday + " ~ " + yesterday);
            // 同时更新输入框
            $("#searchDate").val(yesterday + " ~ " + yesterday);
        }
        
        // 确保至少有日期参数，防止查询所有数据
        if (!param.startDate || !param.endDate) {
            let yesterday = getYesterdayDate();
            param.startDate = yesterday;
            param.endDate = yesterday;
            console.log("强制设置前一天参数:", param); // 调试日志
        }

        let insutype = $("#insutype").val();
        if (insutype !== '') {
            param.insutype = insutype;
        }

        let clrType = $("#clrType").val();
        if (clrType !== '') {
            param.clrType = clrType;
        }

        let stmtRslt = $("#stmtRslt").val();
        if (stmtRslt !== '') {
            param.stmtRslt = stmtRslt;
        }

        table.reload('test', {
            method: 'get',
            url: url,
            where: param,
            page: {
                curr: num
            }
        });
    }

    // 执行医保对账
    function executeReconciliation() {
        layer.prompt({
            title: '请输入对账日期',
            formType: 0,
            value: getCurrentDate(),
            btn: ['确定', '取消']
        }, function(value, index, elem){
            layer.close(index);
            
            let load = layer.load(1, {shade: [0.3, '#000']});
            
            $.ajax({
                url: '/medicalInsuranceReconciliation/executeMedicalInsuranceReconciliation',
                type: 'POST',
                data: {
                    trade_date: value
                },
                success: function(data) {
                    layer.close(load);
                    if(data.code === 0) {
                        layer.msg('对账执行成功！', {icon: 1, time: 2000}, function(){
                            search();
                        });
                    } else {
                        layer.alert('对账执行失败：' + data.msg, {icon: 2});
                    }
                },
                error: function() {
                    layer.close(load);
                    layer.alert('对账执行失败，请检查网络连接！', {icon: 2});
                }
            });
        });
    }

    // 显示详情
    function showDetail(data) {
        currentDetailId = data.id || null;
        $("#detail_trade_date").text(data.trade_date || '-');
        
        let insutypeText = data.insutype;
        if(data.insutype === '310') insutypeText = '310-职工基本医疗保险';
        if(data.insutype === '340') insutypeText = '340-新农合';
        if(data.insutype === '390') insutypeText = '390-城乡居民基本医疗保险';
        if(data.insutype === '510') insutypeText = '510-公务员医疗补助';
        if(data.insutype === '99410') insutypeText = '99410-工伤保险';
        $("#detail_insutype").text(insutypeText || '-');
        
        let clrTypeText = data.clr_type;
        if(data.clr_type === '11') clrTypeText = '11-普通门诊';
        if(data.clr_type === '21') clrTypeText = '21-住院';
        if(data.clr_type === '31') clrTypeText = '31-门诊慢特病';
        if(data.clr_type === '6101') clrTypeText = '6101-门诊慢特病（高血压）';
        if(data.clr_type === '6102') clrTypeText = '6102-门诊慢特病（糖尿病）';
        if(data.clr_type === '999913') clrTypeText = '999913-居民门诊统筹';
        if(data.clr_type === '999914') clrTypeText = '999914-职工医保门诊共济';
        if(data.clr_type === '999916') clrTypeText = '999916-其他/非专项医疗费用';
        $("#detail_clr_type").text(clrTypeText || '-');
        
        $("#detail_medfee_sumamt").text(data.medfee_sumamt || '0.00');
        $("#detail_fund_pay_sumamt").text(data.fund_pay_sumamt || '0.00');
        $("#detail_acct_pay").text(data.acct_pay || '0.00');
        $("#detail_fixmedins_setl_cnt").text(data.fixmedins_setl_cnt || '0');
        
        let stmtRsltText = data.stmt_rslt === '0' ? '平' : (data.stmt_rslt === '1' ? '不平' : '异常');
        $("#detail_stmt_rslt").html('<span style="color: ' + (data.stmt_rslt === '0' ? 'green' : 'red') + ';">' + stmtRsltText + '</span>');
        
        $("#detail_stmt_rslt_dscr").text(data.stmt_rslt_dscr || '-');
        $("#detail_api_result").text(data.api_result || '-');
        $("#detail_remark_flag").html(data.recheck_flag === '1' ? '<span style="color:#409EFF;">二次核对</span>' : '');
        $("#detail_remark_input").val(data.recheck_user || '');
        $("#detail_create_time").text(data.create_time || '-');

        layer.open({
            type: 1,
            title: '医保对账详细信息',
            shade: 0.3,
            area: ['600px', '600px'],
            content: $("#detailDialog")
        });
    }

    function saveDetailRemark() {
        if (!currentDetailId) {
            layer.alert('缺少记录ID，无法保存备注', {icon: 2});
            return;
        }
        updateRemark(currentDetailId, $("#detail_remark_input").val() || '', function () {
            table.reload('test');
        });
    }

    // 导出
    function exportExcel() {
        let url = "/medicalInsuranceReconciliation/exportMedicalInsuranceReconciliationResult";
        let param = {};

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

        param.insutype = $("#insutype").val();
        param.clrType = $("#clrType").val();
        param.stmtRslt = $("#stmtRslt").val();

        let dowloadName = "医保对账结果";
        param.dowloadName = dowloadName;
        
        let load = layer.load();
        AjaxPostJson(url, param, function (data) {
            layer.close(load);
            if (data.errCode === "0") {
                let fileName = data.dlName;
                location.href = '/download?fileName=' + fileName + '&dowloadName=' + dowloadName;
            } else {
                layer.alert(data.errMsg);
            }
        });
    }

    // 获取当前日期（格式：yyyy-MM-dd）
    function getCurrentDate() {
        let date = new Date();
        let year = date.getFullYear();
        let month = String(date.getMonth() + 1).padStart(2, '0');
        let day = String(date.getDate()).padStart(2, '0');
        return year + '-' + month + '-' + day;
    }
    
    // 获取前一天日期（格式：yyyy-MM-dd）
    function getYesterdayDate() {
        let date = new Date();
        date.setDate(date.getDate() - 1); // 减一天
        let year = date.getFullYear();
        let month = String(date.getMonth() + 1).padStart(2, '0');
        let day = String(date.getDate()).padStart(2, '0');
        return year + '-' + month + '-' + day;
    }
</script>
</html>
