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



var page = {
    textbox: ['purchaseOrderCode', 'materialCode', 'unit', 'supplierName', 'lot', 'version', 'dc'],
    numberbox: ['num', 'fullQuantity', 'minQuantity', 'middleQuantity', 'sheets'],
    combox: ['mpn', 'manufacturer'],
    getPurchase: function (value, cc) {
        let materialCode = $('input[textboxname="materialCode"]').val();
        $.ajax({
            url: g.ctx + "pc/order/purchaseOrderDetail/rest/getInfoForLabelPrint",
            type: "GET",
            data: {orderCode: value,materialCode:materialCode},
            success: function (data) {
                $("#dataForm").form("load", data)
                page.logRecord("OK", value)
                cc()
                setTimeout(page.getSupplierManufacturer(value, cc),500)
            },
            error: function (data) {
                $("#dataForm").form("load", {})
                page.logRecord("ERROR", value, data.responseJSON.message)
            }
        })
    },
    getPurchaseForMa: function (value, cc) {
        let orderCode = $('input[textboxname="purchaseOrderCode"]').val();
        $.ajax({
            url: g.ctx + "pc/order/purchaseOrderDetail/rest/getInfoForLabelPrint",
            type: "GET",
            data: {orderCode: orderCode, materialCode: value},
            success: function (data) {
                $("#dataForm").form("load", data)
                page.logRecord("OK", value)
                cc()
                setTimeout(page.getSupplierManufacturer(value, cc),500)
            },
            error: function (data) {
                page.logRecord("ERROR", value, data.responseJSON.message)
            }
        })
    },
    getSupplierManufacturer: function (value, cc) {
        const supplierCode = $("input[name='supplierCode']").val()
        let materialCode = $('input[textboxname="materialCode"]').val();
        if (supplierCode === '' || materialCode == '') {
            return
        }
        $.ajax({
            url: g.ctx + "pc/supplier/avl/rest/getMPN",
            type: "GET",
            data: {
                supplierCode: supplierCode,
                materialCode: materialCode
            },
            success: function (data) {
                $('input[comboname="manufacturer"]').combobox("loadData", data)
                if (data.length === 1) {
                    $('input[comboname="manufacturer"]').combobox("setValue", data[0].productNameEn)
                }
                if (data.length<=0){
                    $('input[comboname="manufacturer"]').combobox("clear")
                    $('input[comboname="mpn"]').combobox("clear")
                    page.logRecord("ERROR", value, '请前往(供应商管理>AVL清单)维护该料号的AVL清单!!!')
                }else {
                    page.logRecord("OK", value)
                }
                cc()
            },
            error: function (data) {
                page.logRecord("ERROR", value, data.responseJSON.message)
            }
        })
        //增加查询是否产地必填的请求
        $.ajax({
            url: g.ctx + "pc/order/purchaseOrderDetail/rest/checkOriginIsRequired",
            type: "GET",
            data: {
                materialCode: materialCode
            },
            success: function (data) {
                debugger;

                // var $combobox = $('input[name="origin"]');
               if(data){
                 //  $("#origin").combobox.attr({required:true});
                   $('#origin').combobox({
                       required: true,
                       method: 'GET',
                       valueField: 'code',
                       textField: 'codeWithDesc',
                       prompt: '--- 请选择物料产地 ---',
                       url:g.ctx + 'pc/sys/dict/getDicByType?type=material_origin'
                   });


                  //设置产地必填
                  //  $combobox.combobox('options').required = true;
               }else{
                  // $("#origin").combobox.attr({required:false});
                   // $combobox.combobox('options').required = false;
                   $('#origin').combobox({
                       required: false,
                       method: 'GET',
                       valueField: 'code',
                       textField: 'codeWithDesc',
                       prompt: '--- 请选择物料产地 ---',
                       url:g.ctx + 'pc/sys/dict/getDicByType?type=material_origin'
                   });
               }
            },
            error: function (data) {

            }
        })
    },
    manufacturerChange: function (val) {
        const supplierCode = $("input[name='supplierCode']").val()
        $.ajax({
            url: g.ctx + "pc/supplier/avl/rest/getMPN",
            type: "GET",
            data: {
                supplierCode: supplierCode,
                manufacturer: val,
                materialCode: $('input[textboxname="materialCode"]').val()
            },
            success: function (data) {
                $('input[comboname="mpn"]').combobox("clear")
                $('input[comboname="mpn"]').combobox("loadData", data)
                if (data.length === 1) {
                    $('input[comboname="mpn"]').combobox("setValue", data[0].mpn)
                }
                page.logRecord("OK", val)
            },
            error: function (data) {
                page.logRecord("ERROR", value, data.responseJSON.message)
            }
        })
    },
    mpnSelect: function (data) {
        $("input[name='msl']").val(data.msl)
    },
    hanlderData: function (name, value, cc) {
        switch (name) {
            case 'purchaseOrderCode':
                page.getPurchase(value, cc)
                break
            case 'materialCode':
                page.getPurchaseForMa(value, cc)
                setTimeout(page.getSupplierManufacturer(value, cc),500)
                break
            case 'supplierName':
                setTimeout(page.getSupplierManufacturer(value, cc),500)
                break
            default:
                cc()
                break
        }
    },
    enterKey: function (event) {
        var cc = function () {
            var currentTabIndex = math.round($(event.target).attr("tabindex"), 0)
            var nextInput = $('input[tabindex="' + (currentTabIndex + 1) + '"]');
            if (nextInput.length) {
                nextInput.focus();
            }
        }

        //需要给对应的数据做校验
        let name = $(event.target).nextAll('input[type="hidden"]').attr("name");
        let value = $(event.target).val();
        page.hanlderData(name, value, cc)
    },
    logRecord: function (status, value, errorMsg) {
        $("#tb").datagrid("insertRow", {
            index: 0,
            row: {
                time: moment().format("YYYY/MM/DDahh:mm:ss"),
                status: status,
                content: value,
                msg: errorMsg
            }
        })
    },
    getFormData: function () {
        var isValid = $("#dataForm").form('validate');
        if (!isValid) {
            topWin.layer.msg("必填项未填写!")
            return false
        }
        let formData = $("#dataForm").serializeJson();
        if (formData['innerFlag'] === undefined) {
            formData['innerFlag'] = '0'
        }
        var dc_v = formData['dc'];
        if (dc_v.length == 4 || dc_v == "") {
            if (!/^\d{4}$/.test(formData['dc'])){
                topWin.layer.msg("请输入正确的4码DC 例如:2401")
                return false
            }
        } else {
            if (dc_v.indexOf("-") > 0 && dc_v.length != 10) {
                topWin.layer.msg("请输入正确的DC码，例如:2024-01-01")
                return false
            } else if (dc_v.length == 10) {
                //2024-04-01日期解析
                var Str = isDate(dc_v);
                if (Str != "") {
                    topWin.layer.msg("请输入正确的DC码，例如:2024-01-01")
                    return false;
                }
                //设值
                var weekStr = getWeek(dc_v)
                $("input[name='dc']").val(weekStr)
            } else if (dc_v.length != 8) {
                topWin.layer.msg("请输入正确的DC码，例如:20240101")
                return false
            } else {
                //20240101日期解析
                if (isValidYYYYMMDD(dc_v)) {
                    topWin.layer.msg("请输入正确的DC码，例如:20240101")
                    return false
                }
                //$("input[name='dc']").val("1210")
                var weekStr = getWeekStr(dc_v);
                $("input[name='dc']").val(weekStr);
            }
        }

        formData = $("#dataForm").serializeJson();
        if (!/^\d{4}$/.test(formData['dc'])){
            //topWin.layer.msg("请输入正确的4码DC 例如:2401")
            //return false
        }
        // if (!moment(formData['dc'], 'YYYYMM', true).isValid()){
        //
        // }
        formData['type'] = type
        return formData;
    }
}

function getWeekStr(str) {
    const match = str.match(/(\d{4})(\d{2})(\d{2})/);
    const year = parseInt(match[1], 10);
    const month = parseInt(match[2], 10);
    const day = parseInt(match[3], 10);
    return getWeek(year +　"-" + month + "-" + day + "");
}

function getWeek(date) {
    date = new Date(date);
    var date2 = new Date(date.getFullYear(),0,1);
    var day1 = date.getDay();
    if(day1 == 0) day1 = 7;
    var day2 = date2.getDay();
    if(day2 == 0) day2 = 7;
    let d = Math.round((date.getTime()-date2.getTime()+(day2-day1)*(24*68*60*1000))/ 86480880);
    //当周数大于52,则为下一年的第一周
    if((Math.ceil(d / 7)+ 1) > 52) {
        return ((date.getFullYear()+1) + "").substring(2,4) +　"01";
        //return (date.getFullYear()+1) + "第1周";
    }
    var weekStr = (Math.ceil(d /7)+ 1) + "";
    if (weekStr.length == 1) {
        return (date.getFullYear() + "").substring(2,4) +　"0" + weekStr;
    } else {
        return (date.getFullYear() + "").substring(2,4) +　"" + weekStr;
    }
    //return date.getFullYear()+"第"+(Math.ceil(d /7)+ 1)+"周";
}

function isValidYYYYMMDD(dateString) {
    const regex = /^\d{8}$/;
    const isValid = regex.test(dateString) && !isNaN(new Date(dateString));
    return isValid;
}

function handleMaterialCodeBlur(event){
    var cc = function () {
        var currentTabIndex = math.round($(event.target).attr("tabindex"), 0)
        var nextInput = $('input[tabindex="' + (currentTabIndex + 1) + '"]');
        if (nextInput.length) {
            nextInput.focus();
        }
    }
    $('input[comboname="mpn"]').combobox("clear");
    $('input[comboname="manufacturer"]').combobox("clear")
    purchaseForMa($(this).val(),cc);
    supplierManufacturer($(this).val(),cc);

}

function supplierManufacturer (materialCode, cc) {
    const supplierCode = $("input[name='supplierCode']").val()
    if (supplierCode === '' || materialCode == '') {
        return
    }
    $.ajax({
        url: g.ctx + "pc/supplier/avl/rest/getMPN",
        type: "GET",
        data: {
            supplierCode: supplierCode,
            materialCode: materialCode
        },
        success: function (data) {
            $('input[comboname="manufacturer"]').combobox("loadData", data)
            if (data.length === 1) {
                $('input[comboname="manufacturer"]').combobox("setValue", data[0].productNameEn)
                $('input[comboname="mpn"]').combobox("clear")
                manufacturerChangeMpn(data[0].productNameEn,materialCode);
            }else{
                $('input[comboname="mpn"]').combobox("clear")
                page.logRecord("OK!", materialCode,"该料号有多个制造商,请下拉选择对应的制造商!")
            }
            if (data.length<=0){
                $('input[comboname="manufacturer"]').combobox("clear")
                $('input[comboname="mpn"]').combobox("clear")
                page.logRecord("ERROR", materialCode, '请前往(供应商管理>AVL清单)维护该料号的AVL清单!!!')
            }
            cc()
        },
        error: function (data) {
            page.logRecord("ERROR", materialCode, data.responseJSON.message)
        }
    })
}

function purchaseForMa(value, cc) {
    let orderCode = $('input[textboxname="purchaseOrderCode"]').val();

    $.ajax({
        url: g.ctx + "pc/order/purchaseOrderDetail/rest/getInfoForLabelPrint",
        type: "GET",
        data: {orderCode: orderCode, materialCode: value},
        success: function (data) {
            $("#dataForm").form("load", data)
            cc()
        },
        error: function (data) {
            page.logRecord("ERROR", value, data.responseJSON.message)
        }
    })
}


function manufacturerChangeMpn(manufacturer,materialCode) {
    const supplierCode = $("input[name='supplierCode']").val()
    $.ajax({
        url: g.ctx + "pc/supplier/avl/rest/getMPN",
        type: "GET",
        data: {
            supplierCode: supplierCode,
            manufacturer: manufacturer,
            materialCode:materialCode
        },
        success: function (data) {
            $('input[comboname="mpn"]').combobox("clear")
            $('input[comboname="mpn"]').combobox("loadData", data)
            if (data.length === 1) {
                $('input[comboname="mpn"]').combobox("setValue", data[0].mpn)
            }else{
                page.logRecord("OK!", manufacturer,"该料号有多个制造商,请下拉选择对应的供应商后再选择MPN!")
            }
        },
        error: function (data) {
            page.logRecord("ERROR", manufacturer, data.responseJSON.message)
        }
    })
}



function isDate(dateString){
    if(dateString.trim()=="") {
        return ("请输入格式正确的日期\n\r日期格式：yyyy-mm-dd\n\r例    如：2008-08-08\n\r");
    }
    //年月日正则表达式
    var r=dateString.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
    if(r==null){
        return ("请输入格式正确的日期\n\r日期格式：yyyy-mm-dd\n\r例    如：2008-08-08\n\r");
    }
    var d=new Date(r[1],r[3]-1,r[4]);
    var num = (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
    if(num==0){
        return "请输入格式正确的日期\n\r日期格式：yyyy-mm-dd\n\r例    如：2008-08-08\n\r";
    }
    return "";

}



$(function () {
    //初始化加载产地信息
    $('#origin').combobox({
        required: true,
        method: 'GET',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择物料产地 ---',
        url:g.ctx + 'pc/sys/dict/getDicByType?type=material_origin'
    });

    $.each(page.textbox, function (idx, itm) {
        $('input[textboxname="' + itm + '"]').textbox({
            inputEvents: $.extend({}, $.fn.textbox.defaults.inputEvents, {
                keyup: function (event) {
                    if (event.keyCode == 13) {
                        page.enterKey(event)
                    }
                }
            })
        });
    })
    $.each(page.numberbox, function (idx, itm) {
        $('input[numberboxname="' + itm + '"]').textbox({
            inputEvents: $.extend({}, $.fn.textbox.defaults.inputEvents, {
                keyup: function (event) {
                    if (event.keyCode == 13) {
                        page.enterKey(event)
                    }
                }
            })
        });
    })
    $.each(page.combox, function (idx, itm) {
        $('input[comboname="' + itm + '"]').textbox({
            inputEvents: $.extend({}, $.fn.textbox.defaults.inputEvents, {
                keyup: function (event) {
                    if (event.keyCode == 13) {
                        page.enterKey(event)
                    }
                }

            })
        });
    })
    $('input[comboname="printerType"]').combobox("loadData", [{val: 1, txt: '默认'}, {val: 2, txt: '200dpi(TSC)'}, {
        val: 3,
        txt: '300dpi(TSC)'
    }])
  //  $('input[comboname="origin"]').combobox("loadData", [{val: "Malaysia", txt: 'Malaysia'}, {val: "Vietnam", txt: 'Vietnam'}])



    // 定义一个新的 moment.js locale
    moment.locale('zh-CN', {
        meridiem: function (hour, minute, isLowercase) {
            if (hour < 12) {
                return '上午';
            } else {
                return '下午';
            }
        }
    });
    $("#tb").datagrid({
        pagination: false,
        height: document.documentElement.clientHeight - 270 <= 0 ? 300 : document.documentElement.clientHeight - 270,
        columns: [[
            {
                field: 'time', title: '时间', align: 'left', width: 200
            }, {
                field: 'content', title: '输入内容', align: 'left', width:120
            }, {
                field: 'status', title: '状态', align: 'left', width: 160
            }, {
                field: 'msg',
                title: '信息',
                align: 'left',
                width: document.documentElement.clientWidth - 480 <= 0 ? 100 : document.documentElement.clientWidth - 517
            }
        ]],
        rowStyler: function (index, row) {
            if (row.status !== 'OK') {
                return 'background-color: red;'; // 设置行背景颜色为浅红色
            }
        }
    });
    //设置
    $('input[tabindex="1"]').focus()
})