<%@ page language="java" contentType="text/html; charset=utf-8"
         pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>


<%@include file="/WEB-INF/page/header.jsp" %>
<script>changeMenu(3, 5);//左边菜单active</script>

<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-lg-10">
        <h2>资料设置</h2>
        <ol class="breadcrumb">
            <li>主页</li>
            <li><a>资料设置</a></li>
            <li class="active"><strong>设置法院</strong></li>
        </ol>
    </div>
    <div class="col-lg-2">
        <div style="padding-top:25px">
            <c:if test="${sessionScope.SESSION_COMPANY.canApply}">
                <button class="btn btn-primary btn-lg" type="button" onclick="submitAll()">提交全部页面</button>
            </c:if>
            <c:if test="${sessionScope.SESSION_COMPANY.companyState==1}">
                认证申请中
            </c:if>
        </div>
    </div>
</div>

<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox float-e-margins">

                <div class="ibox-content">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-10 control-label">
                                <h3 class="text-left">法院列表 （按照城市A-Z排列）</h3>
                            </label>
                            <c:if test="${sessionScope.SESSION_COMPANY.canApply}">
                                <div class="col-sm-2">
                                    <button class="btn btn-danger" type="button"
                                            onclick="$('#mod-add').modal('toggle');">新增法院
                                    </button>
                                </div>
                            </c:if>
                        </div>
                        <div class="hr-line-dashed"></div>

                        <div class="row">
                            <div class="col-md-2">
                                <select class="form-control input-sm" id="province">
                                    <option value="">省份</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <select class="form-control input-sm" id="city">
                                    <option value="">城市</option>
                                </select>
                            </div>

                            <div class="col-sm-3">
                                <input type="text" class="form-control input-sm m-b-xs" id="keyword"
                                       placeholder="输入“法院、地区”等关键词">
                            </div>
                            <div class="col-sm-1">
                                <button class="btn btn-sm btn-success" type="button" onclick="search()">查询</button>
                            </div>
                        </div>
                    </form>
                    <div class="row">
                        <div class="col-md-12 jqGrid_wrapper">
                            <table id="gridTable1"></table>
                            <div id="gridPager1"></div>
                        </div>
                    </div>
                    <h3></h3>
                    <div class="row">
                        <div class="col-md-12">
                            <label>配送:&emsp;</label>
                            <label class="checkbox-inline"> <input type="checkbox" id="file1Deliver1"/>上门配送</label>
                            <label class="checkbox-inline"> <input type="checkbox" id="file1Deliver2"/>快递配送</label>
                            <label class="checkbox-inline"> <input type="checkbox" id="ssdbDwlabelId_5"/>同城闪送</label>
                            <button class="btn btn-sm btn-success" type="button" onclick="saveCourtSendType()">保存
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<div id="mod-add" class="modal fade" tabindex="-1">
    <div class="modal-dialog" style="min-width: 400px;">
        <div class="modal-content">
            <div class="modal-header">
                <div class="table-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        <span class="white">&times;</span>
                    </button>
                    新增法院
                </div>
            </div>
            <div class="modal-body">
                <form class="form-inline">
                    <div class="form-group">

                        <select class="form-control input-sm" id="selProvince">
                            <option value="">省份</option>
                        </select>

                        <select class="form-control input-sm" id="selCity">
                            <option value="">城市</option>
                        </select>

                        <button class="btn btn-sm btn-success" type="button" id="addsearchcourt">获取</button>

                    </div>
                </form>
                <table class="footable table table-stripped" data-page-size="10" id="courtTable2">
                    <thead>
                    <tr>
                        <th>地区</th>
                        <th>法院</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="courtList2"></tbody>
                    <tfoot>
                    <tr>
                        <td colspan="5">
                            <ul class="pagination pull-right"></ul>
                        </td>
                    </tr>
                    </tfoot>
                </table>
            </div>

            <div class="modal-footer">
                <button class="btn  btn-info" type="button" onclick="checkAll()" id="checkall"><strong>全选</strong>
                </button>
                <button class="btn  btn-primary" type="button" id="mod-add-submit"><strong>确定</strong></button>
                <button class="btn " data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

<%@include file="/WEB-INF/page/footer.jsp" %>

<link href="${contextPath}/static/css/plugins/jQueryUI/jquery-ui-1.10.4.custom.min.css" rel="stylesheet"/>
<link href="${contextPath}/static/css/plugins/jqGrid/ui.jqgrid.css" rel="stylesheet">

<script src="${contextPath}/static/js/plugins/jqGrid/jquery.jqGrid.min.js"></script>
<script src="${contextPath}/static/js/plugins/jqGrid/i18n/grid.locale-cn.js"></script>

<script src="${contextPath}/static/ssdb/china_area.js"></script>

<script>
    var gridTable1 = null;
    var grid_selector = "#gridTable1";
    var pager_selector = "#gridPager1";

    var i = 0;

    function checkAll() {
        if (i == 0) {
            $("input[name='addcourt']").attr("checked", true);
            i = 1;
            $("#checkall").html('<strong>反选</strong>');
        } else {
            $("input[name='addcourt']").removeAttr("checked");
            i = 0;
            $("#checkall").html('<strong>全选</strong>');
        }

    }

    function del(id) {
        deleteCourts([id]);
    }

    function deleteCourts(ids) {
        if (confirm("确定删除吗?")) {
            $.ajax({
                dataType: "json",
                url: "${contextPath}/company/setting5Delete",
                type: "post",
                traditional: true,
                data: {
                    'ids': ids
                },
                complete: function (ret) {
                    var ret = eval("(" + ret.responseText + ")");
                    if (ret.success) {
                        alert('删除成功');
                        gridTable1.trigger('reloadGrid');
                    } else {
                        alert(ret.message);
                    }
                }
            });
        }
    }

    function submitAll() {
        $.getJSON('${contextPath}/company/submitAll', function (result) {
            if (result.success) {
                alert('提交成功！');
                location.reload();
            } else
                alert(result.message);
        });
    }

    var add = 0;
    jQuery(function ($) {

        //loadCourt();
        initGridTable();

        $(function () {
            $('#mod-add').on('hide.bs.modal', function () {
                if (add == 1) {
                    gridTable1.trigger('reloadGrid');
                }
            });
        });

        $('#mod-add-submit').on('click', function () {
            var ids = new Array();
            var obj = document.getElementsByName('addcourt');
            for (var i = 0; i < obj.length; i++) {
                if (obj[i].checked) ids.push(obj[i].value);
            }
            /* $("input[name='addcourt']:checked").each(function(){
                if ($(this).attr('checked') ==true) {
                    ids.push($(this).val());
                }
            }); */

            $.ajax({
                url: "${contextPath}/company/setting5Save",
                data: {
                    ids: ids.join(','),
                },
                type: 'POST',
                dataType: 'json',
                success: function (data) {
                    if (data.success) {
                        //loadCourt();
                        //$("#mod-add").modal("toggle");
                        alert("添加成功");
                        $("#region").val('');
                        $("#keyword").val('');
                        add = 1;
                    } else {
                        alert(data.message);
                    }
                },
            });
        });

        $.each(provinceJson, function (k, p) {
            var option = "<option value='" + p.id + "'>" + p.province + "</option>";
            $("#selProvince").append(option);
            $("#province").append(option);
        });
        $("#province").change(function () {
            var selValue = $(this).val();
            $("#city option:gt(0)").remove();
            $.each(cityJson, function (k, p) {
                // 直辖市处理.|| p.parent == selValue，直辖市为当前自己
                if (p.id == selValue || p.parent == selValue) {
                    var option = "<option value='" + p.city + "'>" + p.city + "</option>";
                    $("#city").append(option);
                }
            });
        });
        $("#selProvince").change(function () {
            var selValue = $(this).val();
            $("#selCity option:gt(0)").remove();
            $.each(cityJson, function (k, p) {
                // 直辖市处理.|| p.parent == selValue，直辖市为当前自己
                if (p.id == selValue || p.parent == selValue) {
                    var option = "<option value='" + p.city + "'>" + p.city + "</option>";
                    $("#selCity").append(option);
                }
            });
        });

        $('#addsearchcourt').on('click', function () {
            var selProvince = $("#selProvince").val();
            var selCity = $("#selCity").val();

            var pName = "";
            $.each(provinceJson, function (k, p) {
                if (selProvince == p.id)
                    pName = p.province;
            });
            $("#courtList2").html('');
            $.getJSON('${contextPath}/company/setting5Find?selProvince=' + pName + '&selCity=' + selCity, function (result) {
                var sec = '';
                $.each(result, function (i, v) {
                    var region = v.region;
                    sec += '<tr class="gradeX"><td>' + pName + '-' + region + '</td><td>' + v.name + '</td><td class="center"><input type="checkbox" value="' + v.id + '" name="addcourt"></td></tr>';
                });
                $("#courtList2").html(sec);
                //$("#courtTable2").footable();
            });
        });

        // Add responsive to jqGrid
        $(window).bind('resize', function () {
            var width = $('.jqGrid_wrapper').width();
            gridTable1.setGridWidth(width);
        });

        if (${sessionScope.SESSION_COMPANY.canApply==true}) {
            jQuery(grid_selector).jqGrid('navGrid', pager_selector, {
                edit: false,
                editicon: 'ace-icon fa fa-pencil blue',
                add: false,
                addicon: 'ace-icon fa fa-plus-circle purple',
                del: false,
                delicon: 'ace-icon fa fa-trash-o red',
                search: false,
                searchicon: 'ace-icon fa fa-search orange',
                refresh: false,
                refreshicon: 'ace-icon fa fa-refresh blue',
                view: false,
            }).jqGrid('navButtonAdd', pager_selector, {
                caption: "",
                title: "删除法院",
                buttonicon: "ui-icon ace-icon fa ui-icon-trash blue",
                onClickButton: function () {
                    var selectedIds = gridTable1.jqGrid("getGridParam", "selarrrow");
                    if (selectedIds.length < 1) {
                        alert('请选择记录');
                        return;
                    }
                    deleteCourts(selectedIds);
                },
                position: "last"
            });
        }
    });

    function initGridTable() {
        gridTable1 = jQuery(grid_selector).jqGrid({
            subGrid: false,
            url: "${contextPath}/company/setting5Load",//
            datatype: "json",
            height: "auto",
            autowidth: true,
            colModel: [{
                name: "court.province",
                index: "court.province",
                label: "省",
                width: 60,
                search: false
            }, {
                name: "court.region",
                index: "court.region",
                label: "市",
                width: 60,
                search: false
            }, {
                name: "court.name",
                index: "court.name",
                label: "受理法院",
                width: 160,
                search: false
            }, {
                name: "deliver1",
                index: "deliver1",
                label: "配送方式",
                width: 80,
                search: false,
                formatter: formatDeliver
            }, {
                name: "createDate",
                index: "createDate",
                label: "提交时间",
                width: 80,
                search: false,
                formatter: formatDate
            }, {
                align: "center",
                name: "id",
                index: "id",
                label: "操作",
                width: 60,
                viewable: false,
                hidden: true,
                formatter: operationLink,
            }],
            sortname: "court.id",
            sortorder: "asc",
            viewrecords: true,
            rowNum: 10,
            rowList: [10, 20, 30],
            pager: pager_selector,
            altRows: true,
            //toppager : true,
            multiselect: true,
            //multikey : "ctrlKey",
            multiboxonly: true,
            rownumbers: true,
            rownumWidth: 30,

        });

        if (${sessionScope.SESSION_COMPANY.canApply==true}) {
            jQuery(grid_selector).setGridParam().showCol("id");
        }


    }

    function operationLink(cellvalue, options, rowObject) {
        if (${sessionScope.SESSION_COMPANY.canApply==true}) {
            return "<a href='javascript:void(0);' onclick='del(\"" + cellvalue + "\")'>删除</a>";
        } else {
            return "";
        }

    }

    function formatDate(cellvalue, options, rowObject) {
        if (cellvalue != null && cellvalue != '')
            return new Date(cellvalue).toLocaleDateString();
        return '';
    }

    function formatDeliver(cellvalue, options, rowObject) {
        var result = '';
        if ('1' == rowObject.deliver1) {
            result += '上门配送,';
        }
        if ('1' == rowObject.deliver2) {
            result += '快递配送,';
        }
        if ('5' == rowObject.ssdbDwlabelId) {
            result += '同城闪送,';
        }
        if (result.length > 0) {
            result = result.substring(0, result.length - 1);
        }
        return result;
    }

    function saveCourtSendType() {
        var selectedIds = gridTable1.jqGrid("getGridParam", "selarrrow");
        if (selectedIds.length > 0) {
            var deliver1 = document.getElementById('file1Deliver1').checked ? 1 : 0;
            var deliver2 = document.getElementById('file1Deliver2').checked ? 1 : 0;
            var ssdbDwlabelId = document.getElementById("ssdbDwlabelId_5").checked ? "5" : "";// 同城闪送
            $.ajax({
                url: "${contextPath}/company/setting5SaveDeliver",
                data: {
                    ids: selectedIds.join(','),
                    deliver1: deliver1,
                    deliver2: deliver2,
                    ssdbDwlabelId: ssdbDwlabelId,
                },
                type: 'POST',
                dataType: 'json',
                success: function (data) {
                    if (data.success) {
                        alert("添加成功");
                        gridTable1.trigger('reloadGrid');
                    } else {
                        alert(data.message);
                    }
                },
            });
        } else {
            alert('请选择法院');
        }
    }

    function search() {
        var province = $("#province").val();
        var city = $("#city").val();
        var keyword = $("#keyword").val();

        var pName = "";
        if (province != '') {
            $.each(provinceJson, function (k, p) {
                if (province == p.id)
                    pName = p.province;
            });
        }

        gridTable1.setGridParam({
            postData: {'keyword': keyword, 'province': pName, 'city': city},
            url: '${contextPath}/company/setting5Load',
            page: 1
        }).trigger('reloadGrid');
    }
</script>