@{
    ViewData["Title"] = "平台账单流水";
    Layout = "~/Pages/Shared/_MainLayout.cshtml";
    ViewBag.Nav = new string[] { "销售平台流水", (ViewBag.platform == "" ? "其他" : ViewBag.platform) + "账单流水" };
}


<div class="row">
    <div class="col-sm-12">
        <div class="ibox-content m-b-sm border-bottom">
            <div class="alert alert-warning">

            </div>
            <form id="toolbar">
                <div class="form-inline" style="line-height:40px;">
                    <div id="sel_platform_contain" class="form-group" style="display:none;">
                        <label>平台：</label>
                        <select id="platform" name="platform" class="form-control" style="width:120px">
                            <option value="Dhgate">Dhgate</option>
                            <option value="JOOM">JOOM</option>
                            <option value="WISH">WISH</option>
                            <option value="Walmart">Walmart</option>
                            <option value="Shopify">Shopify</option>
                            <option value="opensky">opensky</option>
                            <option value="esty">esty</option>
                            <option value="JD">JD</option>
                            <option value="Fyndiq">Fyndiq</option>
                            <option value="Paypal">Paypal</option>
                            <option value="速卖通支付宝">支付宝</option>
                            <option value="存货报损">存货报损</option>
                        </select>
                    </div>
                    <div class="form-group">
                        站点：
                        <div data-toggle="buttons-checkbox" class="btn-group">
                            @foreach (var item in ViewBag.sites)
                            {
                                //<option value="@item">@item</option>
                                <button class="btn btn-info wsites" type="button" aria-pressed="false" onclick="selWebsite('@item',this)">@item</button>
                            }
                        </div>
                    </div>

                    <div class="form-group">
                        <label>账单月份</label>
                        <input id="month" name="month" style="width:100px" class="form-control" placeholder="请选择月份" value="@(DateTime.Now.AddMonths(-1).ToString("yyyy-MM"))" />
                    </div>

                    <div class="form-group" style="margin-left:10px">
                        <label>时间</label>
                        @*<input id="month" name="month" class="form-control" style="width:100px" value="@(DateTime.Now.AddMonths(-1).ToString("yyyy-MM"))" />*@
                        <input id="start" name="start" class="form-control" style="width:100px" value="" placeholder="开始时间" />至
                        <input id="end" name="end" class="form-control" style="width:100px" value="" placeholder="结束时间" />
                    </div>
                    <div class="form-group" style="margin-left:10px">
                        <label>平台单号</label>
                        <input id="orderno" name="orderno" class="form-control" style="width:200px" placeholder="请输入平台单号" />
                    </div>
                    <div class="form-group">
                        <label>&nbsp;</label>
                        <button type="button" class="btn btn-primary" onclick="list();"><i class="fa fa-search"></i>&nbsp;查询</button>
                        <button id="btnexport" style="" type="button" class="btn btn-success" onclick="ExportCSV()">导出</button>
                        <button type="button" style="margin-left:10px" class="btn btn-warning" onclick="downloadTemplate()">模版下载</button>
                        <button id="btn_Upload" type="button" style="" class="btn btn-warning">导入流水</button>
                        @*<button id="btn_Upload_Merge" type="button" style="" class="btn btn-warning">导入站点合并流水</button>*@
                        <button id="btn_Export_Voucher" type="button" style="" onclick="Export_Voucher()" class="btn btn-warning">导出凭证</button>
                        <span id="txt_tip"></span>
                    </div>
                </div>
            </form>
        </div>

        <div class="ibox-content m-b-sm border-bottom table-responsive">
            <button class="btn btn-xs btn-danger" onclick="ShowFlowingConfig(1)" style="margin-bottom:5px;">重要：流水字段解析配置</button>
            <table id="roletable" class="table table-hover table-bordered table-striped" style="table-layout:fixed;">
                <thead id="tb_head">

                </thead>
                <tbody id="tb">
                </tbody>
            </table>
            <div id="page-contain">
                <span id="pageresult" style="padding: 5px 3px; display: inline; border: solid 1px #ccc; border-radius: 3px 3px; top: -10px; position: relative;"></span>
                <div id="pagination" class="pagination" style="margin-left:50px;"></div>
            </div>
        </div>

    </div>
</div>

@section css{
    <link href="~/js/webuploader-0.1.5/webuploader.css" rel="stylesheet" />
    <style>

                .webuploader-pick {
                    position: relative;
                    display: block;
                    cursor: pointer;
                    background: none;
                    padding: 0px;
                    color: #fff;
                    text-align: center;
                    border-radius: 3px;
                    overflow: hidden;
                }

                .webuploader-container {
                    background-color: cornflowerblue !important;
                }

                .mules {
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                /*.pagination ul{
                    list-style-type:none;
                    padding:0px;
                    margin:0px;
                }

                .pagination ul li{float:left;width:20px;}
        */
                .pagination {
                    margin: 20px 0;
                }

                    .pagination ul {
                        display: inline-block;
                        *display: inline;
                        margin-bottom: 0;
                        margin-left: 0;
                        -webkit-border-radius: 4px;
                        -moz-border-radius: 4px;
                        border-radius: 4px;
                        *zoom: 1;
                        -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
                        -moz-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
                        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
                        padding-left: 0px;
                    }

                        .pagination ul > li {
                            display: inline;
                        }

                            .pagination ul > li > a,
                            .pagination ul > li > span {
                                float: left;
                                padding: 4px 12px;
                                line-height: 20px;
                                text-decoration: none;
                                background-color: #ffffff;
                                border: 1px solid #dddddd;
                                border-left-width: 0;
                            }

                                .pagination ul > li > a:hover,
                                .pagination ul > li > a:focus,
                                .pagination ul > .active > a,
                                .pagination ul > .active > span {
                                    background-color: #f5f5f5;
                                }

                        .pagination ul > .active > a,
                        .pagination ul > .active > span {
                            color: #999999;
                            cursor: default;
                        }

                        .pagination ul > .disabled > span,
                        .pagination ul > .disabled > a,
                        .pagination ul > .disabled > a:hover,
                        .pagination ul > .disabled > a:focus {
                            color: #999999;
                            cursor: default;
                            background-color: transparent;
                        }

                        .pagination ul > li:first-child > a,
                        .pagination ul > li:first-child > span {
                            border-left-width: 1px;
                            -webkit-border-bottom-left-radius: 4px;
                            border-bottom-left-radius: 4px;
                            -webkit-border-top-left-radius: 4px;
                            border-top-left-radius: 4px;
                            -moz-border-radius-bottomleft: 4px;
                            -moz-border-radius-topleft: 4px;
                        }

                        .pagination ul > li:last-child > a,
                        .pagination ul > li:last-child > span {
                            -webkit-border-top-right-radius: 4px;
                            border-top-right-radius: 4px;
                            -webkit-border-bottom-right-radius: 4px;
                            border-bottom-right-radius: 4px;
                            -moz-border-radius-topright: 4px;
                            -moz-border-radius-bottomright: 4px;
                        }

                .pagination-centered {
                    text-align: center;
                }

                .pagination-right {
                    text-align: right;
                }
    </style>
}

@section scripts{
    <script src="~/js/jspagination/bootstrap-paginator.js"></script>
    <script src="~/js/webuploader-0.1.5/webuploader.min.js"></script>
    <script src="~/js/Layer-2.1/extend/layer.ext.js"></script>
    <script type="text/javascript">
        var tb;
        var current_page = 1;
        var website = '';
        var websitecount = '@(ViewBag.sites.Count)';
        var platform = '@(ViewBag.platform)';

        var BASE_URL = '@(Url.Content("~/js/webuploader-0.1.5/"))';

        var month = '@(DateTime.Now.AddMonths(-1).ToString("yyyy-MM"))';

        $(document).ready(function () {

            //其他平台，默认选择第一个平台
            if (platform == '') {
                $('#sel_platform_contain').css('display', 'inline');
                platform = $('#platform').val();

                $('#platform').change(function () {
                    platform = $('#platform').val();
                    website = '';
                    initUpload();
                })

            }

            list();

            laydate.render({ elem: '#start' });
            laydate.render({ elem: '#end' });
            laydate.render({
                elem: '#month', type: 'month', done: function (value, date, endDate) {
                    //console.log(value); //得到日期生成的值，如：2017-08-18
                    //console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                    //console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。

                    month = value;
                    initUpload();

                }
            });

            initUpload();

            //btn_Upload_Merge
            @*uploadfile('btn_Upload_Merge',
                '@Url.Content("~/DataWareHouse/PlatformOrder/UploadOrderBillingMerge")' + '?platform=' + platform,
                function(result){
                    if(result.success)
                    {
                        alert('上传成功！');
                    }
                    else
                    {
                        alert(result.msg);
                    }
                });*@
        })

        function list() {
            //var website = $('#website').val();
            //var month = $('#month').val();


            //if (website == '') {
            //    alert('请选择站点');
            //    return false;
            //}

            //if (month == '') {
            //    alert('请选择月份');
            //    return false;
            //}

            var start = $('#start').val();
            var end = $('#end').val();
            var orderno = $('#orderno').val();

            if (platform == '') {
                alert('请选择平台');
                return false;
            }

            var load_index = layer.load();
            $.submit({
                url: '@Url.Content("~/DataWareHouse/PlatformOrder/OrderBillingsJson")',
                type:'POST',
                paramData: 'page=' + current_page + '&platform=' + platform + '&website=' + website + '&start=' + start + '&end=' + end + '&orderno=' + orderno + '&month=' + month,
                func: function (result) {
                    layer.close(load_index)
                    $('#tb_head').html('');
                    $('#tb').html('');
                    $('#page-contain').html('<span id="pageresult" style="padding: 5px 3px; display: inline; border: solid 1px #ccc; border-radius: 3px 3px; top: -10px; position: relative;"></span><div id="pagination" class="pagination" style="margin-left:5px;"></div>');
                    if (result.success) {
                        //表头
                        if (result.total == 0) {
                            //alert('没有找到该平台数据，请上传');
                            layer.msg("没有找到该平台数据，请上传");
                            return false;
                        }
                        var firstrow = result.rows[0].jsondata;
                        var _head = '<tr><th style="width:160px;">格式化时间</th>';
                        for (var i in firstrow) {
                            _head += '<th style="width:160px;">' + '<div class="mules" title="' + i + '">' + i + '</div>'+'</th>';
                        }
                        _head += '</tr>';
                        $('#tb_head').html(_head);

                        //内容
                        for (var i in result.rows) {
                            var _obj = result.rows[i].jsondata;

                            var _r = '<tr><td>' + result.rows[i].datatime+'</td>';
                            for (var r in _obj) {

                                var _v = _obj[r];
                                if (isJson(_obj[r])) {
                                    _v = JSON.stringify(_obj[r]).replace(/"/g, "'");
                                }

                                _r += '<td style="width:160px;">' + '<div class="mules" title="' + _v + '">' + _v + '</div>' +'</td>';
                            }
                            _r += '</tr>';

                            $('#tb').append(_r);
                        }

                        //分页
                        InitPage(result.totalpage);

                        $('#pageresult').html('总记录数：' + result.total + '；总页数：' + result.totalpage);

                    }
                    else {
                        //alert('获取数据出现异常')
                        layer.msg("获取数据出现异常");
                    }
                }
            })
        }

        function initUpload() {
            if (platform == '') {
                alert('请选择平台');
                return false;
            }

            //if (month == '') {
            //    alert('请选择月份');
            //    returUrl false;
            //}

            //if (websitecount > 0 && website == '') {
            //    alert('请选择站点，再下载导入模版。');
            //    return false;
            //}

            uploadfile('btn_Upload',
                '@Url.Content("~/DataWareHouse/PlatformOrder/UploadFileFragment")' + '?platform=' + platform + '&website=' + website + '&month=' + month,
                //'http://192.168.6.251:8085/upload/UploadFileFragment',
                function(result){
                    if(result.success)
                    {
                        alert('文件上传成功，后台会自动解析文件，请稍后再查看数据解析情况！');
                        $('#txt_tip').html('');
                    }
                    else
                    {
                        alert(result.msg);
                    }
                });
        }

        function selWebsite(site,data) {
            website = site;

            $('.wsites').each(function () {
                $(this).attr('aria-pressed', 'false');
                $(this).removeClass('active');
            })

            $(data).prop('aria-pressed', 'true');

            list();

            initUpload();
        }

        function InitPage(totalpage) {

            $('#page-contain').html('<span id="pageresult" style="padding: 5px 3px; display: inline; border: solid 1px #ccc; border-radius: 3px 3px; top: -10px; position: relative;"></span><div id="pagination" class="pagination" style="margin-left:5px;"></div>');

            var container = $('#pagination');

            options = {
                containerClass: "pagination"
                , currentPage: current_page
                //, numberOfPages: 6
                , totalPages: totalpage
                , pageUrl: function (type, page) {
                    //return null;
                }
                , onPageClicked: function (e, originalEvent, type, page) {

                    current_page = page;
                    list();
                }
                , onPageChUrlnged: function (page) {

                }

            };

            container.bootstrapPaginator(options);

        }

        function isJson (obj) {
            var isjson = typeof (obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
            return isjson;
        }

        function ExportCSV() {
            //var website = $('#website').val();
            //var month = $('#month').val();

            //if (website == '') {
            //    alert('请选择站点');
            //    return false;
            //}

            var start = $('#start').val();
            var end = $('#end').val();
            var orderno = $('#orderno').val();
            if (platform == '') {
                alert('请选择平台');
                return false;
            }

            window.open('@Url.Content("~/DataWareHouse/PlatformOrder/ExportOrderBillings")' + '?platform=' + platform + '&website=' + website + '&start=' + start + '&end=' + end + '&orderno=' + orderno + '&month=' + month);
        }

        function Export_Voucher() {
            var time = new Date();
            var mon = time.getMonth();
            var month1 = null;
            if (mon < 10) {
                month1 = time.getFullYear() + '-0' + time.getMonth();
            } else {
                month1 = time.getFullYear() + '-' + time.getMonth();
            }
            var centents = '<input type="month" class="layui-layer-input" value="' + month1 + '" placeholder="月份">';
            layer.prompt({
                title: '请选择月份（必选项）',
                content: centents,
                formType: 3
            }, function (enddate, index) {
                    window.open('@Url.Content("~/DataWareHouse/Voucher/GetVoucherList")'+'?month='+enddate+'&platform=亚马逊');
                    layer.close(index);
            })

        };

        function downloadTemplate() {
            if (websitecount > 0 && website=='') {
                alert('请选择站点，再下载导入模版。');
                return false;
            }

            if (platform == '') {
                alert('请选择平台');
                return false;
            }

            var start = $('#start').val();
            var end = $('#end').val();
            var orderno = $('#orderno').val();

            if (month == '') {
                alert('请选择月份');
                return false;
            }

            window.open('@Url.Content("~/DataWareHouse/PlatformOrder/DownLoadOrderBillingTemplate?platform=")' + platform + '&website=' + website + '&start=' + start + '&end=' + end + '&month=' + month, '_blank');

        }

        function uploadfile(id,url,callback)
        {
            var _GUID = WebUploader.Base.guid();//一个GUID
            var uploader = new WebUploader.Uploader({
                // swf文件路径
                swf: BASE_URL + 'Uploader.swf',
                // 文件接收服务端。
                server: url!=undefined?url:'@Url.Content("~/File/UploadFile")',
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                pick: '#'+id,
                // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
                resize: false,
                auto: true,
                timeout: 0,
                accept: {
                    extensions: "xls,xlsx",
                    mimeTypes: ".xls,.xlsx"
                },
                chunked: true,//开始分片上传
                chunkSize: 2048000,//每一片的大小
                formData: {
                    guid: _GUID //自定义参数，待会儿解释
                }
            });

            uploader.on('uploadSuccess', function (file, response) {
                $.submit({
                    type:'post',
                    url: '@Url.Content("~/DataWareHouse/PlatformOrder/MergeUploadFile")',
                    //url: 'http://192.168.6.251:8085/upload/merge',
                    paramData: 'guid=' + _GUID + '&filename=' + file.name + '&platform=' + platform + '&website=' + website + '&month=' + month +'&bucket=bailun-data-center',
                    func: function (result) {
                        if (result.success) {
                            alert('文件上传成功，后台会自动解析文件，请稍后再查看数据解析情况！');
                        }
                        else {
                            alert(result.msg);
                        }
                    }
                })

            });

            uploader.on('uploadProgress', function (file, percentage) {
                //$("#uploader .progress-bar").width(percentage * 100 + '%');
                $('#txt_tip').html('正在上传文件，当前进度：' + percentage * 100 + '%');
            });

            uploader.on('uploadSuccess', function () {
                $('#txt_tip').html('上传成功，待保存数据，请稍等系统操作完成。');

            });

            uploader.on('uploadError', function (file) {
                layer.msg("上传出错");
            });
        }

        function ShowFlowingConfig(datatype) {
            layer_show('流水字段解析配置', '@Url.Content("~/DataWareHouse/PlatformOrder/FlowingConfig")' + '?platform=' + platform+'&datatype=' + datatype, '90%', '90%');
        }

    </script>
}