<%@ page contentType="text/html;charset=UTF-8" %>
    <script>
    $(document).ready(function() {
        $('#dataTable').bootstrapTable({
            //请求方法
            method: 'post',
            //类型json
            dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            //显示检索按钮
            showSearch: true,
            //显示刷新按钮
            showRefresh: true,
            //显示切换手机试图按钮
            showToggle: true,
            //显示 内容列下拉框
            showColumns: false,
            //显示到处按钮
            showExport: true,
            //显示切换分页按钮
            showPaginationSwitch: false,
            //最低显示2行
            minimumCountColumns: 2,
            //是否显示行间隔色
            striped: true,
            //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            cache: false,
            //是否显示分页（*）
            pagination: false,
            //排序方式
            sortOrder: "asc",
            //初始化加载第一页，默认第一页
            pageNumber:1,
            //每页的记录行数（*）
            pageSize: 10,
            //可供选择的每页的行数（*）
            pageList: [10, 25, 50, 100],
            //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据
            url: "${ctx}/supply/particulars/data",
            //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
            //queryParamsType:'',
            ////查询参数,每次调用是会带上这个参数，可自定义
            queryParams : function(params) {
                var searchParam = $("#searchForm").serializeJSON();
                searchParam.pageNo = params.limit === undefined? "1" :params.offset/params.limit+1;
                searchParam.pageSize = params.limit === undefined? -1 : params.limit;
                searchParam.orderBy = params.sort === undefined? "" : params.sort+ " "+  params.order;
                return searchParam;
            },
            //分页方式：client客户端分页，server服务端分页（*）
            sidePagination: "server",
            contextMenuTrigger:"right",//pc端 按右键弹出菜单
            contextMenuTriggerMobile:"press",//手机端 弹出菜单，click：单击， press：长按。
            contextMenu: '#context-menu',
            onContextMenuItem: function(row, $el){
                if($el.data("item") == "edit"){
                    edit(row.id);
                }else if($el.data("item") == "view"){
                    view(row.id);
                } else if($el.data("item") == "delete"){
                    jp.confirm('确认要删除该数据记录吗？', function(){
                        jp.loading();
                        jp.get("${ctx}/supply/particulars/delete?id="+row.id, function(data){
                            if(data.success){
                                $('#dataTable').bootstrapTable('refresh');
                                jp.success(data.msg);
                            }else{
                                jp.error(data.msg);
                            }
                        })

                    });

                }
            },

            onShowSearch: function () {
                $("#search-collapse").slideToggle();
            },
            columns: [/*{
		        checkbox: true

		    }
			,*/
                {
                field: 'batch',
                title: '批次',
                width:100,
                sortName: 'batch'
            }/*,{
                    field: 'materialNumber',
                    title: '物料编码',
                    width:120,
                    sortName: 'materialNumber'
                }*/
                ,{
                    field: 'materialDescription',
                    title: '材料名称',
                    width:200,
                    sortName: 'materialDescription',
                    formatter:function(value, row , index) {
                        var batch = row.batch;
                        var flag = row.flag;
                        value = jp.unescapeHTML(value);
                        /*var actualQuantityIssued = parseFloat(row.actualQuantityIssued);
                        var examineCount = parseFloat(row.examineCount);
                        if (actualQuantityIssued === 0 && examineCount !== 0) {
                            return "<a href='javascript:viewMaterials(\"" + row.materialNumber + "\")'>" + value + "</a>";
                        } else if(actualQuantityIssued !== 0 && examineCount === 0) {
                            return "<a href='javascript:viewMaterials(\"" + row.materialNumber + "\")'>" + value + "</a>";
                        } else{
                            return value;
                        }*/
                        if('true' === flag && (undefined === batch || null === batch || ''=== batch ||'-' === batch)){
                            return "<a href='javascript:viewMaterials(\"" + row.materialNumber + "\")'>" + value + "</a>";
                        }else{
                            return value;
                        }
                    }
                }
                ,{
                    field: 'unit',
                    title: '计量单位',
                    width:100,
                    sortName: 'unit'
                }
                ,{
                    field: 'actualQuantityIssued',
                    title: '实发数量',
                    width:100,
                    sortName: 'actualQuantityIssued'
                }
                ,{
                    field: 'examineCount',
                    title: '审定数量',
                    width:100,
                    sortName: 'examineCount'
                }
                ,{
                    field: 'supplyCount',
                    title: '超（欠）供数量',
                    width:150,
                    sortName: 'supplyCount'
                }
                ,{
                    field: 'unitPrice',
                    title: '单价',
                    width:120,
                    sortName: 'unitPrice',
                    editable: {
                        type: 'text',
                        title: '单价',
                        noeditFormatter (value, row, index) {
                            var batch = row.batch;
                            var flag = row.flag;
                            /*var actualQuantityIssued = parseFloat(row.actualQuantityIssued);
                            var examineCount = parseFloat(row.examineCount);
                            if (actualQuantityIssued === 0 && examineCount !== 0) {
                                return false
                            }else if (actualQuantityIssued !== 0 && examineCount === 0) {
                                return false
                            }else{
                                return value;
                            }*/
                            if('true' === flag && (undefined === batch || null === batch || ''=== batch ||'-' === batch)){
                                return false;
                            }else{
                                return value;
                            }
                        },
                        validate: function (value) {
                            if (isNaN(value))
                                return '单价必须为数字';
                            var age = parseFloat(value);
                            if (age < 0) return '单价必须大于等于0';
                            if (!$.trim(value)) {
                                return '不能为空';
                            }
                        }
                    }

                }
                ,{
                    field: 'supplyMoney',
                    title: '超（欠）供金额',
                    width:150,
                    sortName: 'supplyMoney'
                }
                ,{
                    field: 'commodityHandleTenet',
                    title: '商定处理原则',
                    width:150,
                    sortName: 'commodityHandleTenet',
                    editable: {
                        type: 'select2',
                        title: '商定处理原则',
                        noEditSelectFormatter (value, row, index) {
                            if (row.supplyCount !== "-" && row.flag === "true") {
                                return false
                            }
                            return value
                        },select2: {
                            multiple: true,//多选
                            placeholder: '请选择',
                            width: '100px',
                        },
                        source: //下拉框数据源--后台获取list数据
                            function () {
                                var result1 = [];
                                result1.push({value: "置换", text: "置换"});
                                result1.push({value: "核减施工费", text: "核减施工费"});
                                result1.push({value: "欠供不在发生", text: "欠供不在发生"});
                                result1.push({value: "退料", text: "退料"});
                                result1.push({value: "欠供转乙供", text: "欠供转乙供"});
                                result1.push({value: "欠供补领", text: "欠供补领"});
                                return result1;
                            },
                        validate: function (value) {

                        }
                    }
                }
                ,{
                    field: 'planMoney',
                    title: '计划列入工程投资的物资金额',
                    width:150,
                    sortName: 'planMoney'
                }
                ,{
                    field: 'practicalMoney',
                    title: '实际列入工程投资的物资金额',
                    width:150,
                    sortName: 'practicalMoney'
                }
                ,{
                    field: 'supplyReason',
                    title: '超（欠）供原因',
                    width:150,
                    sortName: 'supplyReason'
                }
                ,{
                    field: 'remarks',
                    title: '备注',
                    width:150,
                    sortName: 'remarks'
                }


            ],
            onEditableSave: function (field, row, oldvalue, $el) {
                var data= $('#dataTable').bootstrapTable('getData',{useCurrentPage:false,includeHiddenRows:false});
                var index =  row.index
                if("unitPrice" === field){
                    row.planMoney = (row.unitPrice * row.examineCount).toFixed(2)
                    if(row.commodityHandleTenet === '置换' || row.commodityHandleTenet === '核减施工费' ||
                        row.commodityHandleTenet === '欠供不在发生' || row.commodityHandleTenet === '欠供转乙供'){
                        //实际列入工程投资的材料金额  =  出库数*单价
                        row.practicalMoney = (row.unitPrice * row.actualQuantityIssued).toFixed(2)
                        $("table tbody").find("tr").eq(index-1).find("td").eq(10).html(row.practicalMoney);
                    } else if(row.commodityHandleTenet === '退料' || row.commodityHandleTenet === '欠供补领'){
                        //实际列入工程投资的材料金额  =  审定数*单价
                        row.practicalMoney = (row.unitPrice * row.examineCount).toFixed(2)
                        $("table tbody").find("tr").eq(index-1).find("td").eq(10).html(row.practicalMoney);
                    }
                    $("table tbody").find("tr").eq(index-1).find("td").eq(9).html(row.planMoney);
                    $("table tbody").find("tr").eq(index-1).find("td").eq(10).html(row.practicalMoney);

                }else if("commodityHandleTenet" === field){
                    if(row.commodityHandleTenet === '置换' || row.commodityHandleTenet === '核减施工费' ||
                        row.commodityHandleTenet === '欠供不在发生' || row.commodityHandleTenet === '欠供转乙供'){
                        //实际列入工程投资的材料金额  =  出库数*单价
                        row.practicalMoney = (row.unitPrice * row.actualQuantityIssued).toFixed(2)
                        $("table tbody").find("tr").eq(index-1).find("td").eq(10).html(row.practicalMoney);
                    } else if(row.commodityHandleTenet === '退料' || row.commodityHandleTenet === '欠供补领'){
                        //实际列入工程投资的材料金额  =  审定数*单价
                        row.practicalMoney = (row.unitPrice * row.examineCount).toFixed(2)
                        $("table tbody").find("tr").eq(index-1).find("td").eq(10).html(row.practicalMoney);
                    }
                }

                //获取所在行材料类型
                var materialsType = row.materialsType
                var planMoneyAll = 0;
                var practicalMoneyAll = 0;
                var collectRow;
                var collectAllRow;
                for(var i=0,l=data.length;i<l;i++){
                    var planMoney = data[i].planMoney.replace(/,/g, "");
                    var practicalMoney = data[i].practicalMoney.replace(/,/g, "");
                    if(data[i].materialsType === materialsType){
                        planMoneyAll = parseFloat(planMoneyAll) + parseFloat(planMoney);
                        practicalMoneyAll = parseFloat(practicalMoneyAll) + parseFloat(practicalMoney);
                    }
                }
                for(var i=0,l=data.length;i<l;i++){
                    if(data[i].showType === materialsType){
                        collectRow = data[i].index;

                        data[i].planMoney = numberDispose(planMoneyAll.toFixed(2)) ;
                        data[i].practicalMoney = numberDispose(practicalMoneyAll.toFixed(2)) ;
                    }
                }
                //对合计行进行处理
                $("table tbody").find("tr").eq(collectRow-1).find("td").eq(9).html(numberDispose(planMoneyAll.toFixed(2)));
                $("table tbody").find("tr").eq(collectRow-1).find("td").eq(10).html(numberDispose(practicalMoneyAll.toFixed(2)));


                var planMoneyCollect = 0;
                var practicalMoneyCollect = 0;
                for(var i=0,l=data.length;i<l;i++){
                    var planMoney = data[i].planMoney.replace(/,/g, "");
                    var practicalMoney = data[i].practicalMoney.replace(/,/g, "");
                    switch (data[i].showType) {
                        case "设备":
                            planMoneyCollect = parseFloat(planMoneyCollect) + parseFloat(planMoney);
                            practicalMoneyCollect = parseFloat(practicalMoneyCollect) + parseFloat(practicalMoney);
                            break;
                        case "材料":
                            planMoneyCollect = parseFloat(planMoneyCollect) + parseFloat(planMoney);
                            practicalMoneyCollect = parseFloat(practicalMoneyCollect) + parseFloat(practicalMoney);
                            break;
                        case "-":
                            planMoneyCollect = parseFloat(planMoneyCollect) + parseFloat(planMoney);
                            practicalMoneyCollect = parseFloat(practicalMoneyCollect) + parseFloat(practicalMoney);
                            break;
                    }
                }

                for(var i=0,l=data.length;i<l;i++){
                    if(data[i].showType === "汇总"){
                        collectAllRow = data[i].index;
                        data[i].planMoney = numberDispose(planMoneyCollect.toFixed(2)) ;
                        data[i].practicalMoney = numberDispose(practicalMoneyCollect.toFixed(2)) ;
                    }
                }

                //对汇总行进行处理
                $("table tbody").find("tr").eq(collectAllRow-1).find("td").eq(9).html(numberDispose(planMoneyCollect.toFixed(2)));
                $("table tbody").find("tr").eq(collectAllRow-1).find("td").eq(10).html(numberDispose(practicalMoneyCollect.toFixed(2)));
            }


        });

        function numberDispose(number) {
            var numberArray = number.split(".");
            return parseFloat(numberArray[0]).toLocaleString() + "." + numberArray[1];
        }


        if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端


            $('#dataTable').bootstrapTable("toggleView");
        }

        $('#dataTable').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
            'check-all.bs.table uncheck-all.bs.table', function () {
            $('#remove').prop('disabled', ! $('#dataTable').bootstrapTable('getSelections').length);
            $('#view,#edit').prop('disabled', $('#dataTable').bootstrapTable('getSelections').length!=1);
        });
        $("#btnImport").click(function(){
            jp.open({
                type: 2,
                area: [500, 200],
                auto: true,
                title:"导入数据",
                content: "${ctx}/tag/importExcel" ,
                btn: [/*'导出模板',*/'确定', '关闭'],
                /*btn1: function () {
                    jp.downloadFile('${ctx}/supply/particulars/templates')
                },*/
                btn1: function(index, layero){
                    var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                    iframeWin.contentWindow.importExcel('${ctx}/supply/particulars/import', function (data) {
                        if(data.success){
                            jp.success(data.msg);
                            refresh();
                        }else{
                            jp.error(data.msg);
                        }
                        jp.close(index);
                    });//调用保存事件
                    return false;
                },
                btn2: function(index){
                    //  jp.close(index);
                }
            });
        });


        function post(URL, PARAMS) {
            var temp = document.createElement("form");
            temp.action = URL;
            temp.method = "post";
            temp.style.display = "none";
            for (var x in PARAMS) {
                var opt = document.createElement("textarea");
                opt.name = x;
                opt.value = PARAMS[x];
                temp.appendChild(opt);
            }
            document.body.appendChild(temp);
            temp.submit();
            return temp;
        }

        $("#export").click(function(){//导出Excel文件物料
            var data= $('#dataTable').bootstrapTable('getData',{useCurrentPage:false,includeHiddenRows:false});

            //var info = $("#dataTable").bootstrapTable('getData');
            var jsonStr = JSON.stringify(data);       //转为JSON字符串
            post('${ctx}/supply/particulars/export',{json:jsonStr})
        });
        $("#exportpro").click(function(){//导出Excel文件
            jp.downloadFile('${ctx}/supply/particulars/exportpro');
        });


        $("#search").click("click", function() {// 绑定查询按扭
            $('#dataTable').bootstrapTable('refresh');
        });

        $("#reset").click("click", function() {// 绑定查询按扭
            $("#searchForm  input").val("");
            $("#searchForm  select").val("");
            $("#searchForm  .select-item").html("");
            $('#dataTable').bootstrapTable('refresh');
        });

    });



function getIdSelections() {
    return $.map($("#dataTable").bootstrapTable('getSelections'), function (row) {
        return row.id
    });
}

function deleteAll(){
    jp.confirm('确认要删除该记录信息吗？', function(){
        jp.loading();
        jp.get("${ctx}/supply/particulars/deleteAll?ids=" + getIdSelections(), function(data){
            if(data.success){
                $('#dataTable').bootstrapTable('refresh');
                jp.success(data.msg);
            }else{
                jp.error(data.msg);
            }
        })

    })
}

//刷新列表
function refresh(){
    $('#dataTable').bootstrapTable('refresh');
}

function add(){
    jp.openSaveDialog('新增', "${ctx}/supply/particulars/form",'800px', '500px');
}



function edit(id){//没有权限时，不显示确定按钮
    if(id == undefined){
        id = getIdSelections();
    }
    jp.openSaveDialog('编辑', "${ctx}/supply/particulars/form?id=" + id, '800px', '500px');
}

function view(id){//没有权限时，不显示确定按钮
    if(id == undefined){
        id = getIdSelections();
    }
    jp.openViewDialog('查看', "${ctx}/supply/particulars/view?id=" + id, '800px', '500px');
}

function viewMaterials(materialNumber){//没有权限时，不显示确定按钮
    jp.openViewDialog('查看', "${ctx}/supply/particulars/viewMaterials?particularMaterialNumber=" + materialNumber, '90%', '90%');
}



</script>
