$(function () {
    $("#jqGrid").jqGrid({
        url: '../freight/list',
        datatype: "json",
        colModel: [
            {label: 'ID', name: 'id', index: 'id', hidden: true, key: true},
            {label: '模版名称', name: 'name', index: 'name'},
            {
                label: '模版类型', name: 'templateType', index: 'template_type', width: 100,
                formatter: function (value) {
                    return transTemplateType(value);
                }
            },
            {
                label: '计价方式', name: 'pricingManner', index: 'pricing_manner', width: 100,
                formatter: function (value) {
                    return transPricingManner(value);
                }
            }],
        viewrecords: true,
        height: 675,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
});

function transTemplateType(value) {
    if (value == 1) {
        return '卖家包邮';
    }
    return '买家承担运费';
};

function transPricingManner(value) {
    if (value == 1) {
        return '按重量';
    } else if (value == 2) {
        return '按体积';
    }
    return '按件数';
};


let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        freight: {},
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]
        },
        q: {
            name: ''
        },
        freightItemEntityList: [{
            id: '',
            freId: '',
            deliveryArea: true,
            firstPiece: '',
            freight: '',
            continuePiece: '',
            renew: '',
            isDelete: 0
        }]
    },
    methods: {
        changeUnit: function(value) {
            if (value == '0') {
                $('#first').html('首件（个）');
                $('#continue').html('续件（个）');
            } else if (value == '1') {
                $('#first').html('首件（kg）');
                $('#continue').html('续件（kg）');
            } else if (value == '2') {
                $('#first').html('首件（m³）');
                $('#continue').html('续件（m³）');
            }
        },
        delItemRow: function (index) {
            //最后一行时禁止删除
            if (vm.freightItemEntityList.length == 1) {
                return;
            }
            vm.freightItemEntityList[index].isDelete = 1;
        },
        addItemRow: function () {
            let id = '';
            if (vm.freight) {
                id = vm.freight.id;
            }
            vm.freightItemEntityList.push({
                id: '',
                freId: '',
                firstPiece: '',
                freight: '',
                continuePiece: '',
                renew: '',
                isDelete: 0
            })
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.freight = {
                name: '',
                templateType: 0,
                pricingManner: 0,
                isDefault: false
            };
            vm.freightItemEntityList = [{
                id: '',
                freId: '',
                deliveryArea: true,
                firstPiece: '',
                freight: '',
                continuePiece: '',
                renew: '',
                isDelete: 0
            }];
        },
        update: function (event) {
            let id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id)
        },
        saveOrUpdate: function (event) {
            let url = vm.freight.id == null ? "../freight/save" : "../freight/update";
            vm.freight.freightItemEntityList = vm.freightItemEntityList;
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.freight),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            let ids = getSelectedRows();
            if (ids == null){
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../freight/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function(id){
            $.get("../freight/info/"+id, function (r) {
                vm.freight = r.freight;
                if (vm.freight.isDefault == "1") {
                    vm.freight.isDefault = true;
                }
                if (r.freight.freightItemEntityList.length > 0) {
                    vm.freightItemEntityList = r.freight.freightItemEntityList;
                    for (var item in vm.freightItemEntityList) {
                        if (item.deliveryArea == "ALL") {
                            item.deliveryArea = true;
                        }
                    }
                } else {
                    vm.freightItemEntityList = [{
                        id: '',
                        freId: '',
                        deliveryArea: true,
                        firstPiece: '',
                        freight: '',
                        continuePiece: '',
                        renew: '',
                        isDelete: 0
                    }];
                }
            });
        },
        reloadSearch: function() {
            vm.q = {
                name: ''
            }
            vm.reload();
        },
        reload: function (event) {
            vm.showList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
    }
});
