$(function () {
    $("#jqGrid").jqGrid({
        url: '../goods/list',
        datatype: "json",
        colModel: [
            {label: 'ID', name: 'id', index: 'id', hidden: true, key: true},
            {label: '商品编码', name: 'goodsSn', index: 'goods_Sn', width: 60},
            {label: 'SKU', name: 'sku', index: 'sku', width: 80},
            {label: '商品类型', name: 'categoryName', index: 'category_id', width: 40},
            {label: '名称', name: 'name', index: 'name', width: 160},
            {
                label: '货品业务类型', name: 'goodsBizType', index: 'goods_biz_type', width: 70,
                formatter: function (value) {
                    if (value == '00') {
                        return '保税备货';
                    } else if (value == '02') {
                        return '保税展示补货';
                    } else if (value == '10') {
                        return '保税展示跨境';
                    }
                    return '普通货物';
                }
            },
            {label: '零售价格', name: 'retailPrice', index: 'retail_price', width: 80},
            {label: '市场价', name: 'marketPrice', index: 'market_price', width: 80},
            {
                label: '上架', name: 'isOnSale', index: 'is_on_sale', width: 40, align: 'center',
                formatter: function (value) {
                    return transIsNot(value);
                }
            },
            /*{
                label: '热销', name: 'isHot', index: 'is_hot', width: 80, formatter: function (value) {
                return transIsNot(value);
            }
            },
            {
                label: '活动', name: 'goodsType', index: 'goodsType', width: 80,
                formatter: function (value) {
                    if (value == 2) {
                        return '<span class="label label-warning">团购</span>';
                    } else {
                        return '<span class="label label-success">无活动</span>';
                    }
                }
            },*/
            {
                label: '录入日期', name: 'addTime', index: 'add_time', width: 80,
                formatter: function (value) {
                    return transDate(value, 'yyyy-MM-dd hh:mm:ss');
                }
            },
            {
                label: '操作', width: 60, align: 'center', sortable: false, formatter: function (value, col, row) {
                    let htmlStr = '';
                    if (row.goodsBizType == '02' || row.goodsBizType == '10') {
                        htmlStr = '<button class="btn btn-outline btn-primary" onclick="vm.qrcodeCanvas(' + row.id + ')"><i class="fa fa-qrcode"></i>二维码</button>';
                    }
                    return htmlStr;
                }
            }
        ],
        viewrecords: true,
        height: 675,
        rowNum: 15,
        rowList: [15, 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"});
        }
    });
    $('#goodsDesc').editable({
        inlineMode: false,
        alwaysBlank: true,
        height: '500px', //高度
        minHeight: '200px',
        language: "zh_cn",
        spellcheck: false,
        plainPaste: true,
        enableScript: false,
        imageButtons: ["floatImageLeft", "floatImageNone", "floatImageRight", "linkImage", "replaceImage", "removeImage"],
        allowedImageTypes: ["jpeg", "jpg", "png", "gif"],
        imageUploadURL: '../sys/oss/upload',
        imageUploadParams: {id: "edit"},
        imagesLoadURL: '../sys/oss/queryAll'
    })
});

var ztree;

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};
var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        uploadList: [],
        imgName: '',
        visible: false,
        goods: {primaryPicUrl: '', listPicUrl: '', categoryId: '', isOnSale: 1, isAppExclusive: 0, isLimited: 0, isHot: 0, categoryName: '', retailPrice: '', marketPrice: '', goodsRate: '', sortOrder: '' },
        ruleValidate: {
            /*name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]*/
        },
        q: {name: '', goodsSn: '', category: '', categoryTwo: ''},
        attributes: [],
        attributeEntityList: [{'id': '', 'goodsId': '', 'attributeId': '', 'value': '', 'isDelete': 0}],
        productEntityList: [{'id': '', 'goodsId': '', 'goodsSpecificationIds': '', 'goodsSpecificationNameValue': '', 'goodsSn': '', 'goodsNumber': '', 'isDelete': 0, 'goodsDefault': 0}],
        queryCategories: [],//一级分类
        queryCategoriesTwo: [],
        categories: [],//一级分类
        categoriesTwo: [],
        macros: [],//商品单位
        attributeCategories: [],//属性类别
        specifications: [],
        brands: [],
        freights: [],
        showInput: true
    },
    methods: {
        delSpeRow: function (index) {
            //最后一行时禁止删除
            if (vm.productEntityList.length == 1) {
                return;
            }
            vm.productEntityList[index].isDelete = 1;
        },
        addSpeRow: function () {
            let goodsId = '';
            if (vm.goods) {
                goodsId = vm.goods.id;
            }
            vm.productEntityList.push({'id': '', 'goodsId': '', 'goodsSpecificationIds': '', 'goodsSpecificationNameValue': '', 'goodsSn': '', 'goodsNumber': '', 'isDelete': 0, 'goodsDefault': 0});
        },
        delAttrRow: function (index) {
            //最后一行时禁止删除
            if (vm.attributeEntityList.length == 1) {
                return;
            }
            vm.attributeEntityList[index].isDelete = 1;
        },
        addAttrRow: function () {
            let goodsId = '';
            if (vm.goods) {
                goodsId = vm.goods.id;
            }
            vm.attributeEntityList.push({'id': '', 'goodsId': goodsId, 'attributeId': '', 'value': '', 'isDelete': 0});
        },
        reloadSearch: function () {
            vm.q = {
                name: '',
                goodsSn: '',
                category: '',
                categoryTwo: ''
            }
        },
        query: function () {
            vm.reload(1);
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.uploadList = [];
            vm.goods = {primaryPicUrl: '', listPicUrl: '', categoryId: '', isOnSale: 1, isAppExclusive: 0, isLimited: 0, isHot: 0, categoryName: '', retailPrice: '', marketPrice: '', goodsRate: '', sortOrder: '' };
            $('#goodsDesc').editable('setHTML', '');
            vm.getCategory();
            vm.macros = [];
            vm.brands = [];
            vm.freights = [];
            vm.attributeEntityList = [{'id': '', 'goodsId': '', 'attributeId': '', 'value': '', 'isDelete': 0}];
            vm.attributeCategories = [];
            vm.getMacro();
            vm.getBrand();
            vm.getFreights();
            vm.getAttributeCategories();
            vm.getAttributes();
            vm.showInput = true;
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.uploadList = [];
            vm.getInfo(id);
            vm.getMacro();
            vm.getBrand();
            vm.getFreights();
            vm.getAttributeCategories();
            vm.getGoodsGallery(id);
            vm.getAttributes();
            vm.showInput = true;
            if (vm.goods.goodsBizType == '10' || vm.goods.goodsBizType == '02') {
                vm.showInput = false;
            }
        },
        getAttributes: function () {
            $.get("../attribute/queryAll", function (r) {
                vm.attributes = r.list;
            });
        },
        getMacro: function () {
            // 获取货品业务类型
            $.get("../sys/macro/queryMacrosByValue?value=goodsBizType", function (r) {
                vm.macros = r.list;
            });
        },
        getBrand: function () {
            // 获取货品业务类型
            $.get("../brand/queryAll", function (r) {
                vm.brands = r.list;
            });
        },
        getFreights: function() {
            $.get("../freight/queryAll", function (r) {
                vm.freights = r.list;
            });
        },
        getGoodsGallery: function (id) {//获取商品顶部轮播图
            $.get("../goodsgallery/queryAll?goodsId=" + id, function (r) {
                vm.uploadList = r.list;
            });
        },
        getAttributeCategories: function () {
            $.get("../attributecategory/queryAll", function (r) {
                vm.attributeCategories = r.list;
            });
        },
        saveOrUpdate: function (event) {
            var url = vm.goods.id == null ? "../goods/save" : "../goods/update";
            vm.goods.goodsDesc = $('#goodsDesc').editable('getHTML');
            vm.goods.goodsImgList = vm.uploadList;
            vm.goods.attributeEntityList = vm.attributeEntityList;
            vm.goods.productEntityList = vm.productEntityList;
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify(vm.goods),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        enSale: function () {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            confirm('确定要上架选中的商品？', function () {
                $.ajax({
                    type: "POST",
                    url: "../goods/enSaleBatch",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        openSpe: function () {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '商品规格',
                content: '../shop/goodsspecification.html?goodsId=' + id
            })
        },
        openPro: function () {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            openWindow({
                type: 2,
                title: '产品设置',
                content: '../shop/product.html?goodsId=' + id
            });
        },
        unSale: function () {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            confirm('确定要下架选中的商品？', function () {
                $.ajax({
                    type: "POST",
                    url: "../goods/unSaleBatch",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../goods/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("../goods/info/" + id, function (r) {
                vm.goods = r.goods;
                // vm.getCategory();
                var opt = {}; opt.value = vm.goods.attributeCategory;
                vm.changeCategories(opt);
                if (r.goods.attributeEntityList.length > 0) {
                    vm.attributeEntityList = r.goods.attributeEntityList;
                } else {
                    vm.attributeEntityList = [{'id': '', 'goodsId': '', 'attributeId': '', 'value': '', 'isDelete': 0}];
                }
                if (r.goods.productEntityList.length > 0) {
                    vm.productEntityList = r.goods.productEntityList;
                } else {
                    vm.productEntityList = [{'id': '', 'goodsId': '', 'goodsSpecificationIds': '', 'goodsSpecificationNameValue': '', 'goodsSn': '', 'goodsNumber': '', 'isDelete': 0, 'goodsDefault': 0}];
                }
                $('#goodsDesc').editable('setHTML', vm.goods.goodsDesc);
            });
        },
        reload: function (event) {
            vm.showList = true;
            let page = event;
            if (event != 1) {
                page = $("#jqGrid").jqGrid('getGridParam', 'page');
            }
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'name': vm.q.name,
                    'goodsSn': vm.q.goodsSn,
                    'category': vm.q.category,
                    'categoryTwo': vm.q.categoryTwo
                },
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        getCategory: function () {
            //加载分类树
            $.get("../category/query", function (r) {
                ztree = $.fn.zTree.init($("#categoryTree"), setting, r.list);
                var node = ztree.getNodeByParam("id", vm.goods.categoryId);
                if (node) {
                    ztree.selectNode(node);
                    vm.goods.categoryName = node.name;
                } else {
                    node = ztree.getNodeByParam("id", 0);
                    ztree.selectNode(node);
                    vm.goods.categoryName = node.name;
                }
            })
        },
        categoryTree: function () {
            openWindow({
                title: "选择类型",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    if (node[0].isParent) {
                        alert("只能选择");
                        return;
                    }
                    //选择上级菜单
                    vm.goods.categoryId = node[0].id;
                    vm.goods.categoryName = node[0].name;

                    layer.close(index);
                }
            });
        },
        changeGoodsBizType: function(opt) {
            var goodsBizType = opt.value;
            if (vm.goods.goodsBizType == '10' || vm.goods.goodsBizType == '02') {
                vm.showInput = false;
            } else {
                vm.showInput = true;
            }
        },
        handleView(name) {
            this.imgName = name;
            this.visible = true;
        },
        changeQueryCategories: function (opt) {
            var value = opt.value;
            $.get("../category/getCategorySelectByParent?parentId=" + value, function (r) {
                vm.queryCategoriesTwo = r.list;
                // vm.reload();
            });
        },
        changeCategories: function (opt) {
            var value = opt.value;
            $.get("../category/getCategorySelectByParent?parentId=" + value, function (r) {
                vm.categoriesTwo = r.list;
            });
        },
        handleRemove(file) {
            // 从 upload 实例删除数据
            const fileList = vm.uploadList;
            vm.uploadList.splice(fileList.indexOf(file), 1);
        },
        handleSuccess(res, file) {
            // 因为上传过程为实例，这里模拟添加 url
            file.imgUrl = res.url;
            file.name = res.url;
            vm.uploadList.add(file);
        },
        handleBeforeUpload() {
            const check = vm.uploadList.length < 5;
            if (!check) {
                this.$Notice.warning({
                    title: '最多只能上传 5 张图片。'
                });
            }
            return check;
        },
        handleSubmit: function (name) {
            // handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            // });
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        handleSuccessPicUrl: function (res, file) {
            vm.goods.primaryPicUrl = file.response.url;
        },
        handleSuccessListPicUrl: function (res, file) {
            vm.goods.listPicUrl = file.response.url;
        },
        eyeImagePicUrl: function () {
            var url = vm.goods.primaryPicUrl;
            eyeImage(url);
        },
        eyeImageListPicUrl: function () {
            var url = vm.goods.listPicUrl;
            eyeImage(url);
        },
        eyeImage: function (e) {
            eyeImage($(e.target).attr('src'));
        },
        qrcodeCanvas: function(id) {
            $("#qrcodeCanvas").html("");
            $("#qrcodeCanvas").qrcode({
                render : "canvas",    //设置渲染方式，有table和canvas，使用canvas方式渲染性能相对来说比较好
                text : "emato../goods/goods?id=" + id,    //扫描二维码后显示的内容,可以直接填一个网址，扫描二维码后自动跳向该链接
                width : "100",               //二维码的宽度
                height : "100",              //二维码的高度
                background : "#ffffff",       //二维码的后景色
                foreground : "#000000",        //二维码的前景色
                src: '../../statics/img/logo.jpg'             //二维码中间的图片
            });

            var qrcSrc = $("canvas")[0].toDataURL();
            $("#qrcImg .qrcImg").attr("src", qrcSrc);
            var upLogSrc = "../../statics/img/logo.jpg";
            $("#qrcImg .upLogo").attr("src", upLogSrc);
            $("#qrcImg").show();//隐藏canvas部分

            openWindow({
                title: "二维码",
                area: ['400px', '400px'],
                content: jQuery("#qrcode"),
                btn: ["打印"],
                btn1: function (index) {
                    $("#qrcImg").print({});
                    $("#qrcImg").hide();
                    layer.close(index);
                }
            });
        }
    },
    mounted() {
        // this.uploadList = this.$refs.upload.fileList;
        $.get("../category/getCategorySelect", function (r) {
            vm.queryCategories = r.list;
            vm.categories = r.list;
        })
    }
});