/**
 *
 * 合同退回货单创建列表页
 * @version 1.0
 */

$(function () {
    initDict("po_item_type,gx_contract_subject,gx_contract_type,contract_item_subject,contract_item_subject_sap")
    initNecessaryDatas("pc/sys/factory/rest/allList,pc/sys/purchaseGroup/rest/listAll")
    $.ajax({
        url: '/pc/contract/manage/rest/getContractCategory',
        type: 'POST',
        async: false,
        data: {"mroFlag":1}, //mro
        success: function (res) {
            var filteredData = res.filter(function(item) {
                return item.code !== "资产采购-模具";
            });
            $("#contractType").combobox({
                valueField: 'code',
                textField: 'name',
                editable: false,
                panelHeight: 'auto',
                data: filteredData
            })
        },
        error: function (res) {
            topWin.layer.alert(res.responseJSON.message, {icon: 2});
        }
    })
    initDataGrid();

});
var reloadOk = false;
var submitFlag = false;
let el = {
    tb: '#tb',
    searchForm: '#searchForm',
    bodyHeight: document.documentElement.clientHeight,
    formDialog: null,
    replayTableHidden: false, // 采购确认列表隐藏
    deliveryTableHidden: true, //送货单创建列表隐藏
    contractCode: '#contractCode',
    contractType: '#contractType',
    contractState: '#contractState',
    contractPurchaseGroup: '#contractPurchaseGroup',
    contractFactoryCode: '#contractFactoryCode',
    contractSupplierCode: '#contractSupplierCode',
    subjectCode: '#subjectCode',
    materialName: '#materialName',
    editIndex: undefined,
    editData: {},
    changQu: []
};

function initDataGrid() {
    let toolbar = [];
    // 收货单创建列表
    el.replayTableHidden = true;
    el.deliveryTableHidden = false;
    toolbar = [{
        id: 'create_return_order_btn', text: '创建退货单', iconCls: 'icon-redo', handler: function () {
            createDeliveryOrder()
        }
    }
    ]

    let searchHeight = $(el.searchForm).outerHeight();
    let pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);
    $(el.tb).edatagrid({
        method: "GET",
        url: g.ctx + 'pc/contract/contractDeliveryDetail/rest/selectreturnOrdertDetailListPage',
        loadMsg: '数据远程载入中,请等待...',
        pagination: true,
        idField: 'id',
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        checkbox: true,
        singleSelect: false,
        height: el.bodyHeight - searchHeight,
        columns: [[
            {field: 'ck', checkbox: true},
            {
                field: 'deliveryNo',
                title: '收货单号',
                width: 140,
                sortable: true
            },
            {
                field: 'receiptLineNo',
                title: '收货单行号',
                width: 80,
                sortable: true
            },
            {
                field: 'deliveryStatus',
                title: '单据状态(收货单)',
                width: 100,formatter: function (value, row) {
                    if (!value) {
                        return ""
                    }
                    if (row.deleteFlag === 1) {
                        return "<span style='color: red;' >已删除</span>"
                    }
                    if (value === 1) {
                        return "<span style='color: yellowgreen;' >已发货</span>"
                    }
                    if (value === 2) {
                        return "已收货"
                    }
                    if (value === 3) {
                        return "<span style='color: seagreen;' >已记账</span>"
                    }
                }, sortable: true
            },
            {
                field: 'contractNo', title: '合同编号',
                width: '120', align: 'left', sortable: true
            }
            , {
                field: 'contractSeq', title: '合同序号',
                width: '100', align: 'left', sortable: true
            },
            {
                field: 'contractType', title: '合同类型',
                width: '85', align: 'left',
                formatter: function (value) {
                    return getDicName('gx_contract_type', value)
                }
            },
            {
                field: 'purchaser', title: '甲方编码',
                width: '230', align: 'left', sortable: true
            }, {
                field: 'supplier', title: '乙方名称',
                width: '230', align: 'left', sortable: true
            },
            {
                field: 'assetCategory', title: '资产类别',
                width: '85', align: 'left',
                formatter: function (value) { return getDicName('gx_contract_subject',value) },
                sortable: true
            },
            {
                field: 'itemName', title: '物品名称',
                width: '100', align: 'left'
            },
            {
                field: 'modelSpec', title: '规格型号',
                width: '200', align: 'left'
            },
            {
                field: 'brand', title: '品牌',
                width: '80', align: 'left',
            },
            {
                field: 'requisitionNo', title: '请购单编号',
                width: '120', align: 'left',
            },
            {
                field: 'unit', title: '单位',
                width: '100', align: 'left',
            }, {
                field: 'orderQuantity', title: '订单数量',
                width: '100', align: 'left',
            },
            {
                field: 'returnableQuantity', title: '可退数量',
                width: '100', align: 'left',
            },
            {
                field: 'returnQuantity', title: '退货数量',
                width: '100', align: 'left', editor: {type: 'textbox'}
            },
            {
                field: 'receivedQuantity', title: '收货数量',
                width: '100', align: 'left',
            },
            {
                field: 'returnedQuantity', title: '已退数量',
                width: '100', align: 'left',
            },
            {
                field: 'deviceSerialNo', title: '设备序列号',
                width: '100', align: 'left',
            },
            {
                field: 'useDeptName', title: '请购部门名称',
                width: '100', align: 'left',
            },
            {
                field: 'requisitionDept', title: '请购部门code',
                width: '100', align: 'left',
            },
            {
                field: 'custodian', title: '请购人名称',
                width: '100', align: 'left',
                color: 13
            },
            {
                field: 'userCode', title: '请购人code',
                width: '100', align: 'left',
                color: 13
            },
            {
                field: 'costCenter', title: '成本中心',width: '100',
                color: 13

            },
            {
                field: 'storageLocation', title: '存放地点',
                width: '100', align: 'left',
            },  {
                field: 'purchaserCode', title: '甲方编码',
                width: '100', align: 'left',
            }, {
                field: 'supplierCode', title: '乙方编码',
                width: '100', align: 'left',
            }, {
                field: 'purchaseGroup', title: '采购组',
                width: '100', align: 'left',
            },
            {
                field: 'price', title: '含税单价', width: '100', align: 'left'
            },
            {
                field: 'noTaxPrice', title: '未税单价', width: '100', align: 'left'
            }
         ]],
        toolbar: toolbar,
        onAfterEdit: function (rowIndex, rowData, changes) {
            //结束编辑后记录编辑数据
            el.editData[rowData.id] = rowData;
        },
        onLoadSuccess: function (data) {
            data.rows.forEach(function (tmp, i) {
                if (el.editData[tmp.id]) {
                    $(el.tb).datagrid('updateRow', {
                        index: $(el.tb).datagrid('getRowIndex', tmp), row: {
                            returnQuantity: el.editData[tmp.id].returnQuantity
                        }
                    });
                }
            });
            reloadOk = true;
        },
        onBeforeLoad: function (param) {
            displayButtonByUserRole('return.order.index');
            reloadOk = false;
        }
    });
}
// 创建送货单
function createDeliveryOrder() {
    debugger;
    let dataList = [];
    $(el.tb).edatagrid("saveRow");
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length === 0) {
        topWin.layer.msg("请选择收货明细");
        return;
    }
    //勾选数据页面赋值校验
    //1.校验勾选明细中的甲方是不是完全一致
    //2.校验勾选明细中的乙方是不是完全一致
    //3.1、所有被勾选的明细，合同“甲方”需要一致，不一致则报错”甲方不一致，请确认！”
    // 2、所有被勾选的明细，合同”乙方“需要一致，不一致则报错”甲方不一致，请确认！”
    let purchaserCode; // 甲方编码
    let supplierCode; // 乙方编码
    for (let i = 0; i < rows.length; i++) {
        let row = rows[i];
        const contractNo = row.contractNo;
        const contractSeq = row.contractSeq;
        // 甲方校验
        if (!purchaserCode) {
            purchaserCode = row.purchaserCode;
        } else if (purchaserCode !== row.purchaserCode) {
            topWin.layer.msg("甲方不一致，请确认！");
            return;
        }
        // 乙方校验
        if (!supplierCode) {
            supplierCode = row.supplierCode;
        } else if (supplierCode !== row.supplierCode) {
            topWin.layer.msg("乙方不一致，请确认！");
            return;
        }

        // 退货数量校验
         const returnQuantity = row.returnQuantity;
         const returnableQuantity = row.returnableQuantity;
        //可退货数量大于0才允许创建
        if(returnableQuantity <= 0){
            topWin.layer.msg("合同编号："+contractNo +"合同序号："+contractSeq+"请勾选可退数量大于0的数据，请确认！");
            return;
        }
         if(returnQuantity > returnableQuantity){
             topWin.layer.msg("合同编号："+contractNo +"合同序号："+contractSeq+"退货数量不能大于可退数量，请确认！");
             return;
         }
    }
    //校验通过页面进行赋值传值
        for (let i = 0; i < rows.length; i++) {
            let row = rows[i];
            //数量校验
            let data = row;
            data.id = null; //确保不会被脏数据赋值
                data.deliveryNo = row.deliveryNo;  //收货单号
                data.receiptLineNo = row.receiptLineNo; //收货单行号
                data.contractNo = row.contractNo; //合同编号
                data.contractSeq = row.contractSeq; //合同序号
                data.purchaser = row.purchaser; //购货方(甲方名称)
                data.purchaserCode = row.purchaserCode; //甲方代码
                data.supplier = row.supplier; //供应商名称
                data.supplierCode = row.supplierCode; //供应商代码
                data.assetCategory = row.assetCategory; //资产类别
                data.itemName = row.itemName; //物品名称
                data.modelSpec = row.modelSpec; //型号规格/参数
                data.brand = row.brand; //品牌
                data.requisitionNo = row.requisitionNo; //请购单编号
                data.unit = row.unit; //单位
                data.orderQuantity = row.orderQuantity; //订单数量
                data.receivedQuantity = row.receivedQuantity; //收货数量
                data.deviceSerialNo = row.deviceSerialNo; //设备序列号
                data.requisitionDept = row.requisitionDept; //请购部门code
                data.useDeptName = row.useDeptName;//请购部门名称
                data.custodian = row.custodian; //保管人名称
                data.userCode =row.userCode;//保管人code
                data.noTaxPrice = row.noTaxPrice;
                data.price = row.price;
                data.costCenter = row.costCenter; //成本中心
                data.storageLocation = row.storageLocation; //存放地点
                data.purchaseGroup = row.purchaseGroup;//采购组
            dataList.push(data);
        }
        debugger;
        localStorage.setItem("contract_return_order", JSON.stringify(dataList));
        let url = g.ctx + "pc/contract/returnOrder/page/createOrUpdate";
        var contractReturnOrderCreateDialog = openDialog("contractReturnOrderCreateDialog", url, {
            title: '退货单创建',
            width: '100%',
            height: '100%',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                contractReturnOrderCreateDialog.dialog('destroy');
            },
            buttons: [{
                text: '退货', iconCls: 'icon-save', handler: function () {
                    topWin.frames['contractReturnOrderCreateDialog'].saveOrUpdate(function (id,shipment) {
                        topWin.layer.msg('退货成功', {icon: 1});
                        contractReturnOrderCreateDialog.dialog('close');
                        $(el.tb).datagrid('reload');
                        $(el.tb).datagrid('clearChecked');
                    }, 1);
                }
            }, {
                text: '关闭', iconCls: 'icon-cancel', handler: function () {
                    contractReturnOrderCreateDialog.dialog('close');
                }
            }]
        })

}
