$(function () {
    initialPage();
    getGrid();
});

function initialPage() {
    $(window).resize(function () {
        TreeGrid.table.resetHeight({height: $(window).height() - 100});
    });
}

function getGrid() {
    var colunms = TreeGrid.initColumn();
    var table = new TreeTable(TreeGrid.id, '../category/queryAll', colunms, {'categoryName': vm.q.categoryName,'storeId':vm.q.storeId});
    table.setExpandColumn(2);
    table.setIdField("id");
    table.setCodeField("id");
    table.setParentCodeField("parentId");
    table.setExpandAll(false);
    table.setHeight($(window).height() - 100);
    table.init();
    TreeGrid.table = table;
}

var TreeGrid = {
    id: "jqGrid",
    table: null,
    layerIndex: -1
};

/**
 * 初始化表格的列
 */
TreeGrid.initColumn = function () {
    var columns = [
        {field: 'selectItem', radio: true},
        {title: 'id', field: 'id', align: 'id', width: '50px'},
        // {title: '类型', field: 'type', align: 'center', valign: 'middle', width: '50px'},
        {title: '级别', field: 'level', align: 'center', valign: 'middle', width: '50px',formatter: function (item, index) {
            if (item.level == 'L1') {
                return '一级分类';
            } else if (item.level == 'L2') {
                return '二级分类';
            }
            return '-';
        }},
        {title: '分类名称', field: 'name', align: 'center', valign: 'middle', width: '60px'},
        {title: '所属商户', field: 'merchName',  width: '100px', align: 'center'},
        {title: '所属门店', field: 'storeName', width: '80px', align: 'center'},
        {title: '描述', field: 'frontDesc', align: 'center', valign: 'middle', width: '150px'},
        {title: '首页排序', field: 'sortOrder', align: 'center', valign: 'middle', width: '50px'},
        {
            title: '显示',
            field: 'isShow',
            align: 'center',
            valign: 'middle',
            width: '50px',
            formatter: function (item, index) {
                return transIsNot(item.show)
            }
        },
        {title: '操作', width: '90px', align: 'center', valign: 'middle',
            formatter: function (item, index) {
                if(hasPermission('category:saveCopyCategory')) {
                    return "&nbsp;&nbsp;&nbsp;&nbsp;<button class='btn btn-primary' " +
                        "onclick='vm.copyCategory(" + item.id + ",\"" + item.level + "\")'>复制分类</button>";
                }else {
                    return '-'
                }
            }
        }]
    return columns;
};

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        category: {isShow: 1, type: 0, level: 'L1', bannerUrl: '', iconUrl: '', imgUrl: '', wapBannerUrl: ''},
        ruleValidate: {
            name: [
                {required: true, message: '分类名称不能为空', trigger: 'blur'}
            ],
            frontDesc: [
                {required: true, message: '描述不能为空', trigger: 'blur'}
            ],
            // bannerUrl: [
            //     {required: true, message: 'banner图片不能为空', trigger: 'blur'}
            // ],
            iconUrl: [
                {required: true, message: '首页icon不能为空', trigger: 'blur'}
            ],
            // imgUrl: [
            //     {required: true, message: '图片不能为空', trigger: 'blur'}
            // ],
            wapBannerUrl: [
                {required: true, message: '分类banner不能为空', trigger: 'blur'}
            ]
            // frontName: [
            //     {required: true, message: 'frontName不能为空', trigger: 'blur'}
            // ]
        },
        q: {
            name: ''
        },
        categoryList: [],
        storeList: [],
        stores: [],
        merchList: [],
        showCopyList: true,
        showViewList: false,
        copyCategoryDto:{categoryId:0,storeList: "",categoryList:""},
        level: ''
    },
    methods: {
        copyCategory: function(id, level){
            vm.copyCategoryDto.categoryId = id;
            vm.copyCategoryDto.storeList = "";
            vm.copyCategoryDto.categoryList = "";
            vm.showCopyList = false;
            vm.showList = true;
            vm.showViewList = true;
            vm.title = "复制分类";
            vm.level = level;
        },
        handleSubmitCopyCate: function () {
            if(vm.copyCategoryDto.categoryId == ""){
                alert('分类id不能为空');
                return;
            }
            if(vm.copyCategoryDto.storeList == ""){
                alert('门店id批量上传数据没有上传或未上传成功');
                return;
            }
            if(vm.level == 'L2'){
                if(vm.copyCategoryDto.categoryList == ""){
                    alert('分类id批量上传数据没有上传或未上传成功');
                    return;
                }
            }
            var url = "../category/saveCopyCategory";
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.copyCategoryDto),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.showCopyList = true;
                            vm.showList = true;
                            vm.showViewList = false;
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        uploadExcelL2Success: function (data) {
            console.log(data);
            if(data.code==0){
                alert(data.msg, function (index) {
                    vm.copyCategoryDto.storeList = data.copyCategoryDto.storeList;
                    vm.copyCategoryDto.categoryList = data.copyCategoryDto.categoryList;
                });
            }else{
                alert(data.msg);
            }
        },
        uploadExcelSuccess: function (data) {
            if(data.code==0){
                alert(data.msg, function (index) {
                    vm.copyCategoryDto.storeList = data.storeIds;
                });
            }else{
                alert(data.msg);
            }
        },
        uploadExcelError: function (data) {
            console.log(data);
            alert('上传出现异常，请重试！');
        },
        uploadExcelFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 xls 或 xlsx 格式的文件。'
            });
        },
        query: function () {
            vm.reload();
        },
        reloadSearch: function() {
            vm.q = {
                categoryName: '',
                storeId:''
            }
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.showCopyList = true;
            vm.showViewList = true;
            vm.title = "新增";
            vm.category = {isShow: 1, type: 0, level: 'L1', bannerUrl: '', iconUrl: '', imgUrl: '', wapBannerUrl: ''};
            // this.getParentCategory(vm.category.storeId);
            vm.storeList = [];
            vm.merchList = [];
            vm.getMerchList();
        },
        update: function (event) {
            var id = TreeGrid.table.getSelectedRow();
            if (id.length == 0) {
                iview.Message.error("请选择一条记录");
                return;
            }
            vm.showList = false;
            vm.showCopyList = true;
            vm.showViewList = true;
            vm.title = "修改";
            vm.category = {isShow: 1, type: 0, level: 'L1', bannerUrl: '', iconUrl: '', imgUrl: '', wapBannerUrl: ''};
            vm.storeList = [];
            vm.merchList = [];
            vm.getInfo(id[0].id);
            vm.getMerchList();
            vm.getStoresByMerch();
        },
        saveOrUpdate: function (event) {
            var url = vm.category.id == null ? "../category/save" : "../category/update";
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.category),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var id = TreeGrid.table.getSelectedRow(), ids = [];
            if (id.length == 0) {
                iview.Message.error("请选择一条记录");
                return;
            }
            $.each(id, function (idx, item) {
                ids[idx] = item.id;
            });
            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../category/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (id) {
            $.get("../category/info/" + id, function (r) {
                vm.category = r.category;
                this.getParentCategory(r.category.storeId);
            });
        },
        getStoresByMerch: function (opt) {
            var value = opt.value;
            $.get("../store/getStoresByMerch?merchSn=" + value, function (r) {
                vm.storeList = r.list;
            });
        },
        getMerchList: function() {
            $.get("../merch/queryAll", function (r) {
                vm.merchList = r.list;
            });
        },
        getParentCategory: function (storeId) {
            if(storeId){
                $.get("../category/getCategorySelect?storeId="+storeId, function (r) {
                    vm.categoryList = r.list;
                });
            }
        },
        getCategory: function (opt) {
            var storeId = opt.value;
            vm.getParentCategory(storeId);
        },
        reload: function (event) {
            vm.showViewList = false;
            vm.showList = true;
            vm.showCopyList = true;
            // TreeGrid.table.refresh();
            initialPage();
            getGrid();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 100K。'
            });
        },
        handleSuccessBannerUrl: function (res, file) {
            vm.category.bannerUrl = file.response.url;
        },
        eyeImageBannerUrl: function () {
            var url = vm.category.bannerUrl;
            eyeImage(url);
        },
        handleSuccessIconUrl: function (res, file) {
            vm.category.iconUrl = file.response.url;
        },
        eyeImageIconUrl: function () {
            var url = vm.category.iconUrl;
            eyeImage(url);
        },
        handleSuccessImgUrl: function (res, file) {
            vm.category.imgUrl = file.response.url;
        },
        eyeImageImgUrl: function () {
            var url = vm.category.imgUrl;
            eyeImage(url);
        },
        handleSuccessWapBannerUrl: function (res, file) {
            vm.category.wapBannerUrl = file.response.url;
        },
        eyeImageWapBannerUrl: function () {
            var url = vm.category.wapBannerUrl;
            eyeImage(url);
        }
    },
    mounted() {
        $.get("../store/queryAll", function (r) {
            vm.stores = r.list;
        });
    }
});
