/**
 *
 * @author BOGON
 * @version 1.0
 */
/**
 * 注意！！！！！！
 * 这个页面是查看和送货单创建
 * 如果是送货单创建，是直接从订单明细中跳转过来，需要在localStore中获取数据
 * 字段需要对应上
 * 如果是送货单界面进来，直接通过送货单id
 * @type {boolean}
 */
var readonly = false;
let el = {
    tb: '#tb',
    bodyHeight: document.documentElement.clientHeight,
    dataForm: '#dataForm',
    dataList: [],
    editIndex: undefined,
    editData: {},
    receiver:'#receiver',
    receiverName:'receiverName'
};
var delSubmitFlag = 0
$(function () {
    debugger;
    initDict('gx_contract_subject');
    $(el.receiver).combobox({
        required: true,
        url: g.ctx + 'pc/sys/dict/getDicByType?type=statement_apply_list',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '--- 请选择 ---',
        editable: false,
        onSelect: function (data) {
            $(el.receiver).val(data.code);
            $(el.receiverName).val(data.name);

        }
    });
    //取收货人
    initPageComBoBox();
    //需要把地址从字典取出来
    if (!createFlag()) {
        //需要从Ajax请求数据
        $.ajax({
            url: g.ctx + 'pc/contract/contractDeliveryDetail/rest/listDeliverDetail',
            type: "GET",
            data: {id:$("#id").val()},
            success: function (d) {
                el.dataList = d.rows
                loadGrid(el.dataList)
            }
        })
    } else {
        el.dataList = JSON.parse(localStorage.getItem("contract_delivery"));
        var firstItem = el.dataList[0];
        var purchaser = firstItem.purchaser;//收货方名称
        var purchaserCode = firstItem.purchaserCode;//收货方代码
        var supplier = firstItem.supplier;//供应商名称
        var supplierCode = firstItem.supplierCode;//供应商代码
        var purchaseGroup = firstItem.purchaseGroup;//采购组初始化
        $('#purchaser').textbox('setValue', purchaser);
        $('#purchaserCode').textbox('setValue', purchaserCode);
        $('#supplier').textbox('setValue', supplier);
        $('#supplierCode').textbox('setValue', supplierCode);
        $('#purchaseGroup').combobox('setValue', purchaseGroup);
    //    $(el.receiver).combobox('setValue',$("#logUserNo").val());

        loadGrid(el.dataList)
    }
    if (readOnly()) {
        //查看和审核所有控件只读
        // 设置所有 datetimebox 为只读模式
        $('.easyui-datebox').datebox('readonly', true);

        // 设置所有 NumberBox 为只读模式
        $('.easyui-numberbox').numberbox('readonly', true);

        // 设置所有 TextBox 为只读模式
        $('.easyui-textbox').textbox('readonly', true);

        // 设置所有 ComboBox 为只读模式
        $('.easyui-combobox').combobox('readonly', true);
    }
});

/**
 * 初始化页面下拉框
 */
function initPageComBoBox() {
    $("#documentType").combobox({
        valueField: 'value',
        textField: 'label',
        value: 1,
        data: [
            {label: '收货', value: 1},
            {label: '退货', value: 2}
        ],
        editable: false,
        panelHeight: 'auto'
    });
}

function loadGrid(dataList) {
    var searchHeight = $(el.tb).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 40, 30);
    const toolbar = []
    let frozenColumns = []

    if (!createFlag()) {
        frozenColumns = [
            {field: 'ck', checkbox: true},
            {
                field: 'receiptLineNo', title: '收货单行号',
                width: '100', align: 'left'
            },
            {
                field: 'contractNo', title: '合同编号',
                width: '150', align: 'left'
            },
            {
                field: 'assetCategory', title: '资产类别',
                width: '100', align: 'left',
                formatter: function (value) { return getDicName('gx_contract_subject',value) }
            },
            {
                field: 'itemName', title: '物品名称',
                width: '200', align: 'left'
            }
        ]
        // 在第一个元素后添加一个新元素
        frozenColumns.splice(1, 0, {
            field: 'deleteFlag',
            title: '删除标识',
            width: 70,
            formatter: function (value) {
                switch (Number(value)) {
                    case 1:
                        return '<span style="color: red;">已删除</span>';
                    default:
                        return '未删除';
                }
            }
        });
    } else {
        frozenColumns = [
            {field: 'ck', checkbox: true},
            {
                field: 'receiptLineNo', title: '收货单行号',
                width: '100', align: 'left'
            },
            {
                field: 'contractNo', title: '合同编号',
                width: '150', align: 'left'
            },{
                field: 'lineNo',
                title: '合同序号',
                width: 80
            },
            {
                field: 'itemCode',
                title: '采购申请行号',
                width: 80
            },
            {
                field: 'assetCategory', title: '资产类别',
                width: '100', align: 'left',
                formatter: function (value) { return getDicName('gx_contract_subject',value) }
            },
            {
                field: 'itemName', title: '物品名称',
                width: '200', align: 'left'
            }
        ]
    }

    let columns = [
       // numColumn,
        {
            field: 'modelSpec', title: '型号规格/参数',
            width: '100', align: 'left'
        },
        {
            field: 'brand', title: '品牌',
            width: '100', align: 'left',
        },

        {
            field: 'unit', title: '单位',
            width: '100', align: 'left',
        },
        {
            field: 'orderQuantity', title: '订单数量',
            width: '100', align: 'left',
        },
        {
            field: 'receivedQuantity', title: '收货数量',
            width: '100', align: 'left',
            editor: {type: 'numberbox', options: {precision: 3}}
        },
        {
            field: 'deviceSerialNo', title: '设备序列号',
            width: '100', align: 'left',
            editor: {type: 'textbox'}
        },
        {
            field: 'acceptanceStatus', title: '验收状态',
            width: '100', align: 'left', formatter: function (value, row) {
        if (!value) {
            return ""
        }
        if (value === "01") {
            return "<span style='color: yellowgreen;' >未验收</span>"
        }
        if (value === "02") {
            return "已验收"
        }
    }
        },
        {
            field: 'acceptanceNo', title: '验收单号',
            width: '120', align: 'left',
        },
        {
            field: 'useDeptName', title: '请购部门名称',
            width: '150', align: 'left'
        },
        {
            field: 'requisitionDept', title: '请购部门code',
            width: '150', align: 'left'
        },
        {
            field: 'custodian', title: '请购人名称',
            width: '150', align: 'left'
        },
        {
            field: 'userCode', title: '请购人代码',
            width: '150', align: 'left'
        },
        {
            field: 'requisitionNo', title: '请购单编号',
            width: '150', align: 'left',
        },
        {
            field: 'costCenter', title: '成本中心',
            width: '200', align: 'left'
        },
        {
            field: 'storageLocation', title: '存放地点',
            width: '200', align: 'left'
        },
        {
            field: 'price', title: '含税单价', width: '100', align: 'left'
        },
        {
            field: 'noTaxPrice', title: '未税单价', width: '100', align: 'left'
        }
    ]
        let cols = frozenColumns.concat(columns)
        $(el.tb).edatagrid({
            loadMsg: '数据远程载入中,请等待...',
            singleSelect: false,
            method: "GET",
            pageSize: pager.pageSize,
            pageList: pager.pageList,
            data: dataList,
            height: el.bodyHeight - searchHeight - 200,
            pagination: true,
            autoSave: true,
            onClickRow: function (index, row) {
                $(this).edatagrid('editRow', index);
            },
            columns: [cols],
            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: {
                                deliveryNum: el.editData[tmp.id].deliveryNum
                            }
                        });
                    }
                });
            },
            onBeforeLoad: function (param) {
                return $(el.tb).edatagrid("saveRow");
            },
            toolbar: toolbar
        });


}


function saveOrUpdate(callback, deliveryFlag) {

    //做订单数据校验

    // 表单校验
    if (!$(el.dataForm).form('validate')) {
        topWin.layer.msg("有必填项不可为空", {time: 2000});
        return;
    }


    // 关闭明细行编辑
    $(el.tb).edatagrid("saveRow");
    let itemList = [];
    let rows = $(el.tb).datagrid("getRows");
    for (let i = 0; i < rows.length; i++) {
        let row = rows[i];
        if (row.receivedQuantity === 0) {
            layer.confirm(pre + "收货数量不可为0", {icon: 2, title: '温馨提示'});
            return;
        }
        //校验收货数量不能大于订单数量
       if(row.receivedQuantity > row.orderQuantity){
           topWin.layer.msg("收货合同编号："+ row.contractNo +"合同行号："+ row.lineNo + "填写的收货数量不能大于订单行单数量", {time: 2000});
           return;
       }
        let items = {
            receiptLineNo:row.receiptLineNo,
            contractNo: row.contractNo,
            contractSeq:row.lineNo,
            assetCategory: row.assetCategory,
            itemName: row.itemName,
            modelSpec: row.modelSpec,
            brand: row.brand,
            requisitionNo: row.requisitionNo,
            itemCode:row.itemCode,
            unit: row.unit,
            orderQuantity: row.orderQuantity,
            receivedQuantity: row.receivedQuantity,
            deviceSerialNo: row.deviceSerialNo,
            acceptanceStatus: row.acceptanceStatus,
            acceptanceNumber: row.acceptanceNumber,
            useDeptName: row.useDeptName,
            requisitionDept: row.requisitionDept,
            custodian: row.custodian,
            userCode : row.userCode,
            noTaxPrice : row.noTaxPrice,
            price : row.price,
            costCenter: row.costCenter,
            storageLocation: row.storageLocation
        };
        itemList.push(items);
    }

    let formData = $(el.dataForm).serializeJson();
    formData.item = itemList;
    let load = topWin.layer.load(0);
     var directShipment = formData.directShipment;
     debugger;
    $.ajax({
    url: g.ctx + "pc/contract/contractDelivery/rest/save",
        contentType: "application/json",
        data: JSON.stringify(formData),
        type: "POST",
        complete: function () {
            topWin.layer.close(load);
        },
        success: function (data) {
            if (data.msg !== undefined) {
                // 只拼内容片段，不要 <html><head><body> 这一整套
                var msgHtml = [];
                msgHtml.push('<div style="text-align:left;">');
                msgHtml.push('<div style="margin-bottom:10px; font-weight:600;">提示信息</div>');
                msgHtml.push('<ul style="margin:0; padding-left:18px;">');

                for (var i = 0; i < data.msg.length; i++) {
                    msgHtml.push('<li style="margin:6px 0;">' + data.msg[i] + '</li>');
                }

                msgHtml.push('</ul>');
                msgHtml.push('</div>');

                topWin.layer.open({
                    type: 1,
                    title: '信息',
                    area: ['420px', '200px'],   // 2条信息够用，也不会挤
                    shade: 0.3,
                    resize: false,
                    scrollbar: false,          //  关键：不让 layer 弄滚动条
                    btnAlign: 'c',
                    content: '<div style="padding:18px 22px 8px 22px; font-size:14px; line-height:22px;">'
                        + msgHtml.join("")
                        + '</div>',
                    btn: ['确定'],
                    yes: function (index) {
                        topWin.layer.close(index);
                        callback(data.id, directShipment);
                    },
                    success: function (layero) {
                        // ✅ 再保险：强制内容区不出现滚动条
                        layero.find('.layui-layer-content').css('overflow', 'hidden');
                    }
                })
            }else {
                topWin.layer.msg('保存成功', {icon: 1});
                callback(data.id, directShipment);
            }
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });

}

function createFlag() {
    if (type === 1 || type === 2) {
        return false
    }
    return true
}

function readOnly() {
    if (type === 2) {
        return true
    }
    return false
}

