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

var page = {
    directShipmentChange: function (val) {
        if (val === '2') {
            $("#expressNo").textbox({required: false})
            $("#expressCode").combobox({required: true})
            $("#expressNo").textbox("readonly", false)
            $("#expressCode").combobox("readonly", false)
        } else {
            $("#expressNo").textbox({required: false})
            $("#expressCode").combobox({required: false})
            $("#expressNo").textbox("clear")
            $("#expressNo").textbox("readonly", true)
            $("#expressCode").combobox("readonly", true)
        }
    },
    factoryChange: function (val) {
        $("#dockerCode").combobox("clear")
        $("#dockerCode").combobox("reload", g.ctx + 'pc/order/appointmentDocker/rest/listAll?factory=' + val.code)
        $("#factoryName").val(val.name)
        $("#receiverAddress").combobox("setValue", val.address)
    },
    addSupplier: function () {
        let url = g.ctx + "pc/supplier/supplierSelect?single=1"
        var supplierDialogElement = openDialog("supplierDialog", url, {
            title: "供应商选择",
            width: '650px',
            height: '80%',
            cache: false,
            modal: true,
            border: false,
            draggable: true,
            shadow: false,
            onClose: function () {
                supplierDialogElement.dialog('destroy');
            },
            buttons: [{
                text: '选择', iconCls: 'icon-save', handler: function () {
                    topWin.frames['supplierDialog'].chooseRow(function (data) {
                        console.log(data)
                        $("#supplierName").textbox("setValue", data.supplierName)
                        $("#supplierErpCode").val(data.supplierErpCode)
                        supplierDialogElement.dialog('close');
                    });
                }
            }, {
                text: '关闭', iconCls: 'icon-cancel', handler: function () {
                    supplierDialogElement.dialog('close');
                }
            }]
        })
    },
    initgrid: function () {
        var frozenColumns = [
            {field: 'ck', checkbox: true},
            {
                field: 'purchaseOrderCode', title: 'SAP订单号',
                width: '100', align: 'left'
            },
            {
                field: 'purchaseOrderRow', title: '订单行号',
                width: '60', align: 'left'
            },
            {
                field: 'materialCode', title: '物料编码',
                width: '100', align: 'left'
            },
            {
                field: 'materialName', title: '物料名称',
                width: '200', align: 'left'
            }
        ]
        let columns = [
            {
                field: 'num', title: '送货数量',
                width: '100', align: 'left',
                editor: {type: 'numberbox', options: {precision: 3}}
            },
            {
                field: 'batchNum', title: '供应商批号',
                color: 13,
                width: '100', align: 'left', editor: {type: 'textbox'}
            },

            {
                field: 'enableNum', title: '可送数量',
                width: '100', align: 'left',
            },
            {
                field: 'noClearNum', title: '未清数量',
                width: '100', align: 'left',
            },
            {
                field: 'onlineNum', title: '在途送货单',
                width: '100', align: 'left',
            },
            {
                field: 'requireDate', title: '需求交期',
                width: '100', align: 'left',
            },
            {
                field: 'purchaseOrderNum', title: '订单数量',
                width: '100', align: 'left',
            },
            {
                field: 'unitCode', title: '订单单位',
                width: '80', align: 'left',
            },
            {
                field: 'factoryName', title: '收货工厂',
                width: '120', align: 'left'
            },

            {
                field: 'remark', title: '送货备注',
                color: 13,
                width: '200', align: 'left'
            },
        ]
        let cols = frozenColumns.concat(columns)
        $("#tb").datagrid({
            loadMsg: '数据远程载入中,请等待...',
            singleSelect: false,
            height: document.documentElement.clientHeight - 200,
            pagination: false,
            autoSave: true,
            columns: [cols],
            toolbar: [{
                text: '导入',
                iconCls: 'icon-import',
                id: 'import',
                handler: function () {
                    if (Number(overseasFlag) === 0){
                        $("#detailUpload .filebox-label").click();
                    }else {
                        page.overseasImport();
                    }
                }
            }]
        });
    },
    overseasImport: function () {
        let factoryCode =   $('#factoryCode').combobox('getValue');
        if(!factoryCode){
            layer.alert('请先选择工厂', {icon: 0});
            return false;
        }
        var importDialog = openImportExcelDialog('static/excel/境外送货单导入.xls','境外送货单导入',function(file){
            let formData = new FormData();
            formData.append("file", file);
            formData.append("factoryCode", factoryCode);
            var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
            $.ajax({
                url: g.ctx + 'pc/order/deliveryOrder/rest/overseasImport',
                method: "POST",
                data: formData,
                contentType: false,
                processData: false,
                success: function (data) {
                    topWin.layer.alert("导入成功", {icon: 1}, function (idx) {
                        topWin.layer.close(idx);
                        $("#tb").datagrid("loadData", data)
                        $("#totalCaseNum").textbox('setValue',data[0].totalCaseNum);
                        $("#entrustNo").textbox('setValue',data[0].entrustNo);
                        importDialog.dialog('close');
                    });
                },
                complete: function(data) {
                    topWin.layer.close(loading);
                },
                error: function (data) {
                    topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                }
            });
        });
    },
    dataImport: function () {
        var files = $("#detailFileInput").filebox('files'), formData = new FormData();
        if (files.length != 1) {
            return
        }
        formData.append('file', files[0]);
        let loadIndex = topWin.layer.load(0);
        var url = g.ctx + 'pc/order/deliveryOrder/rest/import'
        $.ajax({
            url: url, type: 'POST', data: formData, processData: false,
            contentType: false,
            async: false, // 设置为同步请求
            complete: function () {
                $("#detailFileInput").filebox('clear')
                topWin.layer.close(loadIndex);
            },
            success: function (obj) {
                $("#tb").datagrid("loadData", obj)
            }, error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    },
    saveOrUpdate: function (callback) {

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

        //日期比对 2024-08-05
        // let checkData = $(el.dataForm).serializeJson();
        let checkData = $("#dataForm").serializeJson();
        if (!checkData.entrustNo && overseasFlag === 1) {
            topWin.layer.msg("境外送货单创建委托单号必须输入!");
            return;
        }
        let diff = moment(checkData.deliveryDate).diff(moment(checkData.planDeliveryDate), 'days');
        if (diff > 0) {
            topWin.layer.msg("预计到货日期不能早于发货日期");
            return;
        }

        // 关闭明细行编辑
        let itemList = [];
        let rows = $("#tb").datagrid("getRows");
        let factoryCode;
        let companyCode;
        let companyName;
        let factoryName;
        let supplierCode = $("#supplierErpCode").val();
        for (let i = 0; i < rows.length; i++) {
            let row = rows[i];
            if (!factoryCode) {
                factoryCode = row.factoryCode;
                factoryName = row.factoryName;
            } else {
                if (factoryCode !== row.factoryCode) {
                    layer.confirm("第" + (i + 1) + "行，工厂不一致，请选择其他记录", {icon: 2, title: '温馨提示'});
                    return;
                }
            }
            if (!companyCode) {
                companyCode = row.companyCode;
                companyName = row.companyName;
            }
            if (supplierCode !== row.supplierCode && isSupplier === 0) {
                layer.confirm("第" + (i + 1) + "行，供应商编码不一致，请选择其他记录", {icon: 2, title: '温馨提示'});
                return;
            }
            if (row.orderState !== 7) {
                layer.confirm("第" + (i + 1) + "行，订单号【"+row.purchaseOrderCode+"】物料编码【"+row.materialCode+"】，订单未确认，请联系采购员通知供应商确认", {icon: 2, title: '温馨提示'});
                return;
            }
            let pre = "第" + (i + 1) + "行明细，";
            let deliveryNum = row.num;

            if (deliveryNum === 0) {
                layer.confirm(pre + "送货数量不可为0", {icon: 2, title: '温馨提示'});
                return;
            }
            // 未清数量
            let noClearNum = row.noClearNum == null ? 0 : row.noClearNum;
            if (noClearNum <= 0) {
                layer.confirm("第" + (i + 1) + "行，未清数量不足，请选择其他记录", {icon: 2, title: '温馨提示'});
                return;
            }
            // 在途数量
            let onlineNum = row.onlineNum == null ? 0 : row.onlineNum;
            // 最大可送货数量
            // let maxNum = noClearNum - onlineNum;
            var maxNum = math.floor(math.subtract(noClearNum, onlineNum), 4);
            if (maxNum < deliveryNum) {
                layer.confirm("第" + (i + 1) + "行，送货数量不得大于，未清数量减去在途送货单数量的值", {icon: 2, title: '温馨提示'});
                return false;
            }
            itemList.push(row);
        }

        let formData = $("#dataForm").serializeJson();
        formData.companyCode = companyCode
        formData.companyName = companyName
        formData.deliveryFlag = 1
        //境外送货单标识
        formData.overseasFlag = overseasFlag
        formData.item = itemList;
        formData.fileIds = $("#fileIds").attr('data-fileIds')
        let load = topWin.layer.load(0);
        var directShipment = formData.directShipment;
        const hiddenSupplierCode = formData.supplierErpCode;
        $.ajax({
            url: g.ctx + "pc/order/deliveryOrder/rest/save",
            contentType: "application/json",
            data: JSON.stringify(formData),
            type: "POST",
            complete: function () {
                topWin.layer.close(load);
            },
            success: function (data) {
                if (data.msg !== undefined) {
                    let html = []
                    html.push('<html lang="en">')
                    html.push('<head>')
                    html.push('<meta charset="UTF-8">')
                    html.push('<meta name="viewport" content="width=device-width, initial-scale=1.0">')
                    html.push('<style>')
                    html.push('body {\n' +
                        '        font-family: Arial, sans-serif;\n' +
                        '    }\n' +
                        '    table {\n' +
                        '        width: 100%;\n' +
                        '        border-collapse: collapse;\n' +
                        '        margin: 20px 0;\n' +
                        '    }\n' +
                        '    th, td {\n' +
                        '        border: 1px solid #ddd;\n' +
                        '        padding: 8px;\n' +
                        '        text-align: left;\n' +
                        '    }\n' +
                        '    th {\n' +
                        '        background-color: #f2f2f2;\n' +
                        '    }\n' +
                        '    .error {\n' +
                        '        color: red;\n' +
                        '    }')
                    html.push('</style>')
                    html.push('</head>')
                    html.push('<body>')
                    html.push('<table>\n' +
                        '    <tr>')
                    html.push('<td>')
                    for (const str of data.msg) {
                        html.push(str)
                    }
                    html.push('</td>')
                    html.push('</tr>')
                    html.push('</table>')
                    html.push('</body>')
                    html.push('</html>')
                    topWin.layer.open({
                        type: 1,
                        area: ['420px', '640px'], // 宽高
                        content: html.join(""),
                        btn: ['确定'],
                        yes: function (index, layero) {
                            topWin.layer.close(index);
                            callback(data.id, directShipment, hiddenSupplierCode);
                        }
                    })
                } else {
                    topWin.layer.msg('保存成功', {icon: 1});
                    callback(data.id, directShipment, hiddenSupplierCode);
                }
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    },
    dockerCodeLoadSuccess: function (data) {
        console.log(data)
        if (data.length === 1) {
            $("#dockerCode").combobox("setValue", data[0].dockerCode)
        }
    }
}
$(function () {
    page.initgrid()
    // 加载物流公司信息
    $("#expressCode").combobox({
        url: g.ctx + 'pc/sys/expressCompany/rest/listAll',
        method: "GET",
        valueField: 'ecCode',
        textField: 'ecName',
        panelHeight: 300,
        prompt: '-- 请选择 --',
        onSelect: function (data) {
            $("#expressName").val(data.ecName);
        }
    });
})