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

$(function () {
    initDict("gx_contract_subject,gx_contract_type,contract_item_subject")
    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});
    //     }
    // })
    let d = [];
    d = getDictList('gx_contract_subject')
    let  d1 = getDictList('contract_item_subject')
    let mergedList = d.concat(d1);
    //资产类别/科目
    $("#subjectCode").combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        panelHeight: '200',
        limitToList: 'true',
        editable: true,
        data: mergedList
    });


    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 printById(ids) {
    var iframe = document.getElementById('printOrder');
    iframe.src = g.ctx + 'pc/order/deliveryOrder/page/print?ids=' + ids;
}

function initDataGrid() {
    let toolbar = [];
    // 收货单创建列表
    el.replayTableHidden = true;
    el.deliveryTableHidden = false;
    toolbar = [{
        text: '导出', id: 'btn_export', iconCls: 'icon-download', handler: function () {
            let exportFields = [
                {
                    field: 'contractCode', title: '合同编号', width: '120', align: 'left'
                },
              {
                    field: 'lineNo',
                    title: '合同序号',
                    width: 80
                },
               {
                    field: 'itemCode',
                    title: '采购申请行号',
                    width: 80
                },{
                    field: 'contractCompanyName', title: '甲方名称',
                    width: '100', align: 'left'
                }
                , {
                    field: 'contractCompanyCode', title: '甲方编码',
                    width: '100', align: 'left'
                },
                {
                    field: 'contractSupplierName', title: '乙方名称',
                    width: '60', align: 'left'
                }, {
                    field: 'contractSupplierCode', title: '乙方编码',
                    width: '60', align: 'left'
                },
                {
                    field: 'contractType', title: '合同类型',
                    width: '85', align: 'left',
                    formatter: function (value) {
                        return getDicName('gx_contract_type', value)
                    }
                },
                {
                    field: 'materialName', title: '物料名称',
                    width: '100', align: 'left'
                },
                {
                    field: 'subjectCode', title: '资产类别',
                    width: '200', align: 'left',
                    formatter: function (value) { return getDicName('gx_contract_subject',value) }
                },
                {
                    field: 'materialSpec', title: '规格型号',
                    width: '80', align: 'left',
                },
                {
                    field: 'materialBrand', title: '品牌',
                    width: '100', align: 'left',
                },
                {
                    field: 'purchaseCode', title: '请购单编号',
                    width: '100', align: 'left',
                }, {
                    field: 'basisUnit', title: '单位',
                    width: '100', align: 'left',
                },
                {
                    field: 'num', title: '订单数量',
                    width: '100', align: 'left',
                },
                {
                    field: 'onlineNum', title: '在途数量',
                    width: '100', align: 'left'
                },
                {
                    field: 'receiveNum', title: '接收数量',
                    width: '100', align: 'left',
                },
                {
                    field: 'returnNum', title: '已退数量',
                    width: '100', align: 'left',
                },
                {
                    field: 'unclearNum', title: '未清数量',
                    width: '100', align: 'left',
                    color: 13
                },
                {
                    field: 'deliverableNum', title: '可送数量',
                    color: 13
                },
                {
                    field: 'shipmentNum', title: '收货数量',
                    width: '100', align: 'left', editor: {type: 'textbox'}
                },
                {
                    field: 'useDeptName', title: '请购部门',
                    width: '100', align: 'left'
                },
                {
                    field: 'useDeptCode', title: '请购部门编码',
                    width: '100', align: 'left'
                },
                {
                    field: 'userName', title: '使用人名称',
                    width: '120', align: 'left',
                },{
                    field: 'userCode', title: '使用人代码',
                    width: '120', align: 'left',
                },
                {
                    field: 'costCenterCode', title: '成本中心', width: '100', align: 'left',
                    hidden: true
                },
                {
                    field: 'price', title: '含税单价', width: '100', align: 'left'
                },
                {
                    field: 'noTaxPrice', title: '未税单价', width: '100', align: 'left'
                },
                {
                    field: 'stockPoint', title: '存放地点',
                    color: 13,
                    width: '200', align: 'left',
                    hidden: true
                },
                {
                    field: 'remark', title: '资产用途',
                    color: 13,
                    width: '200', align: 'left',
                    hidden: true
                },
                {
                    field: 'remark', title: '资产情况',
                    color: 13,
                    width: '200', align: 'left',
                    hidden: true

                }
            ]
        }
    }, {
        id: 'create_contract_delivery_btn', text: '创建收货单', iconCls: 'icon-redo', handler: function () {
            createDeliveryOrder()
        }
    },{
        text: '导入创建收货单',
        iconCls: 'icon-import',
        id: 'import',
        handler: function () {
                overseasImport();
        }
    }
    ]

    let searchHeight = $(el.searchForm).outerHeight();
    let pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);
    $(el.tb).edatagrid({
        method: "GET",
        url: g.ctx + 'pc/contract/manage/rest/selectReceiptContractDetailListPage',
        loadMsg: '数据远程载入中,请等待...',
        pagination: true,
        idField: 'id',
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        checkbox: true,
        singleSelect: false,
        height: el.bodyHeight - searchHeight,
        frozenColumns: [[{field: 'ck', checkbox: true},
            {
                field: 'contractCode', title: '合同编号', width: '120', align: 'left',sortable: true
            }, {
                field: 'lineNo',
                title: '合同序号',
                width: '80',
                sortable: true
            }

        ]],
        columns: [[
            {
                field: 'contractCompanyName', title: '甲方名称',
                width: '230', align: 'left',
                hidden: true
            }
            , {
                field: 'contractCompanyCode', title: '甲方编码',
                width: '100', align: 'left',sortable: true
            },
            {
                field: 'contractSupplierName', title: '乙方名称',
                width: '230', align: 'left',sortable: true
            }, {
                field: 'contractSupplierCode', title: '乙方编码',
                width: '60', align: 'left',
                hidden: true
            },
            {
                field: 'contractType', title: '合同类型',
                width: '120', align: 'left',sortable: true,
                 formatter: function (value) {
                       return getDicName('gx_contract_type', value)
                 }
            }, {
                field: 'subjectCode', title: '资产类别',
                width: '100', align: 'left',
                formatter: function (value) { return getDicName('gx_contract_subject',value) }
            },
            {
                field: 'materialName', title: '物料名称',
                width: '100', align: 'left'
            },
            {
                field: 'materialSpec', title: '规格型号',
                width: '80', align: 'left',
            },
            {
                field: 'materialBrand', title: '品牌',
                width: '100', align: 'left',
            },
            {
                field: 'basisUnit', title: '单位',
                width: '100', align: 'left',
            },
            {
                field: 'num', title: '订单数量',
                width: '100', align: 'left',
            },
            {
                field: 'deliverableNum', title: '可送数量',
                color: 13,

            },
            {
                field: 'shipmentNum', title: '收货数量',
                width: '100', align: 'left', editor: {type: 'textbox'}
            },
            {
                field: 'onlineNum', title: '在途数量',
                width: '100', align: 'left'
            },
            {
                field: 'receiveNum', title: '已接收数量',
                width: '100', align: 'left',
            },
            {
                field: 'returnNum', title: '已退数量',
                width: '100', align: 'left',
            },
            {
                field: 'unclearNum', title: '未清数量',
                width: '100', align: 'left',
                color: 13
            },
            {
                field: 'purchaseCode', title: '请购单编号',
                width: '150', align: 'left',
            },
            {
                field: 'itemCode',
                title: '采购申请行号',
                width: '80'
            },
            {
                field: 'useDeptCode', title: '请购部门',
                width: '100', align: 'left',
            },
            {
                field: 'userName',  title: '使用人名称',
                width: '120', align: 'left',
            },
            {
                field: 'userCode', title: '使用人代码',
                width: '120', align: 'left',
            },{
                field: 'price', title: '含税单价', width: '100', align: 'left'
            },
            {
                field: 'noTaxPrice', title: '未税单价', width: '100', align: 'left'
            },
            {
                field: 'costCenterCode', title: '成本中心', width: '100', align: 'left',
                hidden: true
            },
            {
                field: 'stockPoint', title: '存放地点',
                color: 13,
                width: '200', align: 'left',
                hidden: true
            },
            {
                field: 'remark', title: '资产用途',
                color: 13,
                width: '200', align: 'left',
                hidden: true
            },
            {
                field: 'remark', title: '资产情况',
                color: 13,
                width: '200', align: 'left',
                hidden: true

            },
            {
                field: 'contractPurchaseGroup', title: '采购组',
                color: 13,
                width: '200', align: 'left'
            },
            {
                field: 'checkState', title: '验收状态',
                color: 13,
                width: '200', align: 'left',
                hidden: true
            },
            {
                field: 'checkNo', title: '验收单号',
                color: 13,
                width: '200', align: 'left',
                hidden: true
            }]],
        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: {
                            shipmentNum: el.editData[tmp.id].shipmentNum
                        }
                    });
                }
            });
            reloadOk = true;
        },
        onBeforeLoad: function (param) {
            displayButtonByUserRole('delivery.contract.index');
            reloadOk = false;
        }
    });
}

function overseasImport() {
    var importDialog = openImportExcelDialog(
        'static/excel/合同收货单导入.xls',
        '合同收货单导入',
        function (file) {
            let formData = new FormData();
            formData.append("file", file);

            var loading = topWin.layer.msg('处理中', {
                icon: 16,
                shade: [0.1, '#000'],
                time: false
            });

            // 兼容关闭：easyui dialog / layer index / topWin 的 dialog
            function closeImportDialog() {
                try {
                    // 1) EasyUI dialog(jQuery对象)
                    if (importDialog && typeof importDialog.dialog === "function") {
                        importDialog.dialog('close');
                        return;
                    }
                    // 2) 如果返回的是 layer 的 index（数字）
                    if (typeof importDialog === "number") {
                        topWin.layer.close(importDialog);
                        return;
                    }
                    // 3) 如果弹窗是在 topWin 创建的，可能需要用 topWin.$ 去关
                    if (topWin && topWin.$ && importDialog) {
                        try {
                            topWin.$(importDialog).dialog('close');
                            return;
                        } catch (e) {}
                    }
                } catch (e) {
                    console.error("closeImportDialog failed:", e);
                }
            }

            $.ajax({
                url: g.ctx + 'pc/contract/contractDelivery/rest/contractDeliveryImport',
                method: "POST",
                data: formData,
                contentType: false,
                processData: false,

                success: function (data) {
                    topWin.layer.alert("导入成功", { icon: 1 }, function (idx) {
                        topWin.layer.close(idx);

                        // 确保即使 loadData 报错，也能关闭弹窗
                        try {
                            $("#tb").datagrid("loadData", data);
                        } catch (e) {
                            console.error("datagrid loadData error:", e, data);
                            // 如果你们后端返回不是 {total,rows}，可以在这里适配：
                            // $("#tb").datagrid("loadData", { total: data.length || 0, rows: data });
                        } finally {
                            closeImportDialog();
                        }
                    });
                },

                complete: function () {
                    topWin.layer.close(loading);
                },

                error: function (xhr) {
                    let msg = "导入失败";
                    try {
                        msg = JSON.parse(xhr.responseText).message || msg;
                    } catch (e) {}
                    topWin.layer.alert(msg, { icon: 2, shadeClose: true, title: '温馨提示' });
                }
            });
        }
    );
}

// 创建送货单
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 contractCompanyCode; // 甲方编码
    let contractSupplierCode; // 乙方编码
    let hasLowValueConsumable = false; // 标记是否存在低值易耗品
    let hasOtherType = false; // 标记是否存在其他类型

    for (let i = 0; i < rows.length; i++) {
        let row = rows[i];
        // 甲方校验
        if (!contractCompanyCode) {
            contractCompanyCode = row.contractCompanyCode;
        } else if (contractCompanyCode !== row.contractCompanyCode) {
            topWin.layer.alert(
                "甲方不一致，请确认！",
                { icon: 0 }
            );
            return;
        }
        // 乙方校验
        if (!contractSupplierCode) {
            contractSupplierCode = row.contractSupplierCode;
        } else if (contractSupplierCode !== row.contractSupplierCode) {
            topWin.layer.alert(
                "乙方不一致，请确认！",
                { icon: 0 }
            );
            return;
        }
        if(row.deliverableNum <= 0){
            topWin.layer.alert(
                "勾选行的可送数量必须大于0！",
                { icon: 0 }
            );

            return;
        }

        //收货数据不能大于订单数量校验
        // if(row.shipmentNum > row.num){
        //     topWin.layer.msg("勾选行的收货数量不能大于订单数量！");
        //     return;
        // }
        // if(row.deliverableNum > row.num){
        //     topWin.layer.msg("勾选行的可送数量不能大于订单数量！");
        //     return;
        // }
        // if(row.unclearNum > row.num){
        //     topWin.layer.msg("勾选行的未清数量不能大于订单数量！");
        //     return;
        // }
        // if( (row.shipmentNum + row.unclearNum)> row.num){
        //     topWin.layer.msg("勾选行的在途数量加上送货数量不能大于订单数量！");
        //     return;
        // }
        // 合同类型校验
        const contractType = row.contractType;
        if (contractType === '04 | 资产-低值易耗品') {
            hasLowValueConsumable = true;
        } else if (contractType) { // 排除空值
            hasOtherType = true;
        }


    }
// 类型校验逻辑
    if (hasLowValueConsumable) {
        if (hasOtherType) {
            topWin.layer.alert(
                "资产-低值易耗品”的合同明细，不能与其他类型的合同一起创建在同一个收货单！",
                { icon: 0 }
            );
            return;
        }
    }
    //校验通过页面进行赋值传值
        for (let i = 0; i < rows.length; i++) {
            let row = rows[i];
            //数量校验

            let data = row;
            data.id = null; //确保不会被脏数据赋值
            data.purchaser = row.contractCompanyName; //甲方名称
            data.purchaserCode = row.contractCompanyCode; //甲方code
            data.supplier =  row.contractSupplierName; //供应商名称
            data.supplierCode =  row.contractSupplierCode; //供应商代码
            data.purchaseGroup =  row.contractPurchaseGroup; //采购组代码
           // data.receiptLineNo =  row.; //收货单行号没有
            data.contractNo =  row.contractCode; //合同编号
            data.lineNo = row.lineNo;//合同序号
            data.assetCategory =  row.subjectCode; //资产类别
            data.itemName =  row.materialName; //物品名称
            data.modelSpec =  row.materialSpec; //型号规格/参数
            data.brand =  row.materialBrand; //品牌
            data.requisitionNo =  row.purchaseCode; //请购单编号
            data.itemCode = row.itemCode;//采购申请行号
            data.unit =  row.basisUnit; //单位
            data.orderQuantity =  row.num; //订单数量
            data.receivedQuantity =  row.shipmentNum; //收货数量
            //data.deviceSerialNo =  row.; //设备序列号页面自己填写
            data.acceptanceStatus =  row.checkState; //验收状态  新加字段，待查询取值
            data.acceptanceNumber =  row.checkNo; //验收单号  新加字段，待查询取值
            data.userCode = row.userCode;// 请购人代码
            data.custodian = row.userName; // 请购人名称
            data.requisitionDept =  row.useDeptCode; //请购部门
            data.useDeptName =  row.useDeptName; //请购部门名称
            data.noTaxPrice = row.noTaxPrice;
            data.price = row.price;
            data.costCenter =  row.costCenterCode; //成本中心
            data.storageLocation =  row.stockPoint; //存放地点
            dataList.push(data);
        }
        let closingGuard = false; // 防止递归关闭
        localStorage.setItem("contract_delivery", JSON.stringify(dataList));
        let url = g.ctx + "pc/contract/contractDelivery/page/createOrUpdate";
        var contractDeliveryCreateDialog = openDialog("contractDeliveryCreateDialog", url, {
            title: '收货单创建',
            width: '100%',
            height: '100%',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                contractDeliveryCreateDialog.dialog('destroy');
            },
            buttons: [{
                text: '发货', iconCls: 'icon-save', handler: function () {
                    topWin.frames['contractDeliveryCreateDialog'].saveOrUpdate(function (id,shipment) {
                        topWin.layer.msg('发货成功', {icon: 1});
                        contractDeliveryCreateDialog.dialog('close');
                        $(el.tb).datagrid('reload');
                        $(el.tb).datagrid('clearChecked');
                    }, 1);
                }
            },{
                text: '关闭', iconCls: 'icon-cancel', handler: function () {
debugger;
                    // 1) 从弹窗iframe里取 businessId（#id）
                    var businessId = null;
                    try {
                        var iframe = contractDeliveryCreateDialog.dialog('body').find('iframe')[0];
                        var win = iframe && iframe.contentWindow;
                        if (win) {
                            // 兼容：子页用了jquery
                            businessId = win.$ ? win.$("#id").val() : (win.document.getElementById("id") || {}).value;
                        }
                    } catch (e) {
                        console.error("get businessId failed:", e);
                    }

                    // 2) 没有id就直接关（说明可能还没生成临时单据）
                    if (!businessId) {
                        contractDeliveryCreateDialog.dialog('close');
                        return;
                    }

                    // 3) 父页面直接调用删除接口（不依赖子页 deleteDelivery）
                    var loading = topWin.layer.msg('处理中...', {icon: 16, shade: 0.1, time: 0});

                    $.ajax({
                        url: g.ctx + "pc/contract/contractDelivery/rest/blankDeliveryRemove",
                        type: "POST",
                        data: { id: businessId }, // ✅ 用表单方式最稳

                        complete: function () {
                            topWin.layer.close(loading);
                        },
                        success: function () {
                            // 删除成功再关闭弹窗
                            contractDeliveryCreateDialog.dialog('close');
                        },
                        error: function (xhr) {
                            console.error("blankDeliveryRemove error:", xhr);
                            // 你想“失败也关闭”就放行；想“失败不让关”就return
                            contractDeliveryCreateDialog.dialog('close');
                        }
                    });
                }
            }
            ]
        })

}
