<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('主单列表')"/>
    <th:block th:include="include :: layout-latest-css"/>
    <th:block th:include="include :: ztree-css"/>
    <th:block th:include="include :: datetimepicker-css" />

    <style>
        #orderSearchBtnGroup {
            margin-top: 10px;
        }

        #allOrServing {
            width: 70px;
            padding: 6px 9px;
            height: 33px;
            font-size: 14px;
            border: 1px solid #e5e6e7;
            background: #fff none;
            border-radius: 4px;
            vertical-align: middle;
        }

        .flex-board {
            display: flex;
            flex-wrap: wrap;
            justify-content: flex-start;
            align-items: center;
        }

        .flex-board-no-wrap {
            display: flex;
            justify-content: flex-start;
            align-items: center;
        }

        .cx-select-input {
            width: 100px;
        }

        .normal-select-input {
            width: 100px;
        }

        .normal-input {
            width: 100px;
        }

        .long-input {
            width: 400px;
        }

        .active-condition-btn {
            background-color: #1c84c6;
            border-color: #1c84c6;
            color: #fff;
        }

        /* 表格滚动条样式 */
        .table-scroll-container {
            overflow-x: auto;
            overflow-y: auto;
            max-height: 600px;
        }

        .table-scroll-container::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        .table-scroll-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        .table-scroll-container::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }

        .table-scroll-container::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        /* 表格最小宽度 */
        #bootstrap-table {
            min-width: 1000px;
        }
    </style>
</head>
<body class="gray-bg">

<div class="ui-layout-center">
    <div class="container-div">
        <div class="row">
            <div class="col-sm-12 search-collapse">
                <form id="order-form" class="m">
                    <input type="hidden" id="deptId" name="deptId">
                    <input type="hidden" id="parentId" name="parentId">
                    <div class="condition-btn">
                        <select id="allOrServing">
                            <option value="">全部</option>
                            <option value="">在途</option>
                        </select>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '待付款', orderStatus: 0, sysPayStatus: 0, orderMode: '02'})">
                            待付款
                            (<span id="nonPaidOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '已发布', orderStatus: 0, workerId: -1})">
                            已发布
                            (<span id="publishedOrderNum">0</span>)
                        </a>
<!--                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatus: 1})">-->
<!--                            已接单-->
<!--                            (<span id="acceptedOrderNum">0</span>)-->
<!--                        </a>-->
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '待约单', orderStatus: 1, isCall: '01'})">
                            待约单
                            (<span id="notAppointedOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '待排期', orderStatus: 1, isCall: '02'})">
                            待排期
                            (<span id="notArrangedOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '待上门', orderStatus: 2})">
                            待上门
                            (<span id="waitForDoorOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '进行中', orderStatus: 3})">
                            进行中
                            (<span id="servingOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '确认审核', orderStatus: 4})">
                            确认审核
                            (<span class="confirmingOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '完成', orderStatus: 5})">
                            完成
                            (<span id="finishedOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '关闭', orderStatus: 6})">
                            关闭
                            (<span id="canceledOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectOnDoorOrderToday(this)">
                            今日待上门
                            (<span id="todayOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectOnDoorOrderTomorrow(this)">
                            明日待上门
                            (<span id="tomorrowOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '售后', searchAfterList: true})">
                            售后
                            (<span id="afterServiceOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '急报中', orderStatus: -1})">
                            急报中
                            (<span>0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '退单', orderStatus: -1})">
                            退单
                            (<span>0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '售后纠纷', orderStatus: -1})">
                            售后纠纷
                            (<span id="afterServiceDisputeNum">0</span>)
                        </a>
                    </div>
                    <div class="flex-board">
                        <div class="flex-board m-t">
                            区域筛选：
                            <div id="areaCxSelect" class="flex-board-no-wrap">
                                <select class="province form-control cx-select-input m-r" name="province" id="province" data-first-title="选择省" onchange="selectRegion('province', 'city')"></select>
                                <select class="city form-control cx-select-input m-r" name="city" id="city" data-first-title="选择市" onchange="selectRegion('city', 'district')"></select>
                                <select class="district form-control cx-select-input m-r" name="district" id="district" data-first-title="选择区" onchange="selectRegion('district', 'street')"></select>
                                <select class="street form-control cx-select-input m-r" name="streetId" id="streetId" data-first-title="选择街道" ></select>
                            </div>
                        </div>
                        <div class="flex-board m-t">
                            创建时间：
                            <div class="input-group date">
                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                <input id="createTimeStart" type="text" class="form-control date-input" placeholder="开始日期" readonly>
                            </div>
                            至
                            <div class="input-group date m-r">
                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                <input id="createTimeEnd" type="text" class="form-control date-input" placeholder="结束日期" readonly>
                            </div>
                        </div>
<!--                        <div class="flex-board m-t">-->
<!--                            服务时间：-->
<!--                            <div class="input-group date">-->
<!--                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>-->
<!--                                <input id="workBeginTimeStart" type="text" class="form-control date-input" placeholder="开始日期" readonly>-->
<!--                            </div>-->
<!--                            至-->
<!--                            <div class="input-group date m-r">-->
<!--                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>-->
<!--                                <input id="workBeginTimeEnd" type="text" class="form-control date-input" placeholder="结束日期" readonly>-->
<!--                            </div>-->
<!--                        </div>-->
<!--                        <div class="flex-board m-t">-->
<!--                            完成时间：-->
<!--                            <div class="input-group date">-->
<!--                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>-->
<!--                                <input id="workFinishTimeStart" type="text" class="form-control date-input" placeholder="开始日期" readonly>-->
<!--                            </div>-->
<!--                            至-->
<!--                            <div class="input-group date m-r">-->
<!--                                <span class="input-group-addon"><i class="fa fa-calendar"></i></span>-->
<!--                                <input id="workFinishTimeEnd" type="text" class="form-control date-input" placeholder="结束日期" readonly>-->
<!--                            </div>-->
<!--                        </div>-->
                        <div class="flex-board m-t">
                            类别筛选：
                            <div id="categoryCxSelect" class="flex-board-no-wrap">
                                <select class="category1 form-control cx-select-input m-r" name="category1" id="category1" data-first-title="选择一类"></select>
                                <select class="category2 form-control cx-select-input m-r" name="category2" id="category2" data-first-title="选择二类"></select>
                                <select class="category3 form-control cx-select-input m-r" name="category3" id="category3" data-first-title="选择三类"></select>
                                <select class="category4 form-control cx-select-input m-r" name="category4" id="category4" data-first-title="选择四类" ></select>
                            </div>
                        </div>
                        <!--                        <div class="flex-board-no-wrap m-t">-->
                        <!--                            <label class="form-control-label">后台人员：</label>-->
                        <!--                            <input type="text" class="form-control normal-input m-r">-->
                        <!--                        </div>-->
                        <div class="flex-board-no-wrap m-t">
                            <label class="form-control-label">商家名称：</label>
                            <input id="storeName" type="text" class="form-control normal-input m-r">
                        </div>
                        <div class="flex-board-no-wrap m-t">
                            <label class="form-control-label">商家电话：</label>
                            <input id="storePhone" type="text" class="form-control normal-input m-r">
                        </div>
                        <div class="flex-board-no-wrap m-t">
                            <label class="form-control-label">接单师傅名称：</label>
                            <input id="workerName" type="text" class="form-control normal-input m-r">
                        </div>
                        <div class="flex-board-no-wrap m-t">
                            <label class="form-control-label">接单师傅电话：</label>
                            <input id="workerPhone" type="text" class="form-control normal-input m-r">
                        </div>
                        <!--                        <div class="flex-board-no-wrap m-t">-->
                        <!--                            <label class="form-control-label">师傅类型：</label>-->
                        <!--                            <select class="form-control normal-select-input m-r">-->
                        <!--                                <option value="">全部</option>-->
                        <!--                                <option value="">大师傅</option>-->
                        <!--                                <option value="">小师傅</option>-->
                        <!--                            </select>-->
                        <!--                            <input type="text" class="form-control normal-input m-r" placeholder="师傅姓名电话">-->
                        <!--                        </div>-->
                        <div class="flex-board-no-wrap m-t">
                            <label class="form-control-label">订单模式：</label>
                            <select id="orderMode" class="form-control normal-select-input m-r" onchange="changeOrderMode(this.options[this.options.selectedIndex].value)">
                                <option value="0">全部</option>
                                <option value="B2B">B2B</option>
                                <option value="B2C">B2C</option>
                            </select>
                            <select id="B2BOptions" class="form-control normal-select-input m-r">
                                <option value="">全部</option>
                                <option value="">常规单</option>
                                <option value="">赠送单</option>
                                <option value="">合规单</option>
                            </select>
                            <select id="B2COptions" class="form-control normal-select-input m-r">
                                <option value="">全部</option>
                                <option value="">商品配件类目</option>
                                <option value="">服务类目</option>
                                <option value="">社区类目</option>
                            </select>
                        </div>
                        <div class="flex-board-no-wrap m-t">
                            <label class="form-control-label">订单标签：</label>
                            <select class="form-control normal-select-input m-r">
                                <option value="">全部</option>
                            </select>
                        </div>
                        <div class="flex-board-no-wrap m-t">
                            <label class="form-control-label">订单查询：</label>
                            <input id="keywords" type="text" class="form-control long-input m-r" placeholder="请输入订单号、姓名、电话">
                        </div>
                        <div class="m-t">
                            <a class="btn btn-primary btn-rounded btn-sm" onclick="searchByForm()"><i
                                class="fa fa-search"></i>&nbsp;搜索</a>
                            <a class="btn btn-warning btn-rounded btn-sm" onclick="resetForm()"><i
                                class="fa fa-refresh"></i>&nbsp;重置</a>
                        </div>
                    </div>
                    <div class="m-t condition-btn">
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatus: 0, workerId : -2})">
                            新订单
                            (<span id="newOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {timeout: 1, orderStatus: 0})">
                            接单超时
                            (<span id="newTimeoutOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {timeout: 1, orderStatus: 1, isCall: '01'})">
                            约单超时
                            (<span id="notAppointedTimeoutOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {timeout: 1, orderStatus: 1, isCall: '02'})">
                            排单超时
                            (<span id="notArrangedTimeoutOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatus: -1})">
                            无法排单
                            (<span>0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {timeout: 1, orderStatus: 2})">
                            待上门超时
                            (<span id="waitForDoorTimeoutOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {timeout: 1, orderStatus: 3})">
                            进行超时
                            (<span id="servingTimeoutOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatus: -1})">
                            售后超时
                            (<span>0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatus: -1})">
                            客诉中
                            (<span>0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatus: 4})">
                            审核中
                            (<span class="confirmingOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatus: -1})">
                            一票价未改价
                            (<span>0</span>)
                        </a>
                    </div>
                </form>
            </div>

            <div class="btn-group-sm" id="toolbar" role="group">
                <div class="btn-group-sm" role="group">
                    <a class="btn btn-warning" onclick="$.table.exportExcel()"
                       shiro:hasPermission="order:order:export">
                        <i class="fa fa-download"></i> 导出
                    </a>
                    <a class="btn btn-warning" onclick="$.table.importExcel()">
                        <i class="fa fa-download"></i> 导入
                    </a>
                    <a class="btn btn-default" onclick="mergePay()">
                        <i class="fa fa-money"></i> 付款
                    </a>
                    <a class="btn btn-default" onclick="showPcOrderWorker()">
                        <i class="fa fa-money"></i> 指派
                    </a>
                    <a class="btn btn-default" onclick="batchChangePrice()">
                        <i class="fa fa-money"></i> 批量改价
                    </a>
                    <a class="btn btn-default" onclick="batchChangeInsurance()">
                        <i class="fa fa-money"></i> 批量选择保险
                    </a>
                </div>
            </div>

            <div class="col-sm-12 select-table table-striped table-scroll-container">
                <table id="bootstrap-table"></table>
            </div>
        </div>
    </div>
</div>
<audio id="myAudio" src=""></audio>

<th:block th:include="include :: footer"/>
<th:block th:include="include :: layout-latest-js"/>
<th:block th:include="include :: ztree-js"/>
<th:block th:include="include :: jquery-cxselect-js" />
<th:block th:include="include :: datetimepicker-js" />
<script th:inline="javascript">
    var payTypes = [[${@dict.getType('pay_type')}]];
    var orderTypes = [[${@dict.getType('goods_category_type')}]];
    var orderModes = [[${@dict.getType('order_mode')}]];
    var payModes = [[${@dict.getType('pay_mode')}]];
    var payStatus = [[${@dict.getType('pay_status')}]];
    var orderStatus = [[${@dict.getType('order_status')}]];

    var editFlag = [[${@permission.hasPermi('order:order:edit')}]];
    var prefix = ctx + "order/master";
    var customParams = {};


    $(function () {
        var panehHidden = false;
        if ($(this).width() < 769) {
            panehHidden = true;
        }
        $('body').layout({initClosed: panehHidden, west__size: 185});
        // 回到顶部绑定
        if ($.fn.toTop !== undefined) {
            var opt = {
                win: $('.ui-layout-center'),
                doc: $('.ui-layout-center')
            };
            $('#scroll-up').toTop(opt);
        }
        initOrderList();

        $.ajax({
            type: "POST",
            dataType:"json",
            url: ctx + "system/area/list",
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#areaCxSelect').cxSelect({
                        selects: ['province', 'city', 'district', 'street'],
                        jsonValue: 'areaId',
                        jsonName: 'areaName',
                        data: result.data
                    });
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

        $(".date-input").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $.ajax({
            type: "POST",
            dataType:"json",
            url: ctx + "goods/deptcategory/app/list",
            data: JSON.stringify({deptId: 101, goodsCategoryId: 1}),
            contentType: 'application/json',
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#categoryCxSelect').cxSelect({
                        selects: ['category1', 'category2', 'category3', 'category4'],
                        jsonValue: 'deptGoodsCategoryId',
                        jsonName: 'goodsCategoryName',
                        jsonSub: 'child',
                        data: result.data
                    });
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

        changeOrderMode();

<!--        不同状态订单数量统计-->
        $.ajax({
            type: "GET",
            dataType:"json",
            url: prefix + '/differentStatus/count',
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#newOrderNum').text(result.data.newOrderNum);
                    $('#notAppointedOrderNum').text(result.data.notAppointedOrderNum);
                    $('#notArrangedOrderNum').text(result.data.notArrangedOrderNum);
                    $('#canceledOrderNum').text(result.data.canceledOrderNum);
                    $('.confirmingOrderNum').text(result.data.confirmingOrderNum);
                    $('#finishedOrderNum').text(result.data.finishedOrderNum);
                    $('#servingOrderNum').text(result.data.servingOrderNum);
                    $('#waitForDoorOrderNum').text(result.data.waitForDoorOrderNum);
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

        <!-- 不同状态超时订单数量统计-->
        $.ajax({
            type: "GET",
            dataType:"json",
            url: prefix + '/differentStatus/count',
            data: {timeout: 1},
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#newTimeoutOrderNum').text(result.data.newOrderNum);
                    $('#notAppointedTimeoutOrderNum').text(result.data.notAppointedOrderNum);
                    $('#notArrangedTimeoutOrderNum').text(result.data.notArrangedOrderNum);
                    $('#servingTimeoutOrderNum').text(result.data.servingOrderNum);
                    $('#waitForDoorTimeoutOrderNum').text(result.data.waitForDoorOrderNum);
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

<!--        待付款订单数量统计-->
        $.ajax({
            type: "GET",
            dataType:"json",
            url: prefix + '/count',
            data: {orderStatus: 0, sysPayStatus: 0, orderMode: '02'},
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#nonPaidOrderNum').text(result.data);
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

<!--        已发布订单数量统计-->
        $.ajax({
            type: "GET",
            dataType:"json",
            url: prefix + '/count',
            data: {orderStatus: 0, workerId: -1},
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#publishedOrderNum').text(result.data);
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

<!--        今日和明日单数量统计-->
        var date = new Date();
        $.ajax({
            type: "GET",
            dataType:"json",
            url: prefix + '/count',
            data: {
                orderStatus: 2,
                expectTimeStart: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + " 00:00:00",
                expectTimeEnd: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + " 23:59:59"
            },
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#todayOrderNum').text(result.data);
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })
        $.ajax({
            type: "GET",
            dataType:"json",
            url: prefix + '/count',
            data: {
                orderStatus: 2,
                expectTimeStart: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + (date.getDate() + 1) + " 00:00:00",
                expectTimeEnd: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + (date.getDate() + 1) + " 23:59:59"
            },
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#tomorrowOrderNum').text(result.data);
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

        <!-- 售后订单数量统计-->
        $.ajax({
            type: "POST",
            dataType:"json",
            url: prefix + '/after/count',
            contentType: 'application/json',
            data: JSON.stringify({}),
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#afterServiceOrderNum').text(result.data);
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

        <!-- 售后纠纷订单数量统计-->
        $.ajax({
            type: "POST",
            dataType:"json",
            url: prefix + '/after/dispute/count',
            contentType: 'application/json',
            data: JSON.stringify({}),
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#afterServiceDisputeNum').text(result.data);
                } else {
                    $.modal.msgError("售后纠纷数据加载错误，请重试！")
                }
            }
        })
    });

    function changeOrderMode(orderMode) {
        if (orderMode === 'B2B') {
            $("#B2BOptions").show();
            $("#B2COptions").hide();
        } else if (orderMode === 'B2C') {
            $("#B2BOptions").hide();
            $("#B2COptions").show();
        } else {
            $("#B2BOptions").hide();
            $("#B2COptions").hide();
        }
    }

    function showOrderWorker(id) {
        var url = "orderWorker/" + id;
        layer.open({
            type: 2,
            area: ['800px', '450px'],
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: '指派师傅',
            content: url,
            // 弹层外区域关闭
            shadeClose: true
        });
    }

    function showAssignWholeOrder(id) {
        var url = "assignWholeOrder/" + id;
        layer.open({
            type: 2,
            area: ['800px', '450px'],
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: '指派师傅',
            content: url,
            // 弹层外区域关闭
            shadeClose: true
        });
    }

    function selectRegion(regionLevelName, nextRegionLevelName) {
        var regionId = $("#" + regionLevelName).val();
        if ($.common.isEmpty(regionId)) {
            return;
        }

        //Ajax调用处理
        $.ajax({
            type: "POST",
            dataType:"json",
            url: ctx + "system/area/list",
            data: {parentCode: regionId},
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#areaCxSelect').cxSelect({
                        selects: [nextRegionLevelName],
                        jsonValue: 'areaId',
                        jsonName: 'areaName',
                        data: result.data
                    });
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })
    }

    function initOrderList() {
        var options = {
            url: prefix + "/list",
            exportUrl: prefix + "/export",
            importUrl: prefix + "/importData",
            queryParams: queryParams,
            sortName: "createTime",
            sortOrder: "desc",
            modalName: "订单",
            uniqueId: 'id',
            columns: [
                {
                    checkbox: true
                },
                {
                    title: "序号",
                    formatter: function (value, row, index) {
                        return $.table.serialNumber(index);
                    }
                },
                {
                    field: 'id',
                    title: '订单ID',
                    visible: false
                },
                {
                    field: 'goods',
                    title: '订单信息',
                    formatter: function (value, row) {
                        var imgUrl = (value && value.goodsImgUrl) ? value.goodsImgUrl : '';
                        return '<div style="display:flex;justify-content: center;align-items: center;">'
                            + '<img decoding="async" src="' + imgUrl + '" width="100" height="100" />'
                            + '<div>'
                            + '<p>' + (row.code || '') + '</p>'
                            + '<p>' + (row.consoleGoodsName || '') + '</p>'
                            + '<p>联系人：' + (row.addressName || '') + '</p>'
                            + '<p>联系电话：' + (row.addressPhone || '') + '</p>'
                            + '<p>联系地址：' + (row.address || '') + '</p>'
                            + '<p>下单时间：' + (row.createTime || '') + '</p>'
                            + '<p>预约时间：' + (row.mixExpectTime || '') + '</p>'
                            + '<p>下单总金额：' + (row.financialMasterMoney || '') + '元,师傅实收金额: ' + (row.financialMasterPayMoney || '') + '</p>'
                            + '</div>'
                            + '</div>';
                    }
                },
                {
                    field: 'orderStatus',
                    title: '订单状态',
                    align: 'center',
                    formatter: function (value, row, index) {
                        if(row.orderStatusName){
                            return row.orderStatusName;
                        }else {
                            return $.table.selectDictLabel(orderStatus, value);
                        }
                    }
                },
                {
                    title: '挂帐',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return statusTools(row);
                    }
                },
                {
                    title: '未派联系',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return contactTools(row);
                    }
                },
                {
                    field: 'worker',
                    title: '师傅接单信息',
                    formatter: function (value, row, index) {
                        if(value){
                            return '<p>' + value.name + value.phone + '</p>'
                                + '<p>接单时间：' + row.createTime + '</p>';
                        }
                    }
                },
                {
                    field: 'lastCallTime',
                    title: '最近联系时间'
                },
                {
                    title: '操作',
                    align: 'left',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="detail(\'' + row.id + '\')"><i class="fa fa-info"></i>查看</a> ');
                        actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="editServingInfo(\'' + row.id + '\')"><i class="fa fa-info"></i>修改</a> ');
                        actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="callDetail(\'' + row.id + '\')"><i class="fa fa-info"></i>拨号详情</a> ');
                        if(row.orderStatus == 0 || row.orderStatus == 1){
                            actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="orderMasterReject(\'' + row.id + '\')"></i>主单退单</a> ');
                            actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="orderMasterCancel(\'' + row.id + '\')"></i>商家退单</a> ');
                        }
                        if (row.workerId != null) {
                            actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="showOrderWorker(\'' + row.id + '\')"></i>指派</a> ');
                        } else {
                            actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="showAssignWholeOrder(\'' + row.id + '\')"></i>指派</a> ');
                        }
                        if (row.payStatus == 0) {
                            actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="showPayQrcode(\'' + row.id + '\')"></i>付款</a> ');
                        }
                        if (row.insuranceId){
                            actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)"></i>已投保险</a> ');
                        } else {
                            actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="pcOrderInsurance(\'' + row.id + '\')"></i>选择保险</a> ');
                        }
                        // 售后纠纷处理按钮
                        if (row.afterServiceStatus == 1) {
                            actions.push('<a class="btn btn-warning btn-xs" href="javascript:void(0)" onclick="handleAfterServiceDispute(\'' + row.id + '\')"><i class="fa fa-gavel"></i>售后纠纷处理</a> ');
                        }
                        return actions.join('');
                    }
                },
                {
                    field: 'goodsWorker',
                    title: '商家信息',
                    formatter: function (value, row, index) {
                        if(value){
                            return '<small>' + value.name + '</small><br>'
                                + '<small>' + value.phone + '</small>';
                        }
                    }
                },
                {
                    field: 'changeMoney',
                    title: '商家追加金额',
                    align: 'center'
                },
                {
                    field: 'orderImgs',
                    title: '完单图片',
                    align: 'center'
                },
                {
                    field: 'payMode',
                    title: '商家付费模式',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return $.table.selectDictLabel(payModes, value);
                    }
                },
                {
                    field: 'orderMode',
                    title: '下单模式',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return $.table.selectDictLabel(orderModes, value);
                    }
                },{
                    field: 'orderType',
                    title: '订单类型',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return $.table.selectDictLabel(orderTypes, value);
                    }
                },
                {
                    field: 'payType',
                    title: '付款类型',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return $.table.selectDictLabel(payTypes, value);
                    }
                },
                {
                    field: 'payStatus',
                    title: '付款状态',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return $.table.selectDictLabel(payStatus, value);
                    }
                },
                {
                    field: 'payTime',
                    title: '付款时间'
                },
                {
                    field: 'returnReason',
                    title: '退单原因',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return value || '-';
                    }
                },
                {
                    field: 'returnReasonDetail',
                    title: '退单原因详情',
                    align: 'center',
                    formatter: function (value, row, index) {
                        if (value && value.length > 20) {
                            return value.substring(0, 20) + '...';
                        }
                        return value || '-';
                    }
                },
                {
                    field: 'returnImages',
                    title: '退单图片',
                    align: 'center',
                    formatter: function (value, row, index) {
                        if (value) {
                            var images = value.split(',');
                            var html = '';
                            for (var i = 0; i < Math.min(images.length, 3); i++) {
                                html += '<img src="' + images[i] + '" style="width:30px;height:30px;margin:2px;" onclick="showImage(\'' + images[i] + '\')" />';
                            }
                            if (images.length > 3) {
                                html += '<span style="color:#999;">+' + (images.length - 3) + '</span>';
                            }
                            return html;
                        }
                        return '-';
                    }
                }]
        };
        $.table.init(options);
    }

    function statusTools(row) {
        if (row.isCharge === "01") {
            return '<i class=\"fa fa-toggle-off text-info fa-2x\" onclick="enable(\'' + row.id + '\')"></i> ';
        } else {
            return '<i class=\"fa fa-toggle-on text-info fa-2x\" onclick="disable(\'' + row.id + '\')"></i> ';
        }
    }

    /* 用户管理-停用 */
    function disable(orderId) {
        $.modal.confirm("确认要取消挂帐吗？", function() {
            $.operate.post(prefix + "/changeIsCharge", { "id": orderId, "isCharge": "01"});
        })
    }

    /* 用户管理启用 */
    function enable(orderId) {
        $.modal.confirm("确认要挂帐吗？", function() {
            $.operate.post(prefix + "/changeIsCharge", { "id": orderId, "isCharge": "02"});
        })
    }

    function contactTools(row) {
        if (row.isContact === "01") {
            return '<i class=\"fa fa-toggle-off text-info fa-2x\" onclick="contactEnable(\'' + row.id + '\')"></i> ';
        } else {
            return '<i class=\"fa fa-toggle-on text-info fa-2x\" onclick="contactDisable(\'' + row.id + '\')"></i> ';
        }
    }

    /* 用户管理-停用 */
    function contactDisable(orderId) {
        $.modal.confirm("确认未联系吗？", function() {
            $.operate.post(prefix + "/changeIsContact", { "id": orderId, "isContact": "01"});
        })
    }

    /* 用户管理启用 */
    function contactEnable(orderId) {
        $.modal.confirm("确认已联系吗？", function() {
            $.operate.post(prefix + "/changeIsContact", { "id": orderId, "isContact": "02"});
        })
    }

    function queryParams(params) {
        var search = $.table.queryParams(params);
        Object.assign(search, customParams)
        return search;
    }

    function detail(id) {
        var url = "order/goods/master?orderId=" + id;
        $.modal.open("商品信息", url);
    }

    function editServingInfo(id) {
        let url = "order/popup/editServingInfo?orderId=" + id + "&pageCode=orderManager";
        $.modal.open("信息修改", url);
    }

    function callDetail(id) {
        var url = "order/record?orderId=" + id;
        $.modal.open("拨号记录", url);
    }

    function orderDetailReject(id) {
        $.modal.confirm("确定要退单吗？", function() {
            const url = "detail/reject";
            const data = { "id": id };
            $.operate.post(url, data);
        });
    }
    // function orderMasterReject(id) {
    //     $.modal.confirm("确定要退单吗？", function() {
    //         const url = "master/reject";
    //         const data = { "id": id };
    //         $.operate.post(url, data);
    //     });
    // }

    // 商家退单
    function orderMasterCancel(id){
        $.modal.confirm("确定要取消订单吗？", function() {
            const url = "cancel";
            const data = { "orderMasterId": id };
            $.operate.post(url, data);
        });
    }

    function orderMasterReject(id) {
    $.modal.confirm("确定要退单吗？", function() {
        const url = "console/cancel";
        const data = { "id": id };
        $.ajax({
            type: "POST",
            dataType: "json",
            url: url,
            data: JSON.stringify(data),
            contentType: 'application/json',
            success: function (result) {
                $.operate.ajaxSuccess(result);
            }
        });
    });
}

    function changeConditionBtnChosenStyle(e) {
        $('.condition-btn .btn').removeClass('active-condition-btn');
        $(e).addClass('active-condition-btn');
    }

    function selectConditionBtn(e, params = {}) {
        changeConditionBtnChosenStyle(e);
        searchOrderList(params)
    }

    function selectOnDoorOrderToday(e) {
        changeConditionBtnChosenStyle(e);
        var date = new Date();
        selectConditionBtn(e, {
            orderStatus: 2,
            expectTimeStart: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + " 00:00:00",
            expectTimeEnd: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + " 23:59:59"
        })
    }

    function selectOnDoorOrderTomorrow(e) {
        changeConditionBtnChosenStyle(e);
        var date = new Date();
        selectConditionBtn(e, {
            orderStatus: 2,
            expectTimeStart: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + (date.getDate() + 1) + " 00:00:00",
            expectTimeEnd: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + (date.getDate() + 1) + " 23:59:59"
        })
    }

    function searchOrderList(params) {
        customParams = params;
        $.table.search();
    }

    function searchByForm() {
        let params = {
            createTimeStart: $('#createTimeStart').val() ? $('#createTimeStart').val() + " 00:00:00" : undefined,
            createTimeEnd: $('#createTimeEnd').val() ? $('#createTimeEnd').val() + " 23:59:59" : undefined,
<!--            workBeginTimeStart: $('#workBeginTimeStart').val(),-->
<!--            workBeginTimeEnd: $('#workBeginTimeEnd').val() ? $('#workBeginTimeEnd').val() + " 23:59:59" : undefined,-->
<!--            workFinishTimeStart: $('#workFinishTimeStart').val(),-->
<!--            workFinishTimeEnd: $('#workFinishTimeEnd').val() ? $('#workFinishTimeEnd').val() + " 23:59:59" : undefined,-->
            storeName: $('#storeName').val(),
            storePhone: $('#storePhone').val(),
            workerName: $('#workerName').val(),
            workerPhone: $('#workerPhone').val(),
            keywords: $('#keywords').val()
        }

        customParams = Object.assign(customParams, params);
        $.table.search();
    }

    function resetForm() {
        $.form.reset();
        customParams = {};
        changeConditionBtnChosenStyle();
        $.table.search();
    }

    function showPayQrcode(id) {
        var url = "payQrcode/" + id;
        <!--        $.modal.open("支付二维码", url, 290, 360);-->
        layer.open({
            type: 2,
            area: ['290px', '360px'],
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: '支付二维码',
            content: url,
            btn: ['关闭'],
            // 弹层外区域关闭
            shadeClose: true,
            cancel: function(index) {
                return true;
            }
        });
    }

    function showPcOrderWorker() {
        table.set();
        var rows = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);
        if (rows.length === 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        var url = "pcOrderWorker/" + rows.join(",");
        layer.open({
            type: 2,
            area: ['800px', '450px'],
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: '指派师傅',
            content: url,
            // 弹层外区域关闭
            shadeClose: true
        });
    }


    function pcOrderInsurance(id) {
        var url = ctx + "order/master/pcOrderInsurance/" + id;
        $.modal.open("选择保险", url, '600', '300');
    }

    function batchChangePrice() {
        table.set();
        var rows = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);
        if (rows.length === 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        var url = prefix + "/changePrice/" + rows.join(",");
        $.modal.open("批量改价", url, '800', '300');
    }

    function batchChangeInsurance() {
        table.set();
        var rows = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);
        if (rows.length === 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        var url = ctx + "order/master/batchChangeInsurance/" + rows.join(",");
        $.modal.open("批量选择保险", url, '600', '300');
    }

    function mergePay() {
        table.set();
        var rows = $.common.isEmpty(table.options.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns(table.options.uniqueId);
        if (rows.length == 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        showPayQrcode(rows.join());
    }

    // 显示退单图片
    function showImage(imageUrl) {
        if (!imageUrl) {
            return;
        }
        
        var html = '<div style="text-align:center;">' +
                   '<img src="' + imageUrl + '" style="max-width:100%;max-height:500px;" />' +
                   '</div>';
        
        layer.open({
            type: 1,
            title: '退单图片',
            area: ['600px', '500px'],
            content: html,
            shadeClose: true,
            btn: ['关闭']
        });
    }

    // 主订单全部
    var orderMasterHaveReleasedUrl = "";
    // 主订单新订单
    var orderMasterNewOrderUrl = "";

    //请求接口加载页面输入框值
    function globalConfiginit(){
        $.ajax({
            type: "GET",
            dataType:"json",
            url: "/config/globalConfig/search/type/1001",
            data: { },
            success: function (data) {
                var response = JSON.parse(data.data.content);
                orderMasterHaveReleasedUrl = response.orderMasterHaveReleasedUrl;
                orderMasterNewOrderUrl = response.orderMasterNewOrderUrl;
            }
        })
    }

    //页面加载
    window.onload = function () {
        //请求接口加载页面输入框值
        globalConfiginit();
    }

    // 定义一个要延迟执行的函数
    function delayedFunction() {
        console.log("");
    }

    var totalOrderNumber = 0;
    var finishCheckNumber = 0;
    var lastTotalOrderNumber = 0;
    var lastFinishCheckNumber = 0;

    function fetchData() {
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "/order/master/statistics/now",
            data: {},
            success: function (data) {
                // 更新当前值
                totalOrderNumber = data.data.totalOrderNumber;
                finishCheckNumber = data.data.finishCheckNumber;
                console.log(totalOrderNumber+"-----"+lastTotalOrderNumber );
                // 检查新值是否大于旧值
                if (totalOrderNumber > lastTotalOrderNumber) {
                    console.log("收到新总订单数据，开始播放。播放通知音频：" + orderMasterHaveReleasedUrl);
                    // 获取source元素
                    var source = document.getElementById('myAudio');
                    // 设置新的音频文件路径
                    source.src = orderMasterHaveReleasedUrl;
                    var audio = document.getElementById('myAudio');
                    audio.play().catch(function(error) {
                        console.log('播放失败：', error);
                    });
                }

                // 设置延迟时间为2000毫秒（2秒）
                setTimeout(delayedFunction, 2000);

                if (finishCheckNumber > lastFinishCheckNumber) {
                    console.log("收到新订单数据，开始播放。播放通知音频：" + orderMasterNewOrderUrl);
                    // 获取source元素
                    var source = document.getElementById('myAudio');
                    // 设置新的音频文件路径
                    source.src = orderMasterNewOrderUrl;
                    var audio = document.getElementById('myAudio');
                    audio.play().catch(function(error) {
                        console.log('播放失败：', error);
                    });
                }

                // 更新上一次的值
                lastTotalOrderNumber = totalOrderNumber;
                lastFinishCheckNumber = finishCheckNumber;
            }
        });
    }




    // 设置定时器，每隔一分钟执行一次 fetchData 函数
    setInterval(fetchData, 60000);

    // 售后纠纷处理弹窗
    function handleAfterServiceDispute(orderMasterId) {
        // 查询该主单的售后记录
        $.ajax({
            type: "POST",
            dataType: "json",
            url: prefix + '/after/records/byMasterId',
            contentType: 'application/json',
            data: JSON.stringify({id: orderMasterId}),
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    showAfterServiceDisputeModal(orderMasterId, result.data);
                } else {
                    $.modal.msgError("查询售后记录失败：" + result.msg);
                }
            },
            error: function() {
                $.modal.msgError("查询售后记录失败，请重试！");
            }
        });
    }

    // 获取订单详情信息
    function getOrderDetailInfo(orderMasterId, callback) {
        $.ajax({
            type: "POST",
            dataType: "json",
            url: prefix + "/app/detail",
            contentType: "application/json",
            data: JSON.stringify({id: orderMasterId}),
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    callback(result.data);
                } else {
                    $.modal.msgError("获取订单详情失败：" + result.msg);
                }
            },
            error: function() {
                $.modal.msgError("获取订单详情失败，请重试！");
            }
        });
    }

    // 获取师傅同意类型文本
    function getWorkerAgreeTypeText(type) {
        var types = {
            1: '同意',
            2: '不同意',
            3: '部分同意'
        };
        return types[type] || '未处理';
    }

    // 显示售后纠纷处理弹窗
    function showAfterServiceDisputeModal(orderMasterId, afterServiceRecords) {
        // 先获取订单详情以判断订单类型
        getOrderDetailInfo(orderMasterId, function(orderDetail) {
            showDisputeModalWithOrderInfo(orderMasterId, afterServiceRecords, orderDetail);
        });
    }

    // 根据订单信息显示售后纠纷处理弹窗
    function showDisputeModalWithOrderInfo(orderMasterId, afterServiceRecords, orderDetail) {
        var isGoodsOrder = orderDetail && orderDetail.orderType === 1;
        
        var html = '<div class="modal fade" id="afterServiceDisputeModal" tabindex="-1" role="dialog">';
        html += '<div class="modal-dialog modal-lg" role="document">';
        html += '<div class="modal-content">';
        html += '<div class="modal-header">';
        html += '<h4 class="modal-title">售后纠纷处理</h4>';
        html += '<button type="button" class="close" data-dismiss="modal">&times;</button>';
        html += '</div>';
        html += '<div class="modal-body">';
        
        if (afterServiceRecords && afterServiceRecords.length > 0) {
            html += '<div class="table-responsive">';
            html += '<table class="table table-bordered table-striped">';
            // 根据订单类型决定表头
            if (isGoodsOrder) {
                html += '<thead><tr><th>子单号</th><th>申请退款金额</th><th>师傅反馈</th><th>师傅同意类型</th><th>客户确认</th><th>操作</th></tr></thead>';
            } else {
                html += '<thead><tr><th>子单号</th><th>申请退款金额</th><th>师傅反馈</th><th>客户确认</th><th>操作</th></tr></thead>';
            }
            html += '<tbody>';
            
            afterServiceRecords.forEach(function(record) {
                html += '<tr>';
                html += '<td>' + (record.orderDetailCode || '') + '</td>';
                html += '<td>¥' + (record.refund || record.agreedRefund || 0) + '</td>';
                html += '<td>' + getWorkerFeedbackText(record.workerFeedbackResult) + '<br><small style="color: #999;">反馈金额：¥' + (record.agreedRefund || 0) + '</small></td>';
                // 如果是商品订单，添加师傅同意类型列
                if (isGoodsOrder) {
                    html += '<td>' + getWorkerAgreeTypeText(record.workerAgreeType) + '</td>';
                }
                html += '<td>' + getCustomerCheckText(record.customerFinalCheck) + '</td>';
                html += '<td style="width: 280px;">';
                html += '<div style="margin-bottom: 8px;">';
                html += '<label style="font-size: 12px; color: #666; margin-bottom: 2px; display: block;">退款金额：</label>';
                html += '<input type="number" class="form-control" id="refundAmount_' + record.id + '" placeholder="输入退款金额" value="' + (record.refund || 0) + '" style="width: 100%; font-size: 12px; height: 28px;" min="0" step="0.01">';
                html += '</div>';
                html += '<div style="margin-bottom: 8px;">';
                html += '<label style="font-size: 12px; color: #666; margin-bottom: 2px; display: block;">处理原因：</label>';
                html += '<input type="text" class="form-control" id="processReason_' + record.id + '" placeholder="请输入处理原因" style="width: 100%; font-size: 12px; height: 28px;">';
                html += '</div>';
                html += '<button class="btn btn-primary btn-xs" onclick="processRefund(\'' + record.id + '\', \'' + orderMasterId + '\')" style="width: 100%; font-size: 12px; height: 28px;">处理退款</button>';
                html += '<button class="btn btn-warning btn-xs" onclick="cancelAfterService(\'' + record.id + '\', \'' + orderMasterId + '\')" style="width: 100%; font-size: 12px; height: 28px; margin-top: 4px;">取消售后</button>';
                html += '</td>';
                html += '</tr>';
            });
            
            html += '</tbody></table></div>';
            
            // 如果是商品订单，添加提示文字
            if (isGoodsOrder) {
                html += '<div class="alert alert-warning" style="margin-top: 15px;">';
                html += '<strong>提示：</strong>商品退款需确认是否存在退货，并确认退完与否再操作退款！同时确认子单款项金额是否符合退款要求！';
                html += '</div>';
            }
        } else {
            html += '<div class="alert alert-info">该订单暂无售后纠纷记录</div>';
        }
        
        html += '</div>';
        html += '<div class="modal-footer">';
        html += '<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>';
        html += '</div>';
        html += '</div></div></div>';
        
        // 移除已存在的弹窗
        $('#afterServiceDisputeModal').remove();
        
        // 添加弹窗到页面
        $('body').append(html);
        
        // 显示弹窗
        $('#afterServiceDisputeModal').modal('show');
    }

    // 处理退款
    function processRefund(recordId, orderMasterId) {
        var refundAmount = $('#refundAmount_' + recordId).val();
        var processReason = $('#processReason_' + recordId).val();
        
        if (!refundAmount || refundAmount <= 0) {
            $.modal.msgError("请输入有效的退款金额");
            return;
        }
        
        if (!processReason || processReason.trim() === '') {
            $.modal.msgError("请输入处理原因");
            return;
        }
        
        $.modal.confirm("确认处理退款 ¥" + refundAmount + " 吗？", function() {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: prefix + '/after/dispute/handle',
                contentType: 'application/json',
                data: JSON.stringify({
                    recordId: recordId,
                    orderMasterId: orderMasterId,
                    refundAmount: parseFloat(refundAmount),
                    platformHandleReason: processReason.trim()
                }),
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msgSuccess("退款处理成功");
                        $('#afterServiceDisputeModal').modal('hide');
                        // 刷新页面数据
                        $.table.refresh();
                    } else {
                        $.modal.msgError("退款处理失败：" + result.msg);
                    }
                },
                error: function() {
                    $.modal.msgError("退款处理失败，请重试！");
                }
            });
        });
    }

    // 取消售后
    function cancelAfterService(recordId, orderMasterId) {
        // 获取处理原因输入框的值
        var processReason = $('#processReason_' + recordId).val();
        
        if (!processReason || processReason.trim() === '') {
            $.modal.msgError("请输入处理原因");
            return;
        }
        
        $.modal.confirm("确认取消该售后申请吗？", function() {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: prefix + '/after/cancel',
                data: {
                    afterServiceRecordId: recordId,
                    platformHandleReason: processReason.trim()
                },
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msgSuccess("取消售后成功");
                        $('#afterServiceDisputeModal').modal('hide');
                        // 刷新页面数据
                        $.table.refresh();
                    } else {
                        $.modal.msgError("取消售后失败：" + result.msg);
                    }
                },
                error: function() {
                    $.modal.msgError("取消售后失败，请重试！");
                }
            });
        });
    }

    // 获取售后类型文本
    function getAfterServiceTypeText(type) {
        var types = {
            1: '未收到货退单退款',
            2: '未收到货退款',
            3: '已收到货退款退货'
        };
        return types[type] || '未知';
    }

    // 获取师傅反馈文本
    function getWorkerFeedbackText(result) {
        var results = {
            0: '拒绝',
            1: '同意',
            2: '上门补做/重做',
            3: '重做/补做完成'
        };
        return results[result] || '未处理';
    }

    // 获取客户确认文本
    function getCustomerCheckText(check) {
        if (check === 1) return '同意';
        if (check === 0) return '不同意';
        return '未确认';
    }

</script>
</body>
<script id="importTpl" type="text/template">
    <form enctype="multipart/form-data" class="mt20 mb10">
        <div class="col-xs-offset-1">
            <input type="file" id="file" name="file"/>
            <div class="mt10 pt5">
                <input type="checkbox" id="updateSupport" name="updateSupport" title="如果登录账户已经存在，更新这条数据。"> 是否更新已经存在的用户数据
                &nbsp;	<a href="http://gqz.opsoul.com/%E6%89%B9%E9%87%8F%E4%B8%8B%E5%8D%95%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls" class="btn btn-default btn-xs"><i class="fa fa-file-excel-o"></i> 下载模板</a>
            </div>
            <font color="red" class="pull-left mt10">
                提示：仅允许导入“xls”或“xlsx”格式文件！
            </font>
        </div>
    </form>
</script>
</html>
