var purchaseOrderGridManager = null;
$(document).ready(function () {
        initUI();
    loadGrid();
    }
);

function initUI() {
    UICtrl.initDefaultLayout();
}

function loadGrid() {
    var toolbarOptions = UICtrl.getDefaultToolbarOptions({
        sapPrintProduceNoHandler: {
            id: 'sapPrintProduceNoHandler', text: 'SAP外协单打印', img:'fa-print', click: function(){
                sapPrintProduceNoHandler();
            }
        },
        sapPrintHandler: {
            id: 'sapPrintHandler', text: 'SAP外协单打印(无生产单号)', img:'fa-print', click: function(){
                printHandler();
            }
        },
        sendOutHandler: {
            id: 'sendOutHandler', text: '已外发', img:'fa-clipboard', click: function(){
                sendOutHandler();
            }
        },
      revokeApproveHandler: {
          id: 'revokeApproveHandler', text: '撤销审批', img: 'fa-trash', click: function () {
              var row = purchaseOrderGridManager.getSelectedRow();
              if (row.status != 3) {
                  Public.tip("请选择一条已完成的数据！");
                  return;
              }
              var loginId = $("#loginId").val();
              if (row.personMemberId != loginId) {
                  Public.tip("只能由创建人撤审！");
                  return;
              }
              UICtrl.showAjaxDialog({
                  url: web_app.name + '/sapPurchaseOrder/showRevokeDetail.load',
                  param:{id:row.id},
                  title: "撤审",
                  width: 400,
                  ok: function () {
                      var _self = this;
                      Public.ajax(web_app.name + '/sapPurchaseOrder/revokeApproval.ajax', {id: row.id,revokeReason: $("#revokeForm #revokeReason").val(),orderRevokeType:$("#orderRevokeType").val()}, function (msg) {
                          purchaseOrderGridManager.loadData();
                      });
                      _self.close();
                  }
              });
          }
        }
    });
    //debugger
    purchaseOrderGridManager = UICtrl.grid('#purchaseOrderGrid', {
            columns: [
                {display: "状态", name: "statusTextView", width: "100", align: "left", type: "string"},
                {display: "外发状态", name: "sendOutTextView", width: "100", align: "left", type: "string",
                    // render: function (item) {
                    //     return item.sendOut == 1 ? "已外发": "";
                    // }
                }
                , {display: "id", name: "id", width: "140", align: "left", type: "string", hide: true}
                , {display: "需求跟踪编号", name: "billCode", width: 150, minWidth: 60, type: "string", align: "center"}
                , {display: "采购订单号码", name: "ebeln", width: 150, minWidth: 60, type: "string", align: "center"}
                , {display: "采购订单类型", name: "bsart", width: 150, minWidth: 60, type: "string", align: "center"}
                , {display: "采购订单类型描述", name: "batxt", width: 150, minWidth: 60, type: "string", align: "center"}
                , {display: "供应商", name: "namel", width: 200, minWidth: 60, type: "string", align: "center"}
                , {display: "项目类别描述", name: "knttp", width: "100", align: "left", type: "string"}
                , {display: "sap回执", name: "message", width: 200, minWidth: 60, type: "string", align: "center"}
                , {display: "创建日期", name: "fillinDate", width: 140, minWidth: 60, type: "string", align: "center"}
                , {display: "创建人", name: "personMemberName", width: 140, minWidth: 60, type: "string", align: "center"}
                , {display: "撤审类型", name: "orderRevokeTypeTextView", width: 100, minWidth: 60, type: "date", align: "center"}
                , {display: "撤审原因", name: "revokeReason", width: 300, minWidth: 60, type: "date", align: "center"}
            ],
            dataAction: 'server',
            url: web_app.name + '/sapPurchaseOrder/slicedSapPurchaseOrderList.ajax?',
            //parms: {requireItemId: $("#prepareItemId").val()},
            toolbar: toolbarOptions,
            width: '99.8%',
            height: '100%',
            checkbox: true,
            pageSize: 20,
            heightDiff: -4,
            usePager: true,
            rownumbers: true,
            fixedCellHeight: true,
            onSuccess: function (data) {
                if (data.error) {
                    Public.tip(data.error);
                }
            }
            ,
            onDblClickRow: function (data, rowindex, rowobj) {
                viewHandler(data.id);
            }
        }
    );
    UICtrl.setSearchAreaToggle(purchaseOrderGridManager);
}

/**
 * 查看采购订单详情
 * @param id 采购订单id
 * @returns {boolean}
 */
function viewHandler(id) {
    if (!id) {
        var row = DataUtil.getSelectedRow(purchaseOrderGridManager);
        if (!row) {
            return row;
        }
        id = row.id;
    }
    UICtrl.addTabItem({
        tabid: 'viewPurchase' + id,
        text: '查看采购订单',
        url: web_app.name + '/sapPurchaseOrder/showSapPurchaseOrderDetail.job?isReadOnly=true&bizId=' + id
    });
}



function reloadPurchaseGrid() {
    var params = $("#queryMainForm").formToJSON();
    UICtrl.gridSearch(purchaseOrderGridManager, params);
}

function query(obj) {
    var param = $(obj).formToJSON();
    UICtrl.gridSearch(purchaseOrderGridManager, param);
}

function resetForm(obj) {
    $(obj).formClean();
}

function printHandler(){
    var rows = purchaseOrderGridManager.getSelectedRows();
    if (rows.length == 0) {
        Public.tip('请选择数据!');
        return;
    }
    var ids = [];
    for (var i = 0; i < rows.length; i++){
        var row=rows[i];
        var count = row.count;
        //工序外协ZNB3
        //成品外购的类型是ZNB1+knttp包含‘M’
        if ((row.bsart == "ZNB1" && row.knttp.indexOf("M") !== -1) || row.bsart == "ZNB3"){
            var url='/sapPurchaseOrder/print.load';
            for (let j = 0; j < count; j++) {
                Public.openPostWindow(web_app.name+url,{id:row.id,j:j});
            }

        }else {
            Public.tip("请选择工序外协单或者外购单");
            return false;
        }
    }
}

function sapPrintProduceNoHandler(){
    // var row = DataUtil.getUpdateRow(purchaseOrderGridManager);
    // if (!row) {
    //     return;
    // }
    // var url='/sapPurchaseOrder/printProduceNo.load';
    // Public.openPostWindow(web_app.name+url,{id: row.id});
    var rows = purchaseOrderGridManager.getSelectedRows();
    if (rows.length == 0) {
        Public.tip('请选择数据!');
        return;
    }
    var ids = [];
    for (var i = 0; i < rows.length; i++){
        var row=rows[i];
        var count = row.count;
        //工序外协ZNB3
        //成品外购的类型是ZNB1+knttp包含‘M’
        if ((row.bsart == "ZNB1" && row.knttp.indexOf("M") !== -1) || row.bsart == "ZNB3"){
            var url='/sapPurchaseOrder/printProduceNo.load';
            for (let j = 0; j <count; j++) {
                Public.openPostWindow(web_app.name+url,{id:row.id,j:j});
            }
        }else {
            Public.tip("请选择工序外协单或者外购单");
            return false;
        }
    }
}

function sendOutHandler(){
    var rows = purchaseOrderGridManager.getSelectedRows();
    if (rows.length == 0) {
        Public.tip('请选择数据!');
        return;
    }
    var ids = [];
    for (var i = 0; i < rows.length; i++){
        var row=rows[i];
        if (row.status != "3"){
            Public.tip("请审批完成并发送订单给供应商后才能标记外发状态");
            return false;
        }

        //工序外协ZNB3
        //成品外购的类型是ZNB1+knttp包含‘M’
        if ((row.bsart == "ZNB1" && row.knttp.indexOf("M") !== -1) || row.bsart == "ZNB3"){

        }else {
            Public.tip("采购订单类型是生产性物品采购申请并且项目类别描述是M，或者工序外协采购订单才能标记外发状态");
            return false;
        }

        ids.push(row.id)
    }
    Public.ajax(web_app.name + "/sapPurchaseOrder/sendOutProcess.ajax",{ids:$.toJSON(ids)},function () {
        reloadPurchaseGrid();
    })

}

