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

    receivingUser: '#receivingUser',
    srmStatus: '#srmStatus',
    receivingTel: '#receivingTel',
    provinceCityCounty: '#provinceCityCounty',
    address: '#address',
    thirdOrder: '#thirdOrder',
    editIndex: undefined,

    purchaseOrg: '#purchaseOrg',
    orderId: '#orderId',
    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();
    initPageComBoBox();
    loadGrid();
});

/**
 * 初始化页面下拉框
 */
function initPageComBoBox() {
    // 初始化售后类型下拉框
    $('#afterSalesType').combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=after_sale_type',
        panelHeight: 'auto',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false
    });
    // 初始化售后方式下拉框
    $('#afterSalesWay').combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=after_sale_ways',
        panelHeight: 'auto',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false
    });
}
/**
 * 加载明细表
 */
function loadGrid() {
    $(el.tb).edatagrid({
        url: '/pc/mall/cart/rest/detail/list?cartId=' + $(el.cartId).val(),
        // height: el.bodyHeight - 400,
        height: 450,
        pagination: false,
        queryParams: {},
        autoSave: true,
        rownumbers: true,
        remoteSort: false,
        columns: [
            [
                /*{
                    field: 'ck',
                    checkbox: true
                },*/
                {
                    field: 'skuCode',
                    title: '商品编码',
                    width: 90
                },
                {
                    field: 'skuName',
                    title: '商品名称',
                    width: 600,
                    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: 150,
                    sortable: true
                },
                {
                    field: 'unit',
                    title: '单位',
                    width: 70
                },
                {
                    field: 'qty',
                    title: '商品数量',
                    width: 70
                },
                {
                    field: 'receiptNum',
                    title: '收货数量',
                    width: 70,
                    formatter: function (value, row) {
                        if (Number(value) === 0) {
                            return '<a style="color: red">' + value + '</a>'
                        } else {
                            return value
                        }
                    }
                },
                {
                    field: 'moReturn',
                    title: '已退数量',
                    width: 70
                },
                {
                    field: 'returnQuatity',
                    title: '退货数量',
                    width: 70,
                    editor: {
                        type: 'numberbox'
                    }
                }
            ]
        ],
        toolbar: [
           "-",
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    deleteProduct();
                }
            }, "-"
        ],
    });
}


/**
 * 删除选中的退货明细信息
 */
function deleteProduct() {
    let rows = $(el.tb).datagrid('getSelections');
    if (rows.length === 0) {
        layer.msg(common_opt_msg.opt_select_one_record);
        return false;
    }
    //先关闭行编辑
    if (el.editIndex !== undefined) {
        $(el.tb).datagrid('endEdit', el.editIndex);
        el.editIndex = undefined;
    }
    layer.confirm('您确定要是删除您选中的退货明细信息吗？', {icon: 3}, function () {
        for (let i = rows.length - 1; i >= 0; i--) {
            let rowIndex = $(el.tb).datagrid('getRowIndex', rows[i]);
            $(el.tb).datagrid('deleteRow', rowIndex);
            layer.msg(common_opt_msg.opt_success_msg);
        }
    });
}




/**
 * 获取表头数据并赋值
 */
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 index 行索引
 */

/**
 * 结束行编辑
 *
 * @return {boolean} 结果
 */
function endEditing() {
    if (el.editIndex === undefined) {
        return true
    }
    if ($(el.tb).datagrid('validateRow', el.editIndex)) {
        $(el.tb).datagrid('endEdit', el.editIndex);
        el.editIndex = undefined;
        return true;
    } else {
        return false;
    }
}

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

/**
 *售后申请保存
 */
function saveOrUpdate(call) {

    if($(el.form).form('validate')){
        $('#tb').edatagrid("saveRow")
        var formData = $(el.form).serializeJson();
        console.log( JSON.stringify(formData))
        console.log(32323232323)
        let product = $(el.tb).datagrid('getRows');
        // for(var i=0;i<product.length;i++) {
        //     var pre = "第" + (i + 1) + "行";
        //     debugger
        //     console.log("777777777"+product[i].returnQuatity)
        //     if (product[i].returnQuatity === '') {
        //         topWin.layer.alert(pre + "退货数量不能为空!", {icon: 2})
        //         return;
        //     }
        // }
        console.log(product)
        // let product = $(el.tb).datagrid('getRows')[el.editIndex];
        formData.items = product;
        console.log(JSON.stringify(formData))
        // 获取 textarea 的值并去除首尾空格
        // var textarea1 = document.getElementById('supplierDisadvantage');
        // var supplierDisadvantage = textarea1.value.trim();
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            contentType: 'application/json',
            url: g.ctx + 'pc/mall/cart/rest/afterSale/saveOrUpdate',
            method: 'post',
            data: JSON.stringify(formData),
            success: function (data) {
                call();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                console.log(data)
                console.log(89898989)
                layer.alert(JSON.parse(data.responseText).message);
            }
        });
    }else{
        layer.msg("红色框为必输项，请填写！");
    }
}

/**
 *售后申请提交
 */
// function submit(call) {
//     if($(el.form).form('validate')){
//         var formData = $(el.form).serializeJson();
//         var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
//         $.ajax({
//             contentType: 'application/json',
//             url: g.ctx + '/pc/mall/cart/rest/afterSale/submit',
//             method: 'post',
//             data: JSON.stringify(formData),
//             success: function (data) {
//                 call();
//             },
//             complete: function(data) {
//                 top.layer.close(loading);
//             },
//             error: function (data) {
//                 layer.alert(JSON.parse(data.responseText).message);
//             }
//         });
//     }else{
//         layer.msg("红色框为必输项，请填写！");
//     }
// }




