/**
 * 发票管理
 */
var el = {
    cartId: '#cartId',

    receivingUser: '#receivingUser',
    receivingTel: '#receivingTel',
    provinceCityCounty: '#provinceCityCounty',
    address: '#address',
    // editIndex: undefined,
    purchaseOrg: '#purchaseOrg',
    purchaseGroup: '#purchaseGroup',
    factoryCode: '#factoryCode',
    centerCode: '#centerCode',
    remark: '#remark',

    invoiceState: '#invoiceState',
    invoiceType: '#invoiceType',
    invoiceTitle: '#invoiceTitle',
    invoiceNo: '#invoiceNo',
    invoiceAddress: '#invoiceAddress',
    invoiceTel: '#invoiceTel',
    openingBank: '#openingBank',
    bankAccount: '#bankAccount',
    bankTel: '#bankTel',
    bankAddress: '#bankAddress',
    content: '#content',


    tb: '#tb',
    bodyHeight: document.documentElement.clientHeight
};


/**
 * 文档就绪
 */
$(function () {
    findHeadData();

    loadGrid();
});


/**
 * 加载明细表
 */
function loadGrid() {
    $(el.tb).datagrid({
        url: '/pc/mall/cart/rest/detail/list?cartId=' + $(el.cartId).val(),
        height: el.bodyHeight - 400,
        pagination: false,
        queryParams: {},
        rownumbers: true,
        remoteSort: false,
        columns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'storeName',
                    title: '商城名称',
                    width: 90
                },
                {
                    field: 'skuName',
                    title: '商品名称',
                    width: 460,
                    formatter: function (value) {
                        return '<span style="display: inline-block;width: 450px;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;" title="' + value + '">' + value + '</span>';
                    }
                },
                {
                    field: 'unitCost',
                    title: '单价',
                    width: 70,
                    sortable: true
                },
                {
                    field: 'unit',
                    title: '单位',
                    width: 70
                },
                {
                    field: 'qty',
                    title: '商品数量',
                    width: 70,
                    sortable: true
                },
                {
                    field: 'receiptNum',
                    title: '已收货数量',
                    width: 70,
                    sortable: true,
                    formatter: function (value, row) {
                        if (Number(value) === 0) {
                            return '<a style="color: red">' + value + '</a>'
                        } else {
                            return value
                        }
                    },
                },
                {
                    field: 'thisReceiptNum',
                    title: '本次收货数量',
                    width: 70,
                    sortable: true,
                    editor:{type:'numberbox',options:{required:true,validType:['num']} }

                },
                // {
                //     field: 'receivedTime',
                //     title: '收货时间',
                //     width: '120px',
                //     align: 'left',
                //     formatter: function (value, row, index) {
                //         return DateFormatMs(value);
                //     }
                // },
                {
                    field: 'receivedTime',
                    title: '收货时间',
                    width: 130,
                    sortable: true,
                    // formatter: function (value) {
                    //     if (value) {
                    //         return moment(value).format('YYYY-MM-DD');
                    //     }
                    //     return '';
                    // },
                    editor: {
                        type: 'datetimebox',
                        options: {
                            prompt: '请选择收货时间',
                            panelWidth: '160',
                            panelHeight: '250',
                            editable: false
                        }
                    }
                },
                {
                    field: 'remark',
                    title: '备注',
                    width: 200,
                    editor:{type:'textbox',options:{required:false} }

                },
                {
                    field: 'invoiceNumber',
                    title: '发票号',
                    width: 200,
                    editor:{type:'textbox',options:{required:false} }

                }
            ]
        ],
        onClickCell: onClickCell
    });
}


/**
 * 获取表头数据并赋值
 */
function findHeadData() {
    var loading = topWin.layer.msg('数据加载中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        type: 'POST',
        url: '/pc/mall/cart/rest/find/by/id',
        data: {cartId: $(el.cartId).val()},
        success: function (data) {
            topWin.layer.close(loading);
            handleHeadData(data);
        },
        error: function (data) {
            topWin.layer.close(loading);
            var errorMsg = data.responseJSON;
            if (!errorMsg) {
                errorMsg = "程序异常, 请联系管理员";
            }
            topWin.layer.alert(errorMsg, {icon: 2});
        }
    });
}


/**
 * 处理表头数据
 *
 * @param headData 表头数据
 */
function handleHeadData(headData) {
    $(el.receivingUser).textbox('setValue', headData.receivingUser);
    $(el.receivingTel).textbox('setValue', headData.receivingTel);
    $(el.provinceCityCounty).textbox('setValue', headData.provinceName + '/' + headData.cityName + '/' + headData.countyName);
    $(el.address).textbox('setValue', headData.address);

    $(el.purchaseOrg).textbox('setValue', headData.pgoName);
    $(el.purchaseGroup).textbox('setValue', headData.pgName);
    $(el.factoryCode).textbox('setValue', headData.factoryName);
    $(el.centerCode).textbox('setValue', headData.centerCode);
    $(el.remark).textbox('setValue', headData.remark);

    $(el.invoiceState).textbox('setValue', Number(headData.invoiceState) === 1 ? '随单开票' : '集中开票');
    $(el.invoiceType).textbox('setValue', Number(headData.invoiceType) === 1 ? '电子普通发票' : '增值税专用发票');
    $(el.invoiceTitle).textbox('setValue', headData.invoiceTitle);
    $(el.invoiceNo).textbox('setValue', headData.invoiceNo);
    $(el.invoiceAddress).textbox('setValue', headData.invoiceAddress);
    $(el.invoiceTel).textbox('setValue', headData.invoiceTel);
    $(el.openingBank).textbox('setValue', headData.openingBank);
    $(el.bankAccount).textbox('setValue', headData.bankAccount);
    $(el.bankTel).textbox('setValue', headData.bankTel);
    $(el.bankAddress).textbox('setValue', headData.bankAddress);
    $(el.content).textbox('setValue', headData.content);
}

$.extend($.fn.datagrid.methods, {
    editCell: function(jq,param){
        return jq.each(function(){
            var opts = $(this).datagrid('options');
            var fields = $(this).datagrid('getColumnFields',true).concat($(this).datagrid('getColumnFields'));
            for(var i=0; i<fields.length; i++){
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor1 = col.editor;
                if (fields[i] != param.field){
                    col.editor = null;
                }
            }
            $(this).datagrid('beginEdit', param.index);
            for(var i=0; i<fields.length; i++){
                var col = $(this).datagrid('getColumnOption', fields[i]);
                col.editor = col.editor1;
            }
        });
    }
});

var editIndex = undefined;
function endEditing(){
    if (editIndex == undefined){return true}
    if ($('#tb').datagrid('validateRow', editIndex)){
        $('#tb').datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    } else {
        return false;
    }
}
function onClickCell(index, field){
    if (endEditing()){
        $('#tb').datagrid('selectRow', index)
            .datagrid('editCell', {index:index,field:field});
        editIndex = index;
    }
}

/*$.extend($.fn.validatebox.defaults.rules, {
    num: {
        validator: function (value) {
            var rows = $('#tb').datagrid('getRows');
            if(editIndex == undefined){
                return true;
            }else{
                let qty = rows[editIndex].qty;
                return (Number(value)<=Number(qty));
            }
        },
        message: '收货数量大于商品数量!'
    }
});*/

function submitReceiptNum(call){
   // let b;
    var rows = $('#tb').datagrid('getRows');
    for(var i=0;i<rows.length;i++){
        let tb = $('#tb').datagrid('endEdit', i);
    }
    rows = $('#tb').datagrid('getRows');
    for(var i=0;i<rows.length;i++){
        var pre="第"+(i+1)+"行";
        // if(rows[i].receiptNum==''|| rows[i].receiptNum==0){
        if(rows[i].receiptNum===''){
            topWin.layer.alert(pre+"收货数量不能为空!" ,{icon:2})
            return ;
        }
        console.log(rows[i].receiptNum +"+"+rows[i].thisReceiptNum+"+"+rows[i].qty)
        console.log((parseFloat(rows[i].receiptNum) + parseFloat(rows[i].thisReceiptNum) ) )
        if((rows[i].receiptNum*1 + rows[i].thisReceiptNum*1 ) > rows[i].qty*1){
            topWin.layer.alert(pre+"收货数量不能大于商品数量" ,{icon:2})
            return ;
        }



        // console.log(editIndex)
        // //这里getEditor取的是实时数据
        //  rows[i].thisReceiptNum = $(el.tb).edatagrid('getEditor', {
        //     index: editIndex,
        //     field: 'thisReceiptNum'
        // }).target;
        // var thisReceiptNumValue = thisReceiptNum.textbox('getValue');
    }





    $.ajax({
        url: '/pc/mall/cart/rest/form/submitReceiptNum',
        // url: '/pc/mall/cart/rest/form/submitReceiptNum?thisReceiptNum=' + thisReceiptNumValue,
        type: 'POST',
        async: false,
        data: {"rows":JSON.stringify(rows),"cartId":$("#cartId").val()},
        success: function (res) {
            topWin.layer.alert("收货成功!", {icon: 1}, function (idx) {
                topWin.layer.close(idx);
                call()
            });
        },
        error: function (res) {
            topWin.layer.alert("收货失败!", {icon: 2});
        }
    });

   // return b;
}