/**
 *
 * @author BOGON
 * @version 1.0
 */
/**
 * 注意！！！！！！
 * 这个页面是查看和送货单创建
 * 如果是送货单创建，是直接从订单明细中跳转过来，需要在localStore中获取数据
 * 字段需要对应上
 * 如果是送货单界面进来，直接通过送货单id
 * @type {boolean}
 */
var readonly = false;
let el = {
    tb: '#tb',
    bodyHeight: document.documentElement.clientHeight,
    dataForm: '#dataForm',
    expressName: "#expressName",
    dataList: [],
    editIndex: undefined,
    editData: {},
    expressCode: "#expressCode",
    changQu: []
};
var delSubmitFlag = 0
$(function () {
    initPageComBoBox();
    //需要把地址从字典取出来
    $("#receiverAddress").combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=delivery_address',
        valueField: 'name',
        method: 'get',
        textField: 'name',
        editable: false,
        loadFilter: function (data) {
            // let add = $("#receiverAddress").val()
            // data.push({name: add})
            console.log(data)
            return data;
        }
    })
    if (!createFlag()) {
        //需要从Ajax请求数据
        $.ajax({
            url: g.ctx + 'pc/order/deliveryOrderDetail/rest/listForDeliverOrder',
            type: "GET",
            data: {id: $("#id").val()},
            success: function (d) {
                el.dataList = d.rows
                loadGrid(el.dataList)
            }
        })
    } else {
        el.dataList = JSON.parse(localStorage.getItem("deliveryOrderRows"))
        if(specialRole===1){
            for(let i=0;i<el.dataList.length;i++){
                el.dataList[i].remark = ''
            }
        }
        for(let i=0;i<el.dataList.length;i++){
            var supplierErpCode = el.dataList[i].supplierErpCode;
            if( !(supplierErpCode === "4386E" ||  supplierErpCode=== "4386")){
                console.log(el.dataList[i].remark);
                el.dataList[i].remark = ''
            }

        }
        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() {
    // 加载物流公司信息
    $(el.expressCode).combobox({
        url: g.ctx + 'pc/sys/expressCompany/rest/listAll',
        method: "GET",
        valueField: 'ecCode',
        textField: 'ecName',
        panelHeight: 300,
        prompt: '-- 请选择 --',
        onSelect: function (data) {
            $(el.expressName).val(data.ecName);
        }
    });
}

function loadGrid(dataList) {
    var searchHeight = $(el.tb).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 40, 30);
    const toolbar = []
    let numColumn = {
        field: 'deliveryNum', title: '送货数量',
        width: '100', align: 'left',
        editor: {type: 'numberbox', options: {precision: 3}}
    }
    let frozenColumns = []

    if (!createFlag()) {
        frozenColumns = [
            {field: 'ck', checkbox: true},
            {
                field: 'purchaseOrderCode', title: 'SAP订单号',
                width: '60', align: 'left'
            },
            {
                field: 'purchaseOrderRow', title: '订单行号',
                width: '60', align: 'left'
            },
            {
                field: 'materialCode', title: '物料编码',
                width: '100', align: 'left'
            },
            {
                field: 'materialName', title: '物料名称',
                width: '200', align: 'left'
            }
        ]
        // 在第一个元素后添加一个新元素
        frozenColumns.splice(1, 0, {
            field: 'delFlag',
            title: '删除标识',
            width: 70,
            formatter: function (value) {
                switch (Number(value)) {
                    case 1:
                        return '<span style="color: red;">已删除</span>';
                    default:
                        return '未删除';
                }
            }
        });

        numColumn = {
            field: 'num', title: '送货数量',
            width: '100', align: 'left',
            editor: {type: 'numberbox', options: {precision: 3}}
        }
    } else {
        frozenColumns = [
            {field: 'ck', checkbox: true},
            {
                field: 'orderCode', title: 'SAP订单号',
                width: '100', align: 'left'
            },
            {
                field: 'orderRow', title: '订单行号',
                width: '60', align: 'left'
            },
            {
                field: 'materialCode', title: '物料编码',
                width: '100', align: 'left'
            },
            {
                field: 'materialName', title: '物料名称',
                width: '200', align: 'left'
            }
        ]
    }

    let columns = [
        numColumn,
        {
            field: 'batchNum', title: '供应商批号',
            width: '100', align: 'left', editor: {type: 'textbox'}
        },
        {
            field: 'packNum', title: '件数',
            width: '100', align: 'left',
            hidden: true
        },
        {
            field: 'partialNum', title: '尾数',
            width: '100', align: 'left',
            hidden: true
        },

        {
            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: 'num', title: '订单数量',
            width: '100', align: 'left',
        },
        {
            field: 'unitCode', title: '订单单位',
            width: '80', align: 'left',
        },
        {
            field: 'factoryName', title: '收货工厂',
            width: '120', align: 'left'
        },

        {
            field: 'remark', title: '送货备注',
            width: '200', align: 'left', editor: {type: 'textbox'}
        },
    ]
    let options = {}
    if (readOnly()) {
        columns = [
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'delFlag',
                title: '删除标识',
                width: 70,
                formatter: function (value) {
                    switch (Number(value)) {
                        case 0:
                            return '未删除';
                        case 1:
                            return '<span style="color: red;">已删除</span>';
                        default:
                            return '';
                    }
                }
            },
            {
                field: 'orderRow', title: '行号',
                width: '60', align: 'center',
                sortable: true
            },
            // {
            //     field: 'isPrint',
            //     title: '打印状态',
            //     width: 65,
            //     formatter: function (value) {
            //         if (value) {
            //             return '<span style="color: lightgreen;">是</span>';
            //         }
            //         return '<span style="color: orange;">否</span>';
            //     }
            // },
            {
                field: 'materialCode', title: '物料编码',
                width: '100', align: 'center',
                sortable: true
            },
            {
                field: 'materialName', title: '物料名称',
                width: '180', align: 'center'
            },
            {
                field: 'num', title: '送货数量',
                width: '100', align: 'center'
            },
            {
                field: 'batchNum', title: '供应商批号',
                width: '100', align: 'center'
            },
            {
                field: 'gmpPackingSpecification', title: '包装规格数',
                width: 100
            },
            {
                field: 'packNum', title: '件数',
                width: '100', align: 'center',
                hidden: true
            },
            {
                field: 'partialNum', title: '尾数',
                width: '100', align: 'center',
                hidden: true
            },
            {
                field: 'purchaseOrderCode', title: 'SAP订单号',
                width: '100', align: 'center'
            },
            {
                field: 'purchaseOrderRow', title: '订单行号',
                width: '60', align: 'center'
            },
            {
                field: 'noClearNum', title: '订单未清数量',
                width: '100', align: 'center',
            },
            {
                field: 'unitCode', title: '订单单位',
                width: '80', align: 'center',
            },
            {
                field: 'requireDate', title: '需求交期',
                width: '100', align: 'center'
            },
            {
                field: 'factoryName', title: '收货工厂',
                width: '120', align: 'center'
            },
            {
                field: 'stockCode', title: '库存地点',
                width: '60', align: 'left',

            },
            {
                field: 'defaultStock', title: '默认储位',
                width: '80', align: 'left',

            },
            {
                field: 'buyer',
                title: '采购员',
                width: '100',
                align: 'center'
            },
            {
                field: 'remark', title: '送货备注',
                width: '200', align: 'center'
            }
        ]
        frozenColumns = []
        let cols = frozenColumns.concat(columns)
        options = {
            loadMsg: '数据远程载入中,请等待...',
            singleSelect: false,
            method: "GET",
            pageSize: pager.pageSize,
            pageList: pager.pageList,
            data: dataList,
            view: detailview,
            detailFormatter: function (index, row) {
                return '<div style="padding:2px;position:relative;"><table class="ddv"></table></div>';
            },
            onExpandRow: function (index, row) {
                var ddv = $(el.tb).datagrid('getRowDetail', index).find('table.ddv');
                ddv.datagrid({
                    url: g.ctx + 'pc/order/purchaseOrderBom/rest/list',
                    queryParams: {
                        materialCode: row.materialCode,
                        factoryCode: row.factoryCode,
                        page: 1,
                        rows: 100
                    },
                    singleSelect: true,
                    rownumbers: true,
                    height: 'auto',
                    columns: [[
                        {field: 'componentCode', title: '编码', width: 125},
                        {field: 'componentName', title: '描述', width: 400},
                        {field: 'componentUnit', title: '单位', width: 60},
                        {field: 'componentNumber', title: '组件数量', width: 60},
                        {field: 'componentDosage', title: '子件数量', width: 60},
                        {field: 'componentDosageTotal', title: '总用量', width: 60},
                    ]],
                    onResize: function () {
                        $(el.tb).datagrid('fixDetailRowHeight', index);
                    },
                    onLoadSuccess: function (data) {
                        row.num;
                        var dd = ddv.datagrid("getRows")
                        $.each(dd, function (idx, itm) {
                            let a = row.num / itm.componentNumber * parseFloat(itm.componentDosage);
                            ddv.datagrid("updateRow", {
                                index: idx,
                                row: {
                                    componentDosageTotal: a.toFixed(3)
                                }
                            })
                        })
                    }
                })
                $(el.tb).datagrid('fixDetailRowHeight', index);
            },
            height: el.bodyHeight - searchHeight - 200,
            pagination: true,
            columns: [cols],
            toolbar: toolbar
        }
        $(el.tb).datagrid(options)
    } else {
        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;
                let num = rowData.deliveryNum
                if (!createFlag()) {
                    num = rowData.num
                }
                var gmpPackingSpecification = rowData.gmpPackingSpecification;
                if (gmpPackingSpecification) {
                    var packNum = math.floor(num / rowData.gmpPackingSpecification);
                    //修改求尾数的方法不能用取余，直接用件数*包装数据，然后总数-包装数就是尾数
                    var tmpDeliveryNum = math.multiply(packNum, gmpPackingSpecification);
                    var partialNum = math.subtract(num, tmpDeliveryNum);
                    if (partialNum > 0) {
                        packNum = packNum + 1;
                    }
                    $(el.tb).datagrid('updateRow', {
                        index: rowIndex,
                        row: {
                            packNum: packNum,
                            partialNum: math.round(partialNum, 4)
                        }
                    });
                }
            },
            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 copy(type) {
    let allRows = $(el.tb).datagrid('getRows');
    for (let i = 0; i < allRows.length; i++) {
        $(el.tb).datagrid('endEdit', i);
    }
    let allDataRows = $(el.tb).datagrid('getRows');
    if (type === 'gmpPackingSpecification') {
        for (let i = 0; i < allDataRows.length; i++) {
            $(el.tb).datagrid('updateRow', {
                index: i,
                row: {
                    gmpPackingSpecification: allDataRows[0].gmpPackingSpecification
                }
            });
        }
    }
}

function saveOrUpdate(callback, deliveryFlag) {

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

    //日期比对 2024-08-05
    let checkData = $(el.dataForm).serializeJson();
    let diff = moment(checkData.deliveryDate).diff(moment(checkData.planDeliveryDate), 'days');
    console.log(diff)
    if (diff > 0) {
        topWin.layer.msg("预计到货日期不能早于发货日期");
        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];

        let pre = "第" + (i + 1) + "行明细，";
        let deliveryNum = row.deliveryNum;
        if (!createFlag()) {
            deliveryNum = row.num;
        }

        if (!deliveryNum) {
            topWin.layer.msg(pre + "送货数量不可为空");
            return;
        }

        if (deliveryNum == 0) {
            topWin.layer.msg(pre + "送货数量不可为0");
            return;
        }
        // 未清数量
        let noClearNum = row.noClearNum == null ? 0 : row.noClearNum;
        if (noClearNum <= 0) {
            topWin.layer.msg("第" + (i + 1) + "行，未清数量不足，请选择其他记录");
            return;
        }
        // if (!row.gmpPackingSpecification) {
        //     topWin.layer.msg("第" + (i + 1) + "行，包装数量不能为空");
        //     return;
        // }
        // 在途数量
        let onlineNum = row.onlineNum == null ? 0 : row.onlineNum;
        // 最大可送货数量
        // let maxNum = noClearNum - onlineNum;
        var maxNum = math.floor(math.subtract(noClearNum, onlineNum), 4);
        if (row.materialCode) {
            // 过量交货限额 百分比计算
            let quantityRange = row.quantityRange;
            if (!quantityRange) {
                quantityRange = 0;
            } else {
                quantityRange = parseFloat(quantityRange.replace("%", ""))
            }
            // 总量超额逻辑
            let overNum = row.num * quantityRange / 100;
            maxNum = maxNum + overNum;
        }
        if (maxNum < deliveryNum) {
            topWin.layer.msg("第" + (i + 1) + "行，送货数量不得大于，未清数量减去在途送货单数量的值");
            return;
        }

        let items = {
            num: deliveryNum,
            purchaseOrderCode: row.orderCode,
            purchaseOrderRow: row.orderRow,
            factoryCode: row.factoryCode,
            factoryName: row.factoryName,
            stockCode: row.stockCode,
            stockName: row.stockName,
            materialCode: row.materialCode,
            materialName: row.materialName,
            colourCode: row.colourCode,
            colourName: row.colourName,
            workmanship: row.workmanship,
            lengths: row.lengths,
            width: row.width,
            thickness: row.thickness,
            unitCode: row.unitCode,
            materialUnitCode: row.materialUnitCode,
            unitChange: row.unitChange,
            unitName: row.unitName,
            materialSpec: row.materialSpec,
            purchaseOrderNum: row.num,
            price: row.price,
            amount: row.amount,
            saleOrderCode: row.saleOrderCode,
            saleOrderRow: row.saleOrderRow,
            batchRule: row.batchRule,
            rowTypeCode: row.rowTypeCode,
            source: row.source,
            sourceId: row.sourceId,
            requireDate: row.requireDate,
            batchNum: row.batchNum,
            shouHuoRen: row.shouHuoRen,
            shouHuoRenPhone: row.shouHuoRenPhone,
            shouHuoDiZhi: row.shouHuoDiZhi,
            buyer: row.createName,
            huoHao: row.huoHao,
            storageConditions: row.storageConditions,
            manufacturer: row.manufacturer,
            demandDepartment: row.demandDepartment,
            gmpPackingSpecification: row.gmpPackingSpecification,
            packNum: row.packNum,
            partialNum: row.partialNum,
            remark: row.remark,
            purchaseUser: row.purchaseUser,
            supplierCode: row.supplierCode,
            id: row.id
        };
        if (!createFlag()) {
            items.purchaseOrderCode = row.purchaseOrderCode
            items.purchaseOrderRow = row.purchaseOrderRow
        }
        itemList.push(items);
    }

    let formData = $(el.dataForm).serializeJson();
    formData.deliveryFlag = deliveryFlag
    formData.item = itemList;
    formData.fileIds = $("#fileIds").attr('data-fileIds')
    formData.supplierCode1=supplierCode1;
    let load = topWin.layer.load(0);
    var directShipment = formData.directShipment;
    $.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);
                    }
                })
            } 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
}

//自定义验证手机号
$.extend($.fn.validatebox.defaults.rules, {
    phoneRex: {
        validator: function (value) {
            var rex = /^1[3-9]+\d{9}$/;
            //var rex=/^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
            //区号：前面一个0，后面跟2-3位数字 ： 0\d{2,3}
            //电话号码：7-8位数字： \d{7,8
            //分机号：一般都是3位数字： \d{3,}
            //这样连接起来就是验证电话的正则表达式了：/^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/
            //var rex2=/^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
            if (rex.test(value)) {
                return true;
            } else {
                return false;
            }
        },
        message: '请输入正确的手机号码格式'
    },
    telNum: {
        //验证座机号
        validator: function (value) {
            var rex2 = /^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
            if (rex2.test(value)) {
                return true;
            } else {
                return false;
            }

        },
        message: '请输入正确的电话号码格式'
    }
});