<!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;
        }
    </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">
                    <input type="hidden" id="orderStatus" name="orderStatus"/>
                    <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 : '待付款', sysPayStatus: 0})">
                            待付款
                            (<span id="nonPaidOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '待约单', orderStatus: 1, isCall : '01'})">
                            待约单
                            (<span id="notCallOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {orderStatusName : '待排期', orderStatus: 1, isCall : '02'})">
                            待排期
                            (<span id="notSetTimeOrderNum">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})">
                            新订单
                            (<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="acceptedTimeoutOrderNum">0</span>)
                        </a>
                        <a class="btn btn-default btn-outline" onclick="selectConditionBtn(this, {timeout: 1, orderStatus: 1, isCall: '02'})">
                            排单超时
                            (<span id="plainTimeoutOrderNum">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-default" onclick="$.table.exportExcel()">-->
<!--                        <i class="fa fa-download"></i> 指派-->
<!--                    </a>-->
                </div>
            </div>

            <div class="col-sm-12 select-table table-striped">
                <table id="bootstrap-table"></table>
            </div>
        </div>
    </div>
</div>

<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 payStatus = [[${@dict.getType('pay_status')}]];
    var orderStatus = [[${@dict.getType('order_status')}]];

    var editFlag = [[${@permission.hasPermi('order:order:edit')}]];
    var prefix = ctx + "order/detail";
    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);
        }
        queryOrderList();

        $.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);
                    $('#acceptedOrderNum').text(result.data.acceptedOrderNum);
                    $('#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",
            data: {isCall: '01'},
            url: prefix + '/differentStatus/count',
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#notCallOrderNum').text(result.data.acceptedOrderNum);
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

        $.ajax({
            type: "GET",
            dataType:"json",
            data: {isCall: '02'},
            url: prefix + '/differentStatus/count',
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#notSetTimeOrderNum').text(result.data.acceptedOrderNum);
                } 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);
                    $('#servingTimeoutOrderNum').text(result.data.servingOrderNum);
                    $('#waitForDoorTimeoutOrderNum').text(result.data.waitForDoorOrderNum);
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

        $.ajax({
            type: "GET",
            dataType:"json",
            url: prefix + '/differentStatus/count',
            data: {timeout: 1, isCall : '01'},
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#acceptedTimeoutOrderNum').text(result.data.acceptedOrderNum);
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

        $.ajax({
            type: "GET",
            dataType:"json",
            url: prefix + '/differentStatus/count',
            data: {timeout: 1, isCall : '02'},
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#plainTimeoutOrderNum').text(result.data.acceptedOrderNum);
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

        $.ajax({
            type: "GET",
            dataType:"json",
            url: prefix + '/count',
            data: {sysPayStatus: 0},
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#nonPaidOrderNum').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: "GET",
            dataType:"json",
            url: prefix + '/after/count',
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $('#afterServiceOrderNum').text(result.data);
                } else {
                    $.modal.msgError("数据加载错误，请重试！")
                }
            }
        })

        // 售后纠纷数量统计
        $.ajax({
            type: "GET",
            dataType:"json",
            url: prefix + '/after/dispute/count',
            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 = "order/detail/orderWorker/" + id;
        $.modal.open("指派师傅", url, '800', '300');
    }

    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 queryOrderList() {
        var options = {
            url: prefix + "/list",
            exportUrl: prefix + "/export",
            queryParams: queryParams,
            sortName: "createTime",
            sortOrder: "desc",
            modalName: "订单",
            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) {
                        return '<div style="display:flex;justify-content: center;align-items: center;">'
                            + '<img decoding="async" src="' + value.goodsImgUrl + '" 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.financialDetailMoney + '元</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);
                        }
                    }
                },
                {
                    field: 'goodsWorker',
                    title: '师傅接单信息',
                    formatter: function (value, row, index) {
                        if(value){
                            return '<p>' + value.name + '</p>'
                                + '<p>' + value.phone + '</p>';
                        }
                    }
                },
                {
                    field: 'worker',
                    title: '师傅做单信息',
                    formatter: function (value, row, index) {
                        if(value){
                            return '<p>' + value.name + value.phone + '</p>'
                                + '<p>接单时间：' + value.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="callDetail(\'' + row.orderMasterId + '\')"><i class="fa fa-info"></i>拨号详情</a> ');
                        actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="orderDetailReject(\'' + row.id + '\')"></i>师傅退单</a> ');
                        // actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="orderMasterReject(\'' + row.orderMasterId + '\')"></i>商家退单</a> ');
                       // actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="showOrderWorker(\'' + 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.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: 'changeMoney',
                    title: '商家追加金额',
                    align: 'center'
                },
                {
                    field: 'orderImgs',
                    title: '完单图片'
                },
                {
                    field: 'orderImages',
                    title: '下单图片',
                    align: 'center',
                    formatter: function (value, row, index) {
                        if (value && value.trim() !== '') {
                            return '<img src="' + value + '" style="width: 50px; height: 50px; object-fit: cover;" onclick="showImagePreview(\'' + value + '\')">';
                        }
                        return '-';
                    }
                },
                {
                    field: 'isDeliveryToStore',
                    title: '是否发货到服务店',
                    align: 'center',
                    formatter: function (value, row, index) {
                        if (value === 1) {
                            return '<span class="label label-success">是</span>';
                        } else {
                            return '<span class="label label-default">否</span>';
                        }
                    }
                },
                {
                    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: '付款时间'
                }]
        };
        $.table.init(options);
    }

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

    function detail(id) {
        var url = "order/goods?orderId=" + id;
        $.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 changeConditionBtnChosenStyle(e) {
        $('.condition-btn .btn').removeClass('active-condition-btn');
        if (e) {
            $(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 = "detail/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;
            }
        });
    }

    // 子订单全部
    var orderDetailsAfterUrl = "";
    // 子订单新订单
    var orderDetailsAfterSalesDisputeUrl = "";

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

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

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

    var totalOrderNumber = 0;
    var inServiceNumber = 0;
    var lastTotalOrderNumber = 0;
    var lastInServiceNumber = 0;

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

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

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

                // 更新上一次的值
                lastTotalOrderNumber = totalOrderNumber;
                lastInServiceNumber = inServiceNumber;
            }
        });
    }

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

    // 图片预览功能
    function showImagePreview(imageUrl) {
        if (!imageUrl || imageUrl.trim() === '') {
            $.modal.msgError("图片地址不能为空");
            return;
        }
        
        layer.open({
            type: 1,
            title: '图片预览',
            shadeClose: true,
            shade: 0.8,
            area: ['auto', 'auto'],
            content: '<div style="text-align: center; padding: 20px;"><img src="' + imageUrl + '" style="max-width: 800px; max-height: 600px; object-fit: contain;" /></div>'
        });
    }

    // 售后纠纷处理
    function handleAfterServiceDispute(orderDetailId) {
        if (!orderDetailId) {
            $.modal.msgError("子单ID不能为空");
            return;
        }
        
        // 查询该子单的售后纠纷记录
        $.ajax({
            type: "POST",
            dataType: "json",
            url: prefix + "/after/records/byDetailId",
            data: {orderDetailId: orderDetailId},
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    showAfterServiceDisputeModal(orderDetailId, result.data);
                } else {
                    $.modal.msgError("查询售后纠纷记录失败：" + result.msg);
                }
            },
            error: function () {
                $.modal.msgError("查询售后纠纷记录失败，请重试");
            }
        });
    }

    // 显示售后纠纷处理弹窗
    function showAfterServiceDisputeModal(orderDetailId, disputeRecords) {
        if (!disputeRecords || disputeRecords.length === 0) {
            $.modal.msgError("没有找到售后纠纷记录");
            return;
        }

        // 直接获取订单详情来判断订单类型
        getOrderDetailInfo(orderDetailId, function(orderDetail) {
            showDisputeModalWithOrderInfo(orderDetailId, disputeRecords, orderDetail);
        });
    }

    // 获取订单详情信息
    function getOrderDetailInfo(orderDetailId, callback) {
        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json",
            url: prefix + "/app/detail",
            data: JSON.stringify({id: orderDetailId}),
            success: function(result) {
                if (result.code == web_status.SUCCESS) {
                    callback(result.data);
                } else {
                    callback(null);
                }
            },
            error: function() {
                callback(null);
            }
        });
    }

    // 根据订单信息显示售后纠纷处理弹窗
    function showDisputeModalWithOrderInfo(orderDetailId, disputeRecords, orderDetail) {
        var isGoodsOrder = orderDetail && orderDetail.orderType === 1; // 1表示商品订单

        var modalContent = '<div class="modal-body">';
        modalContent += '<div class="table-responsive">';
        modalContent += '<table class="table table-bordered table-striped">';
        modalContent += '<thead><tr>';
        modalContent += '<th>子单号</th>';
        modalContent += '<th>申请退款金额</th>';
        modalContent += '<th>师傅反馈</th>';
        modalContent += '<th>客户确认</th>';
        modalContent += '<th style="width: 280px;">操作</th>';
        modalContent += '</tr></thead><tbody>';

        disputeRecords.forEach(function(record) {
            modalContent += '<tr>';
            modalContent += '<td>' + (record.orderDetailCode || record.id) + '</td>';
            modalContent += '<td>¥' + (record.refund || record.agreedRefund || 0) + '</td>';
            
            // 师傅反馈列 - 如果是商品订单则增加workerAgreeType显示
            var workerFeedbackContent = getWorkerFeedbackText(record.workerFeedbackResult) + '<br/><span style="color: #666; font-size: 12px;">反馈金额：¥' + (record.agreedRefund || 0) + '</span>';
            if (isGoodsOrder && record.workerAgreeType) {
                workerFeedbackContent += '<br/><span style="color: #007bff; font-size: 12px;">处理方式：' + getWorkerAgreeTypeText(record.workerAgreeType) + '</span>';
            }
            modalContent += '<td>' + workerFeedbackContent + '</td>';
            
            modalContent += '<td>' + getCustomerCheckText(record.customerFinalCheck) + '</td>';
            modalContent += '<td>';
            modalContent += '<div style="margin-bottom: 8px;">';
            modalContent += '<label style="font-size: 12px; color: #666; margin-bottom: 2px; display: block;">退款金额：</label>';
            modalContent += '<input type="number" class="form-control" id="refundAmount_' + record.id + '" placeholder="输入退款金额" value="' + (record.agreedRefund || 0) + '" style="width: 100%; font-size: 12px; height: 28px;">';
            modalContent += '</div>';
            modalContent += '<div style="margin-bottom: 8px;">';
            modalContent += '<label style="font-size: 12px; color: #666; margin-bottom: 2px; display: block;">处理原因：</label>';
            modalContent += '<input type="text" class="form-control" id="processReason_' + record.id + '" placeholder="请输入处理原因" style="width: 100%; font-size: 12px; height: 28px;">';
            modalContent += '</div>';
            modalContent += '<button class="btn btn-primary btn-xs" onclick="processRefund(' + record.id + ', ' + orderDetailId + ')" style="width: 100%; font-size: 12px; height: 28px;">处理退款</button>';
            modalContent += '<button class="btn btn-warning btn-xs" onclick="cancelAfterService(' + record.id + ', ' + orderDetailId + ')" style="width: 100%; font-size: 12px; height: 28px; margin-top: 4px;">取消售后</button>';
            modalContent += '</td>';
            modalContent += '</tr>';
        });

        modalContent += '</tbody></table>';
        
        // 如果是商品订单，在表格下方增加提示文字
        if (isGoodsOrder) {
            modalContent += '<div style="margin-top: 15px; padding: 10px; background-color: #fff3cd; border: 1px solid #ffeaa7; border-radius: 4px;">';
            modalContent += '<i class="fa fa-exclamation-triangle" style="color: #856404; margin-right: 5px;"></i>';
            modalContent += '<span style="color: #856404; font-weight: bold;">商品退款需确认是否存在退货，并确认退完与否再操作退款！同时确认子单款项金额是否符合退款要求！</span>';
            modalContent += '</div>';
        }
        
        modalContent += '</div>';
        modalContent += '</div>';

        layer.open({
            type: 1,
            title: '售后纠纷处理 - 子单ID: ' + orderDetailId,
            shadeClose: true,
            shade: 0.8,
            area: ['90%', '80%'],
            content: modalContent
        });
    }

    // 获取师傅同意处理方式文本
    function getWorkerAgreeTypeText(type) {
        var typeMap = {
            1: '即时退单退款',
            2: '货物拦截后退单退款',
            3: '快递返回货物后退单退款',
            4: '退回货物后退单退款'
        };
        return typeMap[type] || '未知';
    }

    // 处理退款
    function processRefund(recordId, orderDetailId) {
        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("确认处理退款吗？<br/>退款金额：¥" + refundAmount + "<br/>处理原因：" + processReason, function() {
            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                url: ctx + "order/master/after/dispute/handle",
                data: JSON.stringify({
                    recordId: recordId,
                    orderDetailId: orderDetailId,
                    refundAmount: refundAmount,
                    platformHandleReason: processReason
                }),
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msgSuccess("退款处理成功");
                        // 关闭弹窗
                        layer.closeAll();
                        // 刷新表格
                        $.table.refresh();
                    } else {
                        $.modal.msgError("退款处理失败：" + result.msg);
                    }
                },
                error: function () {
                    $.modal.msgError("退款处理失败，请重试");
                }
            });
        });
    }

    // 取消售后
    function cancelAfterService(recordId, orderDetailId) {
        // 获取处理原因输入框的值
        var processReason = $('#processReason_' + recordId).val();
        
        if (!processReason || processReason.trim() === '') {
            $.modal.msgError("请输入处理原因");
            return;
        }
        
        $.modal.confirm("确认取消该售后申请吗？", function() {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: ctx + "order/master/after/cancel",
                data: {
                    afterServiceRecordId: recordId,
                    platformHandleReason: processReason.trim()
                },
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msgSuccess("取消售后成功");
                        // 关闭弹窗
                        layer.closeAll();
                        // 刷新表格
                        $.table.refresh();
                    } else {
                        $.modal.msgError("取消售后失败：" + result.msg);
                    }
                },
                error: function () {
                    $.modal.msgError("取消售后失败，请重试");
                }
            });
        });
    }

    // 获取售后类型文本
    function getAfterServiceTypeText(type) {
        var typeMap = {
            1: '未收到货',
            2: '已收到货',
            3: '质量问题',
            4: '其他'
        };
        return typeMap[type] || '未知';
    }

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

    // 获取客户确认文本
    function getCustomerCheckText(check) {
        var checkMap = {
            0: '不同意',
            1: '同意',
            2: '未处理'
        };
        return checkMap[check] || '未处理';
    }

</script>
</body>

</html>
