/**
 *
 * @author BOGON
 * @version 1.0
 */

var page = {
    submitFlag: 0,
    quotas: [], datagrid: {}, quotasName: {}, loadDetail: function () {
        $.ajax({
            url: g.ctx + "pc/spe/supAppraiseTemplate/rest/getFieldByPlan",
            method: "GET",
            data: {planId: id},
            success: function (data) {
                let frozenColumns = [{
                    field: 'date', title: '考核期间', width: 80, align: 'center'
                }, {
                    field: 'supplierName', title: '供应商名称', width: 120, align: 'center'
                }, {
                    field: 'supplierCode', title: '供应商</br>编码', width: 55, align: 'center'
                }, {
                    field: 'purchaseUser', title: '采购员', width: 50, align: 'center'
                }, {
                    field: 'sqe', title: 'SQE', width: 50, align: 'center'
                }, {
                    field: 'ce', title: 'CE', width: 50, align: 'center'
                }, {
                    field: 'purchaseCategoryNames', title: '物料类别', width: 100, align: 'center'
                }]
                let firstColumns = []
                let thirdColumns = []
                $.each(data, function (idx, itm) {
                    firstColumns.push({
                        field: itm.code, align: 'center', title: itm.name, colspan: itm.item.length
                    })
                    $.each(itm.item, function (ii, iit) {
                        var width = iit.name.length * 13 + 10;
                        if (itm.item.length === 1) {
                            width = 160
                        }
                        let cc = {
                            field: iit.code, title: iit.name, width: width
                        }
                        if (iit.code === 'ZW_PZ_26') {
                            cc = {
                                field: iit.code, title: iit.name, width: width,
                                formatter:function (value, row, index) {
                                    console.log(value)
                                    if (value==='A' || value==='B' ){
                                        return '<span style="background-color:#00ff00; color:#000000;">' + value + '</span>';
                                    }else if(value==='C'){
                                        return '<span style="background-color:#ffff00; color:#000000;">' + value + '</span>';
                                    }else if(value=== 'D'){
                                        return '<span style="background-color:#e3120b; color:#000000;">' + value + '</span>';
                                    } else {
                                        return value;
                                    }
                                }
                            }
                        }else {
                            page.quotasName[iit.code] = iit.name
                            if (iit.type === 4 && !page.readOnly()) {
                                page.quotas.push(iit.code)
                                if (iit.code === 'ZW_PZ_30' || iit.code === 'ZW_PZ_31') {
                                    cc["editor"] = {
                                        type: 'textbox', options: {
                                            validType: 'length[0,100]'
                                        }
                                    }
                                }else {
                                    cc["editor"] = {
                                        type: 'numberbox', options: {
                                            min: 0, max: iit.maxScore
                                        }
                                    }
                                }

                            }
                        }

                        thirdColumns.push(cc)
                    })
                })
                console.log(firstColumns)
                console.log(thirdColumns)
                page.initDetailTable([frozenColumns], [firstColumns, thirdColumns])
            },
            error: function (data) {
                topWin.layer.alert(JSON.parse(data.responseText).message);
            }
        });
    }, initDetailTable: function (frozenColumns, columns) {
        let h = document.documentElement.clientHeight - $("#searchForm").outerHeight() - 30

        let toolbar = [{
            text: '导出', iconCls: 'icon-download', handler: function () {
                let obj = page.searchParams()
                let params = Object.keys(obj)
                    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
                    .join('&');
                window.open(g.ctx + 'pc/spe/supAppraisePlan/rest/exportScore?planId=' + id + "&" + params + "&_" + new Date().valueOf())
            }
        }, {
            text: '导入', iconCls: 'icon-import', handler: function () {
                $("#fileUpload .filebox-label").click();
            }
        }, {
            text: '统计总分',
            iconCls: 'icon-layout-stop',
            handler: function () {
                page.calculationRow()
            }
        }
        ];
        if (type !== 2) {
            console.log(toolbar)
            toolbar.splice(1, 1)
        }
        if (page.readOnly()) {
            toolbar = [{
                text: '导出', iconCls: 'icon-download', handler: function () {
                    let obj = page.searchParams()
                    let params = Object.keys(obj)
                        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
                        .join('&');
                    window.open(g.ctx + 'pc/spe/supAppraisePlan/rest/exportScore1?planId=' + id + "&" + params + "&_" + new Date().valueOf())
                }
            }]
        }
        page.datagrid = $("#detail_tb").edatagrid({
            url: g.ctx + 'pc/spe/supAppraisePlan/rest/detailList?planId=' + id,
            method: "GET",
            loadMsg: '数据远程载入中,请等待...',
            singleSelect: true,
            pagination: false,
            autoSave: true,
            checkbox: true,
            rownumbers: true,
            height: h <= 0 ? 400 : h,
            frozenColumns: frozenColumns,
            columns: columns,
            toolbar: toolbar,
            onLoadSuccess: function () {
                $("#detail_tb").datagrid("resize")
            },
        })
    }, importExcel: function () {
        var filebox = $("#fileInput").filebox("files");
        if (filebox.length == 1) {
            var formData = new FormData();
            formData.append("file", filebox[0]);
            var index = topWin.layer.load(1, {
                shade: [0.1, '#eee'] //0.1透明度的白色背景
            });
            $.ajax({
                url: g.ctx + 'pc/spe/supAppraisePlan/rest/importScore',
                data: formData,
                type: 'POST',
                contentType: false,
                processData: false,
                success: function (d) {
                    page.datagrid.edatagrid("saveRow");
                    var rows = page.datagrid.edatagrid("getRows");
                    $.each(rows, function (index, item) {
                        var rowIndex = page.datagrid.edatagrid("getRowIndex", item);
                        var key = item.supplierCode;
                        var update = d[key];
                        var updateRow = {};
                        for (var prop in update) {
                            if ($.inArray(prop, page.quotas) != -1) {
                                updateRow[prop] = update[prop];
                            }
                        }
                        page.datagrid.edatagrid("updateRow", {index: rowIndex, row: updateRow});
                    });
                    topWin.layer.close(index);
                    $("#fileInput").filebox("clear")
                }
            })
        }
    }, tipMsgHanlder: function (skipError) {
        page.datagrid.edatagrid("saveRow");
        var rows = page.datagrid.edatagrid("getRows");
        var postRows = [];
        var tipMsg = [];
        $.each(rows, function (index, item) {
            var tmpRow = {};
            tmpRow.supplierCode = item.supplierCode;
            tmpRow.materialGroupCode = item.materialGroupCode;
            for (var prop in item) {
                if ($.inArray(prop, page.quotas) != -1) {
                    if (prop === 'ZW_PZ_31' || prop === 'ZW_PZ_30') {
                        tmpRow[prop] = item[prop];
                    } else {
                        if (item[prop] === '' || item[prop] == undefined) {
                            tipMsg.push('<span style="color: red;">供应商:' + tmpRow.supplierCode + '指标:' + page.quotasName[prop] + "</span>");
                            continue;
                        }
                        tmpRow[prop] = item[prop];
                    }
                }
            }
            postRows.push(tmpRow);
        });
        if (tipMsg.length > 0 && !skipError) {
            topWin.layer.alert(tipMsg.join("</br>") + "评分数据不全无法提交", {icon: 2});
            return false;
        }
        if (postRows.length <= 0) {
            topWin.layer.alert("请先打分再提交!", {icon: 2});
            return false;
        }
        return postRows;
    },
    calculationRow: function (call) {
        page.datagrid.edatagrid("saveRow");
        var rows = page.datagrid.edatagrid("getRows");
        if (rows.length <= 0) {
            return
        }
        var loadIndex = topWin.layer.msg('数据正在处理......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/spe/supAppraisePlan/rest/submitScore/1',
            data: JSON.stringify({planId: id, item: rows}),
            type: "POST",
            contentType: 'application/json',
            complete: function () {
                topWin.layer.close(loadIndex);
            },
            success: function (data) {
                topWin.layer.alert("操作成功!", {icon: 1}, function (idx) {
                    if (call != undefined) {
                        topWin.layer.close(idx);
                        call();
                    } else {
                        topWin.layer.close(idx);
                        page.datagrid.edatagrid("reload");
                    }

                });
            },
            error: function (data) {
                topWin.layer.alert(JSON.parse(data.responseText).message);
            }
        })
    },
    calculation: function (type, call) {
        if (!page.tipMsgHanlder()) {
            return;
        }
        if (page.submitFlag === 1) {
            return;
        }
        page.submitFlag = 1
        var loadIndex = topWin.layer.msg('数据正在处理......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/spe/supAppraisePlan/rest/submitScore/' + type,
            data: JSON.stringify({planId: id, item: page.tipMsgHanlder()}),
            type: "POST",
            contentType: 'application/json',
            complete: function () {
                topWin.layer.close(loadIndex);
                page.submitFlag = 0
            },
            success: function (data) {
                topWin.layer.alert("操作成功!", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    page.datagrid.edatagrid("reload");
                    if (call != undefined) {
                        call()
                    }
                });
            },
            error: function (data) {
                topWin.layer.alert(JSON.parse(data.responseText).message);
            }
        })
    }, save: function (call) {
        var confirIdx = topWin.layer.confirm('是否确认提交?', {
            icon: 3
        }, function (index) {
            if (!page.tipMsgHanlder(true)) {
                return;
            }
            if (page.submitFlag === 1) {
                return;
            }
            page.submitFlag = 1
            var loadIndex = topWin.layer.msg('数据正在处理......', {icon: 16, time: 0, shade: 0.1});
            $.ajax({
                url: g.ctx + "pc/spe/supAppraisePlan/rest/submitScore/0",
                data: JSON.stringify({planId: id, item: page.tipMsgHanlder(true)}),
                type: "POST",
                contentType: 'application/json',
                complete: function () {
                    topWin.layer.close(loadIndex);
                    topWin.layer.close(confirIdx)
                    page.submitFlag = 0
                },
                success: function (data) {
                    topWin.layer.alert("操作成功!", {icon: 1}, function (idx) {
                        topWin.layer.close(idx);
                        page.datagrid.edatagrid("reload");
                        if (call != undefined) {
                            call()
                        }
                    });
                },
                error: function (data) {
                    topWin.layer.alert(JSON.parse(data.responseText).message);
                }
            })
        });
    }, readOnly: function () {
        if (type === 1) {
            return true;
        }
        return false;
    }, searchParams: function () {
        var params = {};
        $.each($("#searchForm").serializeArray(), function (index, item) {
            if (params[item.name] != undefined) {
                params[item.name] = (params[item.name] + ',' + item.value).trim();
            } else {
                params[item.name] = ('' + item.value).trim();
            }
        });
        return params;
    }, searchInfo: function () {
        $("#detail_tb").datagrid('options').queryParams = page.searchParams();
        $("#detail_tb").datagrid('load');
    }, resetSearch: function () {
        $('#searchForm').form("clear");
        $("#detail_tb").datagrid('options').queryParams = $('#searchForm').serializeJson();
        $("#detail_tb").datagrid('load');
    },
}
$(function () {
    page.loadDetail();
    $("#fileInput").filebox({
        buttonText: 'Choose', buttonAlign: 'left', onChange: page.importExcel
    });
})