$(document).ready(function () {
    //iniChart('rptweld');
    //iniChart('rptweld1');
    //iniChart('rptweld2');
    //QueryData().then(data => console.log(data));
    //console.log(QueryData("M02","M15"));
    console.log('aa');
    $(window).bind("load resize", HandleBoxHeight);
    QueryWorkshop()
    //QueryDataAsync();
    SetBoxHeight();
    setInterval(function () {
        QueryDataAsync($('#cbxWorkshop').val());
    }, 1800000);
    //addHints();
    startIntro();
    showsidebar();
});

function showsidebar() {
    $('#rightsidebar').addClass('control-sidebar-open')
    setTimeout(function () { $('#rightsidebar').removeClass('control-sidebar-open') },1000)
}
function startIntro() {
    var intro = introJs();
    intro.setOptions({
        steps: [
            
            {
                element: document.querySelector('#dashtitle'),
                intro: "点击选择查询条件",
                
            },
            //{
            //    element: document.querySelectorAll('#step2')[0],
            //    intro: "Ok, wasn't that fun?",
            //    position: 'right'
            //},
            //{
            //    element: '#step3',
            //    intro: 'More features, more fun.',
            //    position: 'left'
            //},
            //{
            //    element: '#step4',
            //    intro: "Another step.",
            //    position: 'bottom'
            //},
            //{
            //    element: '#step5',
            //    intro: 'Get it, use it.'
            //}
        ],
        //showButtons: false,
        showBullets:false,
    });
    intro.start();



    setTimeout(
        function() { intro.exit()},3000)
    //intro.exit()
}
function addHints() {
    intro = introJs();
    //intro.setOptions({
    //    hints: [
    //        {
    //            element: document.querySelector('#dashtitle'),
    //            hint: "点击选择查询条件7",
    //            hintPosition: 'top-middle',
    //            hintButtonLabel:`mklnjk`

    //        }
    //    ]
    //})
    intro.setOptions({
        hints: [
            {  element: '#dashtitle', hint: "点击选择查询条件", },
           
        ]
    });
    intro.setOption("hintButtonLabel", "OK");
    //introJs().setOption("hintButtonLabel", "OK")
    //intro.onhintsadded(function () {
    //    console.log('all hints added');
    //});
    //intro.onhintclick(function (hintElement, item, stepId) {
    //    console.log('hint clicked', hintElement, item, stepId);
    //});
    //intro.onhintclose(function (stepId) {
    //    console.log('hint closed', stepId);
    //});
    intro.addHints();
}
function SetBoxHeight() {
    var h = window.innerHeight
        || document.documentElement.clientHeight
        || document.body.clientHeight;
    var contentmargin = 30 * 2;
    var boxmargintop = (3 + 3 + 20) * 3
    var height = (h - contentmargin - boxmargintop) / 3;
    //var aaa = window["innerHeight"];
    $('.rpt').css("height", height + "px");
}
function HandleBoxHeight() {
    var resize1;
    $(window).resize(function () {
        if (resize1) {
            clearTimeout(resize1);
        }
        resize1 = setTimeout(function () {
            //_runResizeHandlers();
            SetBoxHeight();
            //handleIframeContent();
        }, 100); // wait 50ms until window resize finishes.
    });
}

function handleary(getdata) {
    var chartary = [];
    var completionary = ["00", "02", "04", "06", "08", "10", "12", "14", "16", "18", "20", "22"];
    _.each(completionary, function (ele, index, ary) {
        var findres = _.find(getdata, function (item, index, obj) {
            return item.times == ele;
        });
        if (findres == undefined) {
            chartary.push(0)
        }
        else {
            chartary.push(findres.qty)
        }
    })
    return chartary;
}

async function QueryWorkshop() {
    let workshop = await FetchApi("QueryWorkshop", {})
    workshop = await workshop.json(); 
    $('#cbxWorkshop').empty()
    _.each(workshop.info, function (ele, index, list) {     
        $('#cbxWorkshop').append("<option value='"+ele.PRISOURCENAME+"'>"+ele.PRIDISPLAYNAME+"</option>")
    })
    console.log(workshop)
    console.log('query workshop end')
    var title = /\d*$/.exec($('#cbxWorkshop').val())[0]
    title=title.replace(/\b0*/, '')
    $('#wotitle').text(title)
    await QueryDataAsync($('#cbxWorkshop').val())
}

//车间下拉选项事件
$('#cbxWorkshop').on('change', function () {
    console.log('车间选项变成:' + $('#cbxWorkshop').val())
    QueryDataAsync($('#cbxWorkshop').val());
    var title = /\d*$/.exec($('#cbxWorkshop').val())[0]
    title= title.replace(/\b0*/,'')
    $('#wotitle').text(title)
})
async function QueryDataAsync(paraworkshop) {
    try {
        let workshop = paraworkshop
        console.log('chart')
        //1 焊接
        let weld = await QueryData(workshop, "M10");
        weld = await weld.json();
        weld = handleary(weld.info);
        iniChart('rptweld', '焊接', weld);
        //2 叠层
        let lamination = await QueryData(workshop, "M15");
        lamination = await lamination.json();
        lamination = handleary(lamination.info);
        iniChart('rptlamination', '叠层', lamination);
        //3 层压
        let layup = await QueryData(workshop, "M30");
        layup = await layup.json();
        layup = handleary(layup.info);
        iniChart('rptlayup', '层压', layup);
        //4 层压后检验
        //let inspectionafterlayup = await QueryData(workshop, "M35");
        //inspectionafterlayup = await inspectionafterlayup.json();
        //inspectionafterlayup = handleary(inspectionafterlayup.info);
        //iniChart('rptinspectionafterlayup', '层压后检验', inspectionafterlayup)
        //5 装框
        let frame = await QueryData(workshop, "M45");
        frame = await frame.json();
        frame = handleary(frame.info);
        iniChart('rptframe', '装框', frame);
        //6 清洗
        let clean = await QueryData(workshop, "M50");
        clean = await clean.json();
        clean = handleary(clean.info);
        iniChart('rptclean', '清洗', clean);
        //7 IV测试
        let iv = await QueryData(workshop, "iv");
        iv = await iv.json();
        iv = handleary(iv.info);
        iniChart('rptiv', 'IV测试', iv);
        //8 EL测试
        let el = await QueryData(workshop, "el");
        el = await el.json();
        el = handleary(el.info);
        iniChart('rptel', 'EL测试', el);
        //9 全检
        let fullinspection = await QueryData(workshop, "M70");
        fullinspection = await fullinspection.json();
        fullinspection = handleary(fullinspection.info);
        iniChart('rptfullinspection', '全检', fullinspection);
    }
    catch (err) {
        console.log(err);
    }
}
function FetchApi(funname, para) {
    return fetch("/api/Report/Dashboard/" + funname + "", {
        method: "post",
        headers: {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json"
        },
        body: JSON.stringify(para)
    })
}
function QueryData(workshop, sitename) {
    let response = fetch("/api/Report/Dashboard/QueryData", {
        method: "post",
        headers: {
            "Accept": "application/json, text/plain, */*",
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ workshop: workshop, sitename: sitename })
    })
    //let data = await response.json();
    return response;
}
//       .then(function (res) {
//        return res.json();
//    }).then(function (res) {
//        var getdata = res.info;
//        //$('#mainboxbody').next().remove();
//        //App.unblockUI($('#tab-content'));
//        var chartary = [];
//        var completionary = ["00", "02", "04", "06", "08", "10", "12", "14", "16", "18", "20", "22"];
//        _.each(completionary, function (ele, index, ary) {
//            var findres = _.find(getdata, function (item, index, obj) {
//                return item.times == ele;
//            });
//            if (findres == undefined) {
//                chartary.push(0)
//            }
//            else {
//                chartary.push(findres.qty)
//            }
//        })
//        iniChart('rptweld', '焊接', chartary);
//        iniChart('rptweld1', '叠层', chartary);
//        iniChart('rptweld2', '层压', chartary);
//        iniChart('rptweld3', '层压', chartary);
//        iniChart('rptweld4', '层压', chartary);
//        iniChart('rptweld5', '层压', chartary);
//        iniChart('rptweld6', '层压', chartary);
//        iniChart('rptweld7', '层压', chartary);
//        iniChart('rptweld8', '层压', chartary);
//        console.log(chartary);
//    }).catch(function (ex) {
//        //$('#mainboxbody').next().remove();
//        //toastr.error(ex, '', { progressBar: true });
//        console.log('request failed', ex);
//        })
//    console.log(a1);
//}
function iniChart(eleid, title, data) {
    var chart = Highcharts.chart(eleid, {
        chart: {
            type: 'column'
        },
        credits: {
            enabled: false
        },
        title: {
            text: title
        },
        subtitle: {
            //text: '数据来源: WorldClimate.com'
        },
        xAxis: {
            categories:
                ["00:00", "02:00", "04:00", "06:00", "08:00", "10:00", "12:00", "14:00", "16:00", "18:00", "20:00", "22:00"]
            ,
            crosshair: true
        },
        yAxis: {
            min: 0,
            title: {
                text: '组件数量'
            },
            //stackLabels: {  // 堆叠数据标签
            //    enabled: true,
            //    style: {
            //        fontWeight: 'bold',
            //        color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
            //    }
            //}
        },
        tooltip: {
            // head + 每个 point + footer 拼接成完整的 table
            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
            footerFormat: '</table>',
            shared: true,
            useHTML: true
        },
        exporting: { enabled: false },
        plotOptions: {
            column: {
                borderWidth: 0,
                dataLabels: {
                    enabled: true //设置显示对应y的值
                }
            },

        },
        series: [{

            data: data
        }],
        legend: {
            enabled: false
        },
    });
}
function iniStockTable() {
    $('#tbLCLPallet').bootstrapTable({
        columns: [{
            field: 'palletno',
            title: '托盘'
        }, {
            field: 'powergrade',
            title: '电压'
        }
            , {
            field: 'igrade',
            title: '电流'
        }, {
            field: 'cellqty',
            title: '电池片数量'
        }, {
            field: 'bartype',
            title: '晶体类型'
        }, {
            field: 'modulespec',
            title: '组件类型'
        }, {
            field: 'finalgrade',
            title: '最终等级'
        }, {
            field: 'color',
            title: '颜色'
        },
        {
            field: 'locationname',
            title: '库位'

        }
        ],
        //data: [{
        //    id: 1,
        //    name: 'Item 1',
        //    price: '$1'
        //}, {
        //    id: 2,
        //    name: 'Item 2',
        //    price: '$2'
        //}]
    }
    )
}

//查询仓库的库位
function QueryStorageLocationByStock(stockid) {
    var promise = $.ajax({
        url: '../api/StockIn/QueryLocationByStock',
        type: 'post',
        cache: false,
        async: true,
        contentType: "application/json",
        data: JSON.stringify({
            stockid: stockid
        })
    });
    promise.done(function (r) {

        var options = '';
        $.each(r, function (i, v) {
            options += "<option value='" + v.id + "'>" + v.locationname + "</option>";
        });
        $('#ddlLocation').html(options);
        $('#ddlLocation').val('');
        $('#ddlLocation').select2({
            placeholder: "选择库位",
            allowClear: true
        });
        //查询库位的条件 2019-2-20 xue lei
        $('#ddlLocation').on('select2:select', function (e) {
            console.log($(this).val());
            var selectvalue = $(this).val();
            QueryLocationCondiction(selectvalue);
        });
    });
    promise.fail(function (error) {
        console.log(error)
        alert(error);
    });
}
//查询仓库
function QueryStock() {
    var promise = $.ajax({
        url: '../api/StockIn/QueryStock',
        type: 'post',
        cache: false,
        async: true,
        contentType: "application/json",
        //data: JSON.stringify({
        //    lotid: $("#LotID").val()
        //}),
    });
    promise.done(function (r) {

        var options = '';
        $.each(r, function (i, v) {
            options += "<option value='" + v.ID + "'>" + v.Name + "</option>";
        })
        $('#ddlStock').html(options);
        $('#ddlStock').val('');
        $('#ddlStock').select2({
            placeholder: "选择仓库",
            allowClear: true
        });
        $('#ddlStock').on('select2:select', function (e) {
            console.log($(this).val());
            var selectvalue = $(this).val();
            QueryStorageLocationByStock(selectvalue);
        });

    });
    promise.fail(function (error) {
        console.log(error);
        alert(error);
    });
}

//查询库位的条件
function QueryLocationCondiction(lacotionid) {
    fetch("../api/StockIn/QueryLocationCondiction", {
        method: "post",
        headers: {
            "Accept": "application/json, text/plain, */*",
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ locationid: lacotionid })
    }).then(function (res) {
        return res.json();
    }).then(function (res) {
        const CondictionAry = ['powergrade', 'igrade', 'color', 'cellqty', 'bartype', 'modulespec', 'finalgrade'];

        if (res.powergrade != null) { $('#cbxPowerGrade').iCheck('check'); };
        if (res.igrade != null) { $('#cbxIGrade').iCheck('check'); };
        if (res.cellqty != null) { $('#cbxCellQty').iCheck('check'); };
        if (res.bartype != null) { $('#cbxBarType').iCheck('check'); };
        if (res.modulespec != null) { $('#cbxModuleSpec').iCheck('check'); };
        if (res.finalgrade != null) { $('#cbxFinalGrade').iCheck('check'); };
        if (res.color != null) { $('#cbxColor').iCheck('check'); };



        console.log("查询库位条件结束");
    }).catch(function (ex) {
        console.log('request failed', ex);
    })
}

function CondictionisSelected() {
    var conobj = {
        powergrade: $('#cbxPowerGrade').iCheck('update')[0].checked,
        igrade: $('#cbxIGrade').iCheck('update')[0].checked,
        color: $('#cbxColor').iCheck('update')[0].checked,
        cellqty: $('#cbxCellQty').iCheck('update')[0].checked,
        bartype: $('#cbxBarType').iCheck('update')[0].checked,
        modulespec: $('#cbxModuleSpec').iCheck('update')[0].checked,
        finalgrade: $('#cbxFinalGrade').iCheck('update')[0].checked,
    }
    if (!conobj.powergrade && !conobj.igrade && !conobj.color && !conobj.cellqty && !conobj.battype && !conobj.modulespec && !conobj.finalgrade) { return false; }
    return true;
}

//扫描托盘号
$("#txtPallet").keypress(function (event) {
    if (event.which == 13 || event.KeyCode == 13) {
        event.preventDefault();
        //检查拼柜条件是否选中
        if (CondictionisSelected() == false) {
            toastr.warning('请选择拼柜条件', '', { progressBar: true });
            return;
        }

        if ($('#txtContainer').val() == '') {
            toastr.warning('请输入柜号', '', { progressBar: true });
            return;
        }
        if ($('#txtContainerQty').val() == '') {
            toastr.warning('请输入拼柜数量', '', { progressBar: true });
            return;
        }

        var conobj = {
            powergrade: $('#cbxPowerGrade').iCheck('update')[0].checked,
            igrade: $('#cbxIGrade').iCheck('update')[0].checked,
            color: $('#cbxColor').iCheck('update')[0].checked,
            cellqty: $('#cbxCellQty').iCheck('update')[0].checked,
            bartype: $('#cbxBarType').iCheck('update')[0].checked,
            modulespec: $('#cbxModuleSpec').iCheck('update')[0].checked,
            finalgrade: $('#cbxFinalGrade').iCheck('update')[0].checked,
        }
        var palletno = $('#txtPallet').val();
        //$('#mainboxbody').after('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
        //App.blockUI({
        //    target: $('#tab-content'),
        //    animate: true,
        //    overlayColor: 'none'
        //})
        $.blockUI({
            css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff'
            }
        });
        //提交托盘号和入库所选的条件
        fetch("../api/LCL/LCL", {
            method: "post",
            headers: {
                "Accept": "application/json, text/plain, */*",
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ palletno: palletno, container: $("#txtContainer").val(), containerqty: $("#txtContainerQty").val(), selectcondiction: conobj })
        }).then(function (res) {
            return res.json();
        }).then(function (res) {
            //$('#mainboxbody').next().remove();
            //App.unblockUI($('#tab-content'));
            $.unblockUI();
            if (res.result == "fail") {
                //toastr.options.progressBar = true;
                //toastr.options.positionClass = "toast-top-center";
                toastr.warning(res.msg, '', { progressBar: true });
            }
            else if (res.result == "success") {
                toastr.success(res.msg, '', { progressBar: true });
                var locationname = '';
                if (res.info.stockinfo != null) {
                    locationname = res.info.stockinfo.locationname;
                }
                var rowobj = {
                    palletno: res.info.pallet.pallet_nbr,
                    powergrade: res.info.pallet.power_grade,
                    igrade: res.info.pallet.current_grade,
                    cellqty: res.info.product.cell_qty,
                    bartype: res.info.product.crys_type_value,
                    modulespec: res.info.product.mod_spec_value,
                    finalgrade: res.info.pallet.final_grade,
                    color: res.info.pallet.mod_color,
                    locationname: locationname
                }
                $('#tbLCLPallet').bootstrapTable('insertRow', { index: 0, row: rowobj });
                $('#txtPallet').val('');
            }
            else if (res.result == "doing") {

                var $toastr = toastr.warning('<div>该托盘正在拼柜,是否显示托盘的柜号信息</div><div><button type="button" id="okBtn" class="btn btn-default">取消</button><button type="button" id="ShowContainerBtn" class="btn btn-primary" style="margin: 0 8px 0 8px">显示</button></div>', '', { timeOut: 0, extendedTimeOut: 0 })
                LCLApp.stockinfo = res.info.stockinfo;
                LCLApp.palletinfo = res.info.palletinfo;
                if ($toastr.find('#ShowContainerBtn').length) {
                    $('#ShowContainerBtn').on("click", function () {
                        ShowPalletOfContainer();
                    })
                }
            }

            console.log(res);
        }).catch(function (ex) {
            $('#mainboxbody').next().remove();
            toastr.error(ex, '', { progressBar: true });
            console.log('request failed', ex);
        })
    }
});
var LCLApp = {
    stockinfo: null,
    palletinfo: null
}

function ShowPalletOfContainer() {
    //显示正在平柜的数据
    //柜号
    $('#txtContainer').val(LCLApp.stockinfo[0].ContainerNo);
    //柜号数量
    $('#txtContainerQty').val(LCLApp.stockinfo[0].Count);
    //柜号里的托盘
    var tbdata = [];
    for (var i = 0; i <= LCLApp.stockinfo.length - 1; i++) {
        var match = _.find(LCLApp.palletinfo, function (num) {
            return num.palletno == LCLApp.stockinfo[i].palletno;
        });
        if (match != undefined) {
            var entendres = _.extend(LCLApp.stockinfo[i], match)
            tbdata.push(entendres);
        }
        else {
            tbdata.push(LCLApp.stockinfo[i]);
        }
    }

    $('#tbLCLPallet').bootstrapTable('destroy').bootstrapTable({
        columns: [{
            field: 'palletno',
            title: '托盘'
        }, {
            field: 'powergrade',
            title: '电压'
        }
            , {
            field: 'igrade',
            title: '电流'
        }, {
            field: 'cellqty',
            title: '电池片数量'
        }, {
            field: 'bartype',
            title: '晶体类型'
        }, {
            field: 'modulespec',
            title: '组件类型'
        }, {
            field: 'finalgrade',
            title: '最终等级'
        }, {
            field: 'color',
            title: '颜色'
        },
        {
            field: 'locationname',
            title: '库位'

        }
        ],
        data: tbdata
    });
    LCLApp.palletinfo = null;
    LCLApp.stockinfo = null;
}