$(function () {
    $("#jqGrid").jqGrid({
        url: '../mkdistsellallocation/list',
        datatype: "json",
        colModel: [
			{label: 'sellAllocId', name: 'sellAllocId', index: 'sell_alloc_id', key: true, hidden: true},
			{label: '分销渠道名称', name: 'distFlag', index: 'dist_flag', width: 80},
            {label: '所属三方商户', name: 'thirdPartyMerchName', index: 'thirdPartyMerchName', width: 80},
            {label: '所属供应商', name: 'childSupplierName', index: 'childSupplierName', width: 80},
			{label: '商品所属分销商', name: 'distName', index: 'distName', width: 80},
            {label: '所属门店', name: 'storeName', index: 'storeName', width: 80},
			{label: '商品', name: 'goodsName', index: 'goodsName', width: 80},
			{label: '分配方式', name: 'allocType', index: 'alloc_type', width: 80,
                formatter: function (value) {
                    if (value == '00') {
                        return '比例';
                    } else if (value == '10') {
                        return '金额';
                    }
                    return '';
                }},
			{label: '子级分销商id规则', name: 'expendDistIds', index: 'expend_dist_ids', width: 120},
			{label: '子级分销额度分配（点数/金额）', name: 'expendDistLines', index: 'expend_dist_lines', width: 120},
            {label: '是否有效', name: 'isValid', index: 'is_valid', width: 60,
                formatter: function (value) {
                    if (value == '0') {
                        return '有效';
                    } else if (value == '1') {
                        return '无效';
                    }
                    return '';
                }},
            {label: '备注', name: 'note', index: 'note', width: 60},
            {label: '创建人编号', name: 'createrSn', index: 'creater_sn', width: 70},
            {label: '创建时间', name: 'createTime', index: 'create_time', width: 110,
                formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd hh:mm:ss');
                }},
            {label: '修改人编号', name: 'moderSn', index: 'moder_sn', width: 70},
            {label: '修改时间', name: 'modTime', index: 'mod_time', width: 110,
                formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd hh:mm:ss');
                }}],
		viewrecords: true,
        height: 385,
        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"});
        }
    });
});

//菜单树
var menu_ztree;
var menu_setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "distId",
            pIdKey: "pdistId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    },
    check: {
        enable: true,
        nocheckInherit: true
    }
};

let vm = new Vue({
	el: '#rrapp',
	data: {
        showList: true,
        title: null,
		mkDistSellAllocation: {},
		ruleValidate: {
			name: [
				{required: true, message: '名称不能为空', trigger: 'blur'}
			]
		},

		q: {
            distChnlId: '',
            storeId:'',
            distId:'',
            goodsId:''
		},
        mkDistChnlList:[],
        thirdMerchantBizList: [],
        suppliers:[],
        mkDistList:[],
		goodsList:[],
        storeList:[],
        mkDist:{},
        storeId: '',
        sellAllocId: '',
        queryGoodsList:[],
        queryStoreList:[],
        queryMkDistList:[],
        queryMkDistChnlList:[],
        distChnlId:'',
        distId:'',
        expendDistList: []
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function () {
			vm.showList = false;
			vm.title = "新增";
			vm.mkDistSellAllocation = {isValid:0,storeId:''};
			vm.mkDistChnlList = [];
            vm.thirdMerchantBizList = [];
            vm.storeList = [];
            vm.suppliers = [];
            vm.mkDistList = [];
            vm.goodsList = [];
            vm.expendDistList = [{expendDistId:'',expendDistName:'',expendDistLine:'',expendDistLvl:''}];
            // vm.getMkDistChnlList();
			vm.getThirdMerchantBizList();
			// vm.getMkDistList();
		},
		update: function (event) {
            let sellAllocId = getSelectedRow();
			if (sellAllocId == null) {
				return;
			}
			vm.showList = false;
            vm.title = "修改";

            // vm.getMkDistChnlList();
            vm.getThirdMerchantBizList();
            // vm.getMkDistList();
            // vm.getInfo(sellAllocId);
            vm.getInfo(sellAllocId);
		},
		saveOrUpdate: function (event) {
            // //获取选择的菜单
            // var nodes = menu_ztree.getCheckedNodes(true);
            // var expendDistIdList = new Array();
            // for (var i = 0; i < nodes.length; i++) {
            //     expendDistIdList.push(nodes[i].distId);
            // }
            // vm.mkDistSellAllocation.expendDistIdList = expendDistIdList;
            vm.mkDistSellAllocation.expendDistDtoList = vm.expendDistList;

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

			confirm('确定要删除选中的记录？', function () {
				$.ajax({
					type: "POST",
				    url: "../mkdistsellallocation/delete",
				    contentType: "application/json",
				    data: JSON.stringify(sellAllocIds),
				    success: function (r) {
						if (r.code == 0) {
							alert('操作成功', function (index) {
								$("#jqGrid").trigger("reloadGrid");
							});
						} else {
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(sellAllocId){
		    if(sellAllocId){
                $.get("../mkdistsellallocation/info/"+sellAllocId, function (r) {
                    vm.mkDistSellAllocation = r.mkDistSellAllocation;
                    vm.sellAllocId = r.mkDistSellAllocation.sellAllocId;
                    //勾选角色所拥有的菜单
                    vm.expendDistIds = r.mkDistSellAllocation.expendDistIdList;
                });
            }
		},
        getMkDistChnlList: function () {
            $.get("../mkdistchnl/queryAll", function (r) {
                vm.mkDistChnlList = r.list;
            });
        },
        // changeDist: function (option) {
		 //    var distChnlId = option.value;
		 //    if(distChnlId){
        //         vm.distChnlId = distChnlId;
        //         $.get("../mkdistchnl/info/"+distChnlId, function (r) {
        //             var thirdMerchSn = r.mkDistChnl.thirdMerchSn;
        //             vm.getThirdMerchantBizList(thirdMerchSn);
        //             vm.showSupplier(thirdMerchSn);
        //             vm.getStoreList(thirdMerchSn);
        //         });
        //     }
        //     // vm.loadTree();
        //     // vm.goodsList = [];
        //     // vm.mkDistList = [];
        //     // menu_ztree = $.fn.zTree.init($("#expendDistIdsTree"), menu_setting, []);
        // },
        getThirdMerchantBizList: function() {
            $.get("../thirdmerchantbiz/queryAll", function (r) {
                vm.thirdMerchantBizList = r.list;
            });
        },
        changeDist: function (option) {
            var thirdMerchSn = option.value;
            if(thirdMerchSn){
                vm.showSupplier(thirdMerchSn);
                vm.getStoreList(thirdMerchSn);
            }
            // vm.loadTree();
            // vm.goodsList = [];
            // vm.mkDistList = [];
            // menu_ztree = $.fn.zTree.init($("#expendDistIdsTree"), menu_setting, []);
        },
        showSupplier: function (thirdMerchSn) {
            $.get("../supplier/queryAll?thirdMerchSn=" + thirdMerchSn, function (r) {
                vm.suppliers = r.list;
            });
        },
        getStoreList: function(thirdMerchSn){
            $.get("../store/queryAll?thirdMerchSn=" + thirdMerchSn, function (r) {
                vm.storeList = r.list;
            });
        },
        changeGoods: function (option) {
            var storeId = option.value;
            if(storeId){
                vm.getGoodsList(storeId);
                vm.changeMkDist(storeId);
                vm.expendDistList = [{expendDistId:'',expendDistName:'',expendDistLine:'',expendDistLvl:''}];
            }
        },
        getGoodsList: function(storeId){
            if(storeId){
                $.get("../productstorerela/queryAll?storeId=" + storeId, function (r) {
                    vm.goodsList = r.list;
                });
            }
        },
        changeMkDist: function (storeId) {
            if(storeId) {
                $.get("../mkdist/queryDistByGoodsId?storeId=" + storeId, function (r) {
                    vm.mkDist = r.mkDistEntity;
                    if (r.mkDistEntity) {
                        vm.getMkDistList(r.mkDistEntity.distId);
                    } else {
                        vm.mkDistList = [];
                    }
                });
            }
        },
        getMkDistList: function (distId) {
            if(distId) {
                $.get("../mkdist/queryAll?distId=" + distId, function (r) {
                    vm.mkDistList = r.list;
                });
            }
        },
        // getExpendDistTree: function (pdistId,sellAllocId) {
        //     //加载树
        //     $.get("../mkdisthier/queryAll/tree?pdistId="+pdistId+"&sidx=s.hier_lvl", function (r) {
        //         menu_ztree = $.fn.zTree.init($("#expendDistIdsTree"), menu_setting, r.list);
        //         //展开所有节点
        //         menu_ztree.expandAll(true);
        //         if (sellAllocId != null) {
        //             vm.getInfo(sellAllocId);
        //         }
        //     });
        // },
        showTree:function (option) {
            var distId = option.value;
            vm.distId = distId;
            // vm.loadTree();
            vm.loadExpendDistList();
        },
        loadTree: function () {
            if(vm.distId){
                // console.log('vm.distChnlId：'+vm.distChnlId);
                // console.log('vm.distId：'+vm.distId);
                //加载树
                $.get("../mkdisthier/queryAll/tree?distId=" + vm.distId + "&sidx=h.hier_lvl", function (r) {
                    menu_ztree = $.fn.zTree.init($("#expendDistIdsTree"), menu_setting, r.list);
                    //展开所有节点
                    menu_ztree.expandAll(true);

                    var exIds = vm.expendDistIds;
                    if(exIds){
                        for (var i = 0; i < exIds.length; i++) {
                            var node = menu_ztree.getNodeByParam("distId", exIds[i]);
                            menu_ztree.checkNode(node, true, false);
                        }
                    }
                });
            }else{
                menu_ztree = $.fn.zTree.init($("#expendDistIdsTree"), menu_setting, []);
            }
        },
        loadExpendDistList:function () {
            if(vm.distId){
                $.get("../mkdisthier/queryAll/tree?distId=" + vm.distId + "&sidx=h.hier_lvl", function (r) {
                    vm.expendDistList = r.list;
                    console.log(vm.expendDistList)
                });
            }
        },
        queryChangeGoodsByStore: function (storeId) {
            if(storeId){
                $.get("../productstorerela/queryAll?storeId=" + storeId, function (r) {
                    vm.queryGoodsList = r.list;
                });
            }
        },
        queryChangeByDistChnlId: function (distChnlId) {
            if(distChnlId){
                $.get("../mkdistchnl/info/"+distChnlId, function (r) {
                    var thirdMerchSn = r.mkDistChnl.thirdMerchSn;
                    $.get("../store/queryAll?thirdMerchSn="+thirdMerchSn, function (r) {
                        vm.queryStoreList = r.list;
                    });
                    $.get("../mkdist/queryAll?thirdMerchSn="+thirdMerchSn, function (r) {
                        vm.queryMkDistList = r.list;
                    });
                });
            }
        },
        reloadSearch: function() {
            vm.q = {
                distChnlId: '',
                storeId:'',
                distId:'',
                goodsId:''
            }
            vm.reload();
		},
		reload: function (event) {
			vm.showList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
			$("#jqGrid").jqGrid('setGridParam', {
                postData: {'distChnlId': vm.q.distChnlId,'storeId': vm.q.storeId,'distId': vm.q.distId,'goodsId': vm.q.goodsId},
                page: page
            }).trigger("reloadGrid");
            // vm.handleReset('formValidate');
		},
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
	},
    mounted() {
        $.get("../mkdistchnl/queryAll", function (r) {
            vm.queryMkDistChnlList = r.list;
        });
    }
});