var  refreshFlag = false;
//1.品质管理体系：2.文件控制：3.供应商品质控制：4.产品质量控制：5.不合格品控制：7.量测仪器管制：8.产品包装与防护：
var tableName = [
    {
        name:'quality',
        height:''
    },
    {
        name:'file',
        height:''
    },
    {
        name:'supplier',
        height:''
    },
    {
        name:'product',
        height:''
    },{
        name:'unqualified',
        height:300
    },{
        name:'mark',
        height:200
    },
    {
        name:'measure',
        height:''
    },{
        name:'package',
        height:''
    },{
        name:'device',
        height:''
    },{
        name:'change',
        height:200
    },{
        name:'produce',
        height:200
    },{
        name:'price',
        height:''
    },{
        name:'giveDate',
        height:200
    },{
        name:'payDate',
        height:200
    }
];

var tableArray = [];
tableName.forEach(node=>{
    let tableGrid = {
        parms: {},
        node: node.name,
        height: node.height||400,
        gridManager: null,
        data: null,
        columns:getGridColumns(node.name),
    };
    tableArray.push(tableGrid);
})

//创建表格（参数、列、插入的节点、数据源）
function loadGrid(obj) {
    var isApply = isApplyProcUnit();
    var subProcUnitId = getSubProcUnitId();
    obj.gridManager = UICtrl.grid("#" + obj.node, {
        columns: obj.columns,
        dataAction: "local",
        data: obj.data,
        parms: obj.parms,
        pageSize: 20,
        toolbar: UICtrl.getDefaultToolbarOptions({}),
        usePager: false,
        enabledEdit: true,
        delayLoad: false,
        // width: "100%",
        height: obj.height,
        heightDiff: -8,
        checkbox: true,
        fixedCellHeight: true,
        selectRowButtonOnly: true,
        onAfterEdit:function(...arg) {
            countSum()
        },
    });
    UICtrl.setSearchAreaToggle(obj.gridManager);
}

$(function () {
    // 切换Tab
    $('#produceSupplierReview-ledger-tab').tab({
        onClick: function ($clicked) {
            switch ($clicked.attr('id')) {
            }
        }
    });
})

$(document).ready(function () {
    initialize();
    bindEvent();
});

function initialize() {
    $('#produceSupplierInfoList').fileList({
        bizId : $("#attbizId").val()
    });
    //获取数据源初始化表格
    Public.ajax(web_app.name + '/produceSupplierReview/slicedNewSupplierReviewItemList.ajax', {newSupplierReviewId: getId()}, function (data) {
        //根据定义列拆除实体对象，封装成每个table对应的数据集
        tableArray.forEach(obj => {
            if (Public.isNotBlank(getId())){
                var Rows = [];
                data.Rows.map(item => {
                    if (item.itemType == obj.node){
                        let row = {};
                        obj.columns.forEach(col => {
                            if (item.hasOwnProperty(col.name)) {
                                row[col.name] = item[col.name];
                            }
                            // if (col.name == 'selfRate' || col.name == 'sgRate'){
                            //     var columnsItems = col.columns;
                            //     columnsItems.forEach(colItem =>{
                            //         if (item.hasOwnProperty(colItem.name)) {
                            //             row[colItem.name] = item[colItem.name];
                            //         }
                            //     })
                            // }else {
                            //     if (item.hasOwnProperty(col.name)) {
                            //         row[col.name] = item[col.name];
                            //     }
                            // }
                        });
                        Rows.push(row);
                    }
                })
                obj.data = {
                    Rows : Rows
                };
            }else {
                var Rows = [];
                data.Rows.map(item => {
                    if (item.itemType == obj.node){
                        let row = {};
                        obj.columns.forEach(col => {
                            // if (col.name == 'reviewItem'){
                            //     row[col.name] = item[col.name];
                            // }
                            row[col.name] = item[col.name];
                        });
                        Rows.push(row);
                    }
                })
                obj.data = {
                    Rows : Rows
                };
            }

        });
        useArrayTable(loadGrid);
    })

}

function getGridColumns(node) {
    var columns = [];
    columns.push({display: "评估项目", name: "reviewItem", title: "评估项目", width: 500, minWidth: 60, type: "string", align: "left",
        totalSummary: {
            render: function (suminf, column, cell) {
                return "本项最终得分（见本行最后格）";
            }
        }
    });
    if (node == 'price' || node == 'giveDate' || node == 'payDate') {
        columns.push({display: "评分", name: "noQualifiedDes", title: "评分", width: 300, minWidth: 60, type: "string", align: "center"
            ,totalSummary:{type:'tsum'},
            editor: {required: false, type: "text", mask: '999.99'}
        });
    }else {
        columns.push({display: "自评分",
            // columns:[
            //     {display: "0", title: "0", name: "selfRate0", width: 100, minWidth: 40, type: "string", align: "left", totalSummary:{type:'sum'}, editor: { type: 'text',required:false}},
            //     {display: "1", title: "1", name: "selfRate1", width: 100, minWidth: 40, type: "string", align: "left", totalSummary:{type:'sum'}, editor: { type: 'text',required:false}},
            //     {display: "2", title: "2", name: "selfRate2", width: 100, minWidth: 40, type: "string", align: "left", totalSummary:{type:'sum'}, editor: { type: 'text',required:false}},
            // ],
            name: "selfRate", width: 100, minWidth: 60, type: "number", align: "center",
            totalSummary:{
                type:'tsum',
            },
            editor: {
                type: 'dictionary',
                data: {name: 'selfRate'},
                textField: 'selfRateTextView',
                valueField: 'selfRate',
                required: false,
                render: function (item) {
                    return item.selfRateTextView;
                },

            }
        });
        columns.push({display: "SG评分",
            // columns:[
            //     {display: "0", title: "0", name: "sgRate0", width: 100, minWidth: 40, type: "string", align: "left", totalSummary:{type:'sum'}, editor: { type: 'text',required:false}},
            //     {display: "1", title: "1", name: "sgRate1", width: 100, minWidth: 40, type: "string", align: "left", totalSummary:{type:'sum'}, editor: { type: 'text',required:false}},
            //     {display: "2", title: "2", name: "sgRate2", width: 100, minWidth: 40, type: "string", align: "left", totalSummary:{type:'sum'}, editor: { type: 'text',required:false}},
            // ],
            name: "sgRate", width: 100, minWidth: 60, type: "number", align: "center",totalSummary:{type:'tsum'},
            editor: {
                type: 'dictionary',
                data: {name: 'sgRate'},
                textField: 'sgRateTextView',
                valueField: 'sgRate',
                required: false,
                render: function (item) {
                    return item.sgRateTextView;
                },
            }
        });
        columns.push({display: "不合格现象描述", name: "noQualifiedDes", title: "不合格现象描述", width: 300, minWidth: 60, type: "string", align: "center",
            totalSummary: {
            type: 'tsum',
                render:function( ...arg) {
                    return arg[3].reduce((pre, cur) => pre + MathUtil.add(cur.selfRate,0) + MathUtil.add(cur.sgRate,0), 0)
                },
            },
            editor: { type: 'text',required:false}});
    }
    columns.push({display: "评估项目类型", title: "评估项目类型",name: "itemType", width: 1, align: "left", type: "string",hide: true});
    columns.push({display: "id", title: "id",name: "id", width: 1, align: "left", type: "string",hide: true});
    columns.push({display: "newSupplierReviewId", title: "newSupplierReviewId",name: "newSupplierReviewId", width: 1, align: "left", type: "string",hide: true});
    return columns;
}

function countSum() {
    //获取dom
    const rows = [...document.querySelectorAll('.l-grid-totalsummary')].filter((v, i) => i % 2 != 0)
    var qualitySum = 0;
    var projectSum = 0;
    var purchaseSum = 0;
    rows.forEach(row => {
        [...row.children].reduce((pre, cur) => {
            if (cur.attributes['columnname'].value == 'sgRate'
            || cur.attributes['columnname'].value == 'selfRate') {
                //品管评估项目
                if (cur.id.includes("quality") ||
                    cur.id.includes("file") ||
                    cur.id.includes("supplier") ||
                    cur.id.includes("product") ||
                    cur.id.includes("unqualified") ||
                    cur.id.includes("mark") ||
                    cur.id.includes("measure") ||
                    cur.id.includes("package")){
                    qualitySum = MathUtil.add(qualitySum, parseInt(cur.innerText))
                }

                //工程评估项目
                if (cur.id.includes("device") ||
                    cur.id.includes("change") ||
                    cur.id.includes("produce")){
                    projectSum = MathUtil.add(projectSum, parseInt(cur.innerText))
                }
                return pre + parseInt(cur.innerText);
            }
            if (cur.attributes['columnname'].value == 'noQualifiedDes') {
                //三、采购评估项目：
                if (cur.id.includes("price") ||
                    cur.id.includes("giveDate") ||
                    cur.id.includes("payDate")){
                    purchaseSum = MathUtil.add(purchaseSum,parseInt(cur.innerText));
                }else {
                    cur.innerText = pre
                }
            }
            return pre
        }, 0)
    })
    // 一、品管评估项目：
    //总得分
    $("#qualitySum").val(qualitySum)
    //品质得分=（总得分/110）*100 :
    var qualityTotal = MathUtil.div(qualitySum,1.1).toFixed(2)
    $("#qualityTotal").val(qualityTotal)

    //二、工程评估项目：
    //总得分
    $("#projectSum").val(projectSum);
    //工程评分=（总得分/18）*100
    var projectTotal = MathUtil.div(projectSum,0.18).toFixed(2)
    $("#projectTotal").val(projectTotal);


    //采购评分=以上三项目总和/3=
    var purchaseSumValue = MathUtil.div(purchaseSum,3).toFixed(2);
    $("#purchaseSum").val(purchaseSumValue);

    //最终得分=品管评分*35%+工程评分子量35%+采购评分*30%=
    var finalSumValue = (MathUtil.mul(qualityTotal,0.35) + MathUtil.mul(projectTotal,0.35) + MathUtil.mul(purchaseSumValue,0.3)).toFixed(2)
    $("#finalSum").val(finalSumValue);
}

function bindEvent(){
    //供应商名称
    $('#produceSupplierReviewInfo input[name="name"]').change(function (data) {
        var value = $("#produceSupplierReviewInfo #name").val();
        $("#newSupplierReviewInfo #name").val(value);
    })

    //公司地址
    $('#produceSupplierReviewInfo input[name="address"]').change(function (data) {
        var value = $("#produceSupplierReviewInfo #address").val();
        $("#newSupplierReviewInfo #address").val(value);
    })

    //联系电话
    $('#produceSupplierReviewInfo input[name="tel"]').change(function (data) {
        var value = $("#produceSupplierReviewInfo #tel").val();
        $("#newSupplierReviewInfo #tel").val(value);
    })

    //传真号码
    $('#produceSupplierReviewInfo input[name="fax"]').change(function (data) {
        var value = $("#produceSupplierReviewInfo #fax").val();
        $("#newSupplierReviewInfo #fax").val(value);
    })

    //联系人
    $('#produceSupplierReviewInfo input[name="businessContact"]').change(function (data) {
        var value = $("#produceSupplierReviewInfo #businessContact").val();
        $("#newSupplierReviewInfo #businessContact").val(value);
    })


    var _businessLicenseImg=$('#showBusinessLicensePicture');
    var _businessLicensePath=$('#businessLicense').val();
    if (Public.isNotBlank(_businessLicensePath)) {
        _businessLicenseImg[0].src = $.getCSRFUrl('attachment/downFileBySavePath.ajax',{file:_businessLicensePath});
    }

    var _taxLicenseImg=$('#showTaxLicensePicture');
    var _taxLicensePath=$('#taxLicense').val();
    if (Public.isNotBlank(_taxLicensePath)) {
        _taxLicenseImg[0].src = $.getCSRFUrl('attachment/downFileBySavePath.ajax',{file:_taxLicensePath});
    }
    //注册上传照片事件
    $('#addBusinessLicense').uploadButton({
        filetype: ['jpg','gif','jpeg','png','bmp'],
        afterUpload: function(data){
            _businessLicenseImg[0].src = $.getCSRFUrl('attachmentDownFile.ajax',{id:data.id});
        },
        param: function(){
            if(getId() == ''){
                Public.errorTip('请先保存表单。');
                return false;
            }
            return {bizCode: 'businessLicensePicture', bizId: getId(), flag: 'false', deleteOld: 'true', returnPath: 'true'};
        }
    });
    $('#addTaxLicense').uploadButton({
        filetype: ['jpg','gif','jpeg','png','bmp'],
        afterUpload: function(data){
            _taxLicenseImg[0].src = $.getCSRFUrl('attachmentDownFile.ajax',{id:data.id});
        },
        param: function(){
            if(getId() == ''){
                Public.errorTip('请先保存表单。');
                return false;
            }
            return {bizCode: 'taxLicensePicture', bizId: getId(), flag: 'false', deleteOld: 'true', returnPath: 'true'};
        }
    });
}

//重置表单
function resetForm(obj) {
    $(obj).formClean();
}

/**
 * 流程引擎回调设置打样的id
 * @param value 打样申请的id
 */
function setId(id) {
    $("#id").val(id);
}

/**
 * 流程引擎获取打样申请id的回掉方法。
 * @return 打样申请的id
 */
function getId() {
    return $("#id").val() || "";
}

function getExtendedData(processAction) {

    //回退、打回、转交时，不需要验证必填项是否已经填写；
    if (processAction == ProcessAction.BACK
        || processAction == ProcessAction.REPLENISH
        || processAction == ProcessAction.TRANSMIT) {
        //不验证
        $('#submitForm').attr('check', false);
    }
    let resultArray = useArrayTable(getTableDataAll);
    let resultList = [];
    resultArray.forEach(results=>{
        results.forEach(result=>{
            resultList.push(result);
        })
    })
    let extendedData = {};
    extendedData.resultList = Public.encodeJSONURI(resultList);
    return extendedData;

}

function getTableDataAll(obj) {
    let result = DataUtil.getGridData({
        gridManager: obj.gridManager,
        isAllData: true
    });
    return result;
}

//调用数组
function useArrayTable(func, ...data) {
    const results = tableArray.map((item) => {
        return func(item, ...data);
    });
    return results;
}


//UICtrl中校验是否允许编辑
// function businessJudgmentUnit() {
//     var isApply = isApplyProcUnit();
//     if (isApply) {
//         return true;
//     }else {
//         UICtrl.setDisable($("#submitForm"));
//     }
//     return true;
// }



