$(function () {
    vm.getIsSupplierShowByThirdSn();
    $("#jqGrid").jqGrid({
        url: '../productstorerela/list',
        datatype: "json",
        colModel: [
            {label: 'ID', name: 'id', index: 'id', hidden: true, key: true},
            {label: '商品商户编号', name: 'goods_merch_sn', index: 'goods_merch_sn', hidden: true},
            {label: '所属商户', name: 'merchName', index: 'merchName', width: 70, align: 'center'},
            {label: '所属门店', name: 'storeName', index: 'storeName', width: 70, align: 'center'},
            {label: '商品类型', name: 'categoryName', index: 'categoryName', width: 80, align: 'center'},
            {
                label: '货品业务类型', name: 'goodsBizType', index: 'goods_biz_type', width: 70, align: 'center',
                formatter: function (value) {
                    if (value == '00') {
                        return '保税备货';
                    } else if (value == '02') {
                        return '保税展示补货';
                    } else if (value == '10') {
                        return '保税展示跨境';
                    }
                    return '普通货物';
                }
            },
            {label: '商品编码', name: 'goodsSn', index: 'goodsSn', width: 70, align: 'center'},
            {label: '名称', name: 'goodsName', index: 'goodsName', width: 160, align: 'left'},
            {label: '产品编码', name: 'productSn', index: 'productSn', width: 70, align: 'center'},
            {
                label: '上架', name: 'isOnSale', index: 'is_on_sale', width: 40, align: 'center',
                formatter: function (value) {
                    return transIsNot(value);
                }
            },
            {
                label: '热销', name: 'isHot', index: 'isHot', width: 40, align: 'center',
                formatter: function (value) {
                    return transIsNot(value);
                }
            },
            {label: '库存是否共享', name: 'isStockShare', index: 'isStockShare', width: 70, align: 'center',
                formatter: function (value) {
                    if (value == '0') {
                        return '否';
                    } else if (value == '1') {
                        return '是';
                    }
                    return '-';
                }},
            {label: '门店库存', name: 'stockNum', index: 'stockNum', width: 70, align: 'center'},
            {label: '零售价格', name: 'retailPrice', index: 'retailPrice', width: 60, align: 'center'},
            {label: '市场价', name: 'marketPrice', index: 'marketPrice', width: 60, align: 'center'},
            // {label: '库存价格', name: 'stockPrice', index: 'stockPrice', width: 80},
            {
                label: '销售量',
                name: 'sellVolume',
                index: 'a.sell_volume',
                width: 60,
                sortable: true, align: 'center',
                onSortCol: function (index, colindex, sortorder) {
                    //列排序事件
                    jQuery("#jqGrid").jqGrid('setGridParam', {page: $('#XtoPage').val()});
                }
            },
            {
                label: '操作', width: 120, 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.goodsId + ",\""+ row.storeId +"\",\""+row.goodsMerchSn+"\",\""+row.merchSn+"\")'><i class='fa fa-qrcode'></i>二维码</button>";
                }
                if (row.goodsBizType == '00') {
                    htmlStr = "<button class='btn btn-outline btn-primary' " +
                        "onclick='vm.qrcodeCanvas(" + row.goodsId + ",\""+ row.storeId +"\",\""+row.goodsMerchSn+"\",\""+row.merchSn+"\")'><i class='fa fa-qrcode'></i>二维码</button> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+
                    "<button class='btn btn-outline btn-primary' " +
                        "onclick='vm.putOn(" + row.id + ")'><i class='fa fa-qrcode'></i>投放</button>";
                }
                return htmlStr;
            }
            }
        ],
        viewrecords: true,
        height: 550,
        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"});
        }
    });
    $('#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: false,
        showViewList: true,
        showSaveSupplierGoods: true,
        title: null,
        uploadList: [],
        imgName: '',
        visible: false,
        productStoreRela: { stockNum: '', retailPrice: '', marketPrice: '', categoryId:'', brandId:'', specification:'', storeId:'', goodsBizType:'' },
        ruleValidate: {
            /*storeId: [
                {required: true, message: '门店不能为空'}
            ]*/
        },
        q: {
            storeId: '',
            goodsName: '',
            productSn: '',
            goodsSn: '', category: '', categoryTwo: '', goodsBizType:'',
            thirdPartyMerchCode:''
        },
        stores: [],
        macros: [],//商品单位
        goodss: {},
        products: [],
        showInput: false,
        showInputSpecification: false,
        categories: [],//一级分类
        categoriesTwo: [],
        brands: [],
        attributeEntityList: [{'id': '', 'goodsId': '', 'attributeId': '', 'value': '', 'isDelete': 0}],
        attributes: [],
        queryCategories: [],//一级分类
        queryCategoriesTwo: [],
        categoryId: '',
        freights: [],
        storeId: 0,
        specification: '',
        isOperator: '',
        isStockShare: false,
        isOperatorShow: false,
        thirdMerchantBizList:[],
        thirdMerchantBizShowList:[],
        storesList:[],
        thirdPartyMerchCode:'',
        isSupplierStockShare: false,
        goodsId: '',
        goodsList: [],
        isSupplierOperatorShow: false,
        storesBySupplierList: [],
        stockNum: '',
        isSupplierShowByThirdSn: false,
        roleType: false,
        isHotShow: false
    },
    methods: {
        getIsSupplierShowByThirdSn: function () {
            $.get("../thirdmerchantbiz/getIsSupplierShowByThirdSn", function (r) {
                vm.isSupplierShowByThirdSn = r.map.isSupplierShow;
                vm.roleType = r.map.roleType;
            });
        },
        changeGoods: function (opt) {
            var goodsId = opt.value;
            if (null != goodsId && '' != goodsId) {
                $.get("../goods/info/" + goodsId, function (r) {
                    vm.goodsId = goodsId;
                    if(r.goods.isHot == 1){
                        vm.isHotShow = true;
                    }else{
                        vm.isHotShow = false;
                    }
                    vm.showInput = true;
                    // console.log(r.goods.goodsBizType);
                    if (r.goods.goodsBizType == 11) {
                        vm.showInputSpecification = true;
                    } else {
                        vm.showInputSpecification = false;
                    }
                    if(r.goods.goodsBizType == '00' && r.goods.isStockShare == 1){//共享
                        vm.isStockShare = true;
                    }else{
                        vm.isStockShare = false;
                    }
                });
            }
        },
        changeSupplerGoods: function (opt) {
            var goodsId = opt.value;
            if (null != goodsId && '' != goodsId) {
                vm.goodsId = goodsId;
                $.get("../goods/info/" + goodsId, function (r) {
                    vm.showInput = true;
                    if(r.goods.isHot == 1){
                        vm.isHotShow = true;
                    }else{
                        vm.isHotShow = false;
                    }
                    if (r.goods.goodsBizType == 11) {
                        vm.showInputSpecification = true;
                    } else {
                        vm.showInputSpecification = false;
                    }
                    if(r.goods.goodsBizType == '00' && r.goods.isStockShare == 1){//共享
                        vm.isSupplierStockShare = true;
                        vm.productStoreRela.stockNum = r.goods.goodsNumber;
                    }else{
                        vm.isSupplierStockShare = false;
                        vm.productStoreRela.stockNum = vm.stockNum;
                    }
                });
            }
        },
        changeQueryCategories: function (opt) {
            var value = opt.value;
            $.get("../category/getCategorySelectByParent?parentId=" + value, function (r) {
                vm.queryCategoriesTwo = r.list;
            });
        },
        reloadSearch: function () {
            vm.q = {
                storeId: '',
                goodsName: '',
                productSn: '',
                goodsSn: '', category: '', categoryTwo: '', goodsBizType:'',
                thirdPartyMerchCode: ''
            }
            vm.reload();
        },
        query: function () {
            vm.reload();
        },
        getThirdMerchantBizList: function() {
            $.get("../thirdmerchantbiz/queryAlls", function (r) {
                vm.thirdMerchantBizList = r.list;
            });
        },
        getDataChangeStore: function (opt) {
            var storeId = opt.value;
            vm.storeId = storeId;
            if(storeId){
                $.get("../store/info/"+storeId, function (r) {
                    vm.storeId = storeId;
                    vm.thirdPartyMerchCode =  r.store.thirdPartyMerchCode;
                });
                vm.categories = [];
                vm.categoriesTwo = [];
                vm.getCategories(storeId);
                vm.getFreights(storeId);
            }
        },
        getGoodsByThirdMerchSn: function (opt) {
            var thirdMerchSn = opt.value;
            if(vm.isOperator == 'add'){
                $.get("../goods/queryAll?thirdMerchSn=" +thirdMerchSn+'&storeIdBySupplier='+vm.storeId, function (r) {
                    vm.goodss = r.list;
                });
            }else{
                var goodsId = vm.goodsId;
                $.get("../goods/queryAll?thirdMerchSn="+thirdMerchSn+"&id="+goodsId, function (r) {
                    vm.goodss = r.list;
                });
            }
        },
        add: function (event) {
            vm.stockNum = '';
            vm.showList = true;
            vm.showViewList = false;
            vm.showSaveSupplierGoods = true;
            vm.title = "新增";
            vm.isOperator = 'add';
            vm.isOperatorShow = false;
            vm.isStockShare = false;
            vm.freights = [];
            vm.brands = [];
            vm.categories = [];
            vm.categoriesTwo = [];
            vm.getStoreList();
            vm.productStoreRela = { stockNum: '', retailPrice: '', marketPrice: '', categoryId:'', brandId:'',specification:'', storeId:'' };
            vm.attributeEntityList = [{'id': '', 'goodsId': '', 'attributeId': '', 'value': '', 'isDelete': 0}];
            vm.getMacro();
            vm.showInput = false;
            vm.showInputSpecification = false;
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            $.get("../productstorerela/info/" + id, function (r) {
                var supplierThirdId = r.productStoreRela.supplierThirdId;
                vm.stockNum = r.productStoreRela.stockNum;
                vm.storeId = r.productStoreRela.storeId;
                var opt2 = {};
                opt2.value = r.productStoreRela.categoryId;
                opt2.flag = 1;
                vm.getAttributes(opt2);
                if (supplierThirdId != null) {
                    alert("当前选择的门店商品不能使用“修改商品”操作！");
                    return;
                } else {
                    vm.showList = true;
                    vm.showViewList = false;
                    vm.showSaveSupplierGoods = true;
                    vm.title = "修改";
                    vm.isOperator = 'update';
                    vm.isOperatorShow = true;
                    vm.productStoreRela = {};
                    vm.goodss = [];
                    vm.goodsList = [];
                    vm.getStoreList();
                    // vm.getProductStoreRela(r);
                    vm.getInfo(id);
                    vm.getMacro();
                    if (vm.productStoreRela.goodsBizType == 11) {
                        vm.showInput = true;
                        vm.showInputSpecification = true;
                    } else {
                        vm.showInput = false;
                        vm.showInputSpecification = false;
                    }
                }
            });
        },
        addSupplierGoods: function (event) {
            vm.stockNum = '';
            vm.showList = true;
            vm.showViewList = true;
            vm.showSaveSupplierGoods = false;
            vm.title = "新增供货商商品";
            vm.isOperator = 'add';
            vm.isSupplierOperatorShow = false;
            vm.freights = [];
            vm.brands = [];
            vm.categories = [];
            vm.categoriesTwo = [];
            vm.productStoreRela = { stockNum: '', retailPrice: '', marketPrice: '', categoryId:'', brandId:'',specification:'', storeId:'' };
            vm.attributeEntityList = [{'id': '', 'goodsId': '', 'attributeId': '', 'value': '', 'isDelete': 0}];
            vm.getMacro();
            vm.getStoreListBySupplier();
            vm.getThirdMerchantBizList();
            vm.showInput = false;
            vm.showInputSpecification = false;
            vm.isSupplierStockShare = false;
        },
        updateSupplierGoods: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            $.get("../productstorerela/info/" + id, function (r) {
                var supplierThirdId = r.productStoreRela.supplierThirdId;
                vm.stockNum = r.productStoreRela.stockNum;
                vm.storeId = r.productStoreRela.storeId;
                var opt2 = {};
                opt2.value = r.productStoreRela.categoryId;
                opt2.flag = 1;
                vm.getAttributes(opt2);
                if(supplierThirdId == null){
                    alert("当前选择的门店商品不能使用“修改供货商商品”操作！");
                    return;
                }else {
                    vm.showList = true;
                    vm.showViewList = true;
                    vm.showSaveSupplierGoods = false;
                    vm.title = "修改供货商商品";
                    vm.isOperator = 'update';
                    vm.isSupplierOperatorShow = true;
                    vm.productStoreRela = {};
                    vm.getStoreListBySupplier();
                    vm.getThirdMerchantBizList();
                    vm.getInfo(id);
                    vm.getMacro();
                    if (vm.productStoreRela.goodsBizType == 11) {
                        vm.showInput = true;
                        vm.showInputSpecification = true;
                    }else{
                        vm.showInput = false;
                        vm.showInputSpecification = false;
                    }
                }
            })
        },
        getStoreListBySupplier: function(){
            $.get("../store/queryAll?isSupplierGoods=1", function (r) {
                vm.storesBySupplierList = r.list;
            });
        },
        /**
         * 获取单位
         */
        getMacro: function () {
            $.get("../sys/macro/queryMacrosByValue?value=goodsUnit", function (r) {
                vm.macros = r.list;
            });
        },
        saveOrUpdate: function (event) {
            var url = vm.productStoreRela.id == null ? "../productstorerela/save" : "../productstorerela/update";
            vm.productStoreRela.attributeEntityList = vm.attributeEntityList;
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.productStoreRela),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../productstorerela/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("../productstorerela/info/" + id, function (r) {
                vm.productStoreRela = r.productStoreRela;
                vm.categoryId = r.productStoreRela.categoryId;
                vm.goodsId = r.productStoreRela.goodsId;

                var opt = {};
                opt.value = vm.productStoreRela.attributeCategory;
                vm.changeCategories(opt);
                if (r.productStoreRela.attributeEntityList.length > 0) {
                    vm.attributeEntityList = r.productStoreRela.attributeEntityList;
                } else {
                    vm.attributeEntityList = [{'id': '', 'goodsId': '', 'attributeId': '', 'value': '', 'isDelete': 0}];
                }
                vm.specification = vm.productStoreRela.specification;
                vm.storeId = vm.productStoreRela.storeId;
            });
        },
        getGoods: function (opt) {
            var storeId = opt.value;
            vm.storeId = storeId;
            if(storeId){
                if(vm.isOperator == 'add'){
                    $.get("../goods/queryAll?storeId=" +storeId, function (r) {
                        vm.goodsList = r.list;
                    });
                }else{
                    var goodsId = vm.goodsId;
                    $.get("../goods/queryAll?id="+goodsId, function (r) {
                        vm.goodsList = r.list;
                    });
                }
                vm.categories = [];
                vm.categoriesTwo = [];
                vm.getCategories(storeId);
                vm.getFreights(storeId);
            }
        },
        changeCategories: function (opt) {
            var value = opt.value;
            vm.brands = [];
            if(value){
                vm.getBrand(value);
                $.get("../category/getCategorySelectByParent?isShow=1&parentId=" + value, function (r) {
                    vm.categoriesTwo = r.list;
                });
            }
        },
        getCategories: function (storeId) {
            $.get("../category/getCategorySelect?isShow=1&storeId=" + storeId, function (r) {
                vm.categories = r.list;
            });
        },
        getBrand: function (categoryId) {
            $.get("../brand/queryAll?categoryId=" + categoryId, function (r) {
                vm.brands = r.list;
            });
        },
        getAttributes: function (opt) {
            var value = opt.value;
            if(value){
                $.get("../attribute/query?attributeCategoryId=" + value + "&storeId="+vm.storeId, function (r) {
                    vm.attributes = r.list;
                });

                if (opt.flag != 1 && !(value === vm.categoryId)) {
                    if (vm.attributeEntityList.length > 0 && vm.attributeEntityList[0].attributeId != '') {
                        for (var i = 0; i < vm.attributeEntityList.length; i++) {
                            if (!(vm.attributeEntityList[0].attributeId === '')) {
                                vm.attributeEntityList[i].isDelete = 1;
                            }
                        }

                        var goodsId = '';
                        if (vm.goodss) {
                            goodsId = vm.goodss.id;
                        }
                        vm.attributeEntityList.unshift({'id': '', 'goodsId': goodsId, 'attributeId': '', 'value': '', 'isDelete': 0});
                    }
                }
            }
        },
        getFreights: function(storeId) {
            $.get("../freight/queryAll?storeId=" + storeId, function (r) {
                vm.freights = r.list;
            });
        },
        getStoreList: function(){
            $.get("../store/queryAll?isSupplierGoods=0", function (r) {
                vm.storesList = r.list;
            });
        },
        addAttrRow: function () {
            let goodsId = '';
            if (vm.goods) {
                goodsId = vm.goods.id;
            }
            vm.attributeEntityList.push({'id': '', 'goodsId': goodsId, 'attributeId': '', 'value': '', 'isDelete': 0});
        },
        delAttrRow: function (index) {
            //最后一行时禁止删除
            if (vm.attributeEntityList.length == 1) {
                return;
            }
            vm.attributeEntityList[index].isDelete = 1;
        },
        reload: function (event) {
            vm.showList = false;
            vm.showViewList = true;
            vm.showSaveSupplierGoods = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    storeId: vm.q.storeId,
                    goodsName: vm.q.goodsName,
                    goodsSn: vm.q.goodsSn,
                    productSn: vm.q.productSn, category: vm.q.category, categoryTwo: vm.q.categoryTwo, goodsBizType:vm.q.goodsBizType,
                    thirdPartyMerchCode: vm.q.thirdPartyMerchCode
                },
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        uploadExcelSuccess: function () {
            alert('上传成功', function (index) {
                $("#jqGrid").trigger("reloadGrid");
            });
        },
        uploadExcelError: function () {
            alert('上传出现异常');
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        qrcodeCanvas: function(id, storeId, goodsMerchSn, merchSn) {
            if(merchSn != goodsMerchSn){
                alert("商品所属商户与门店商品所属商户不一致，请修改为一致后再生成二维码！");
                return;
            }
            $("#qrcodeCanvas").html("");
            $("#qrcodeCanvas").qrcode({
                render : "canvas",    //设置渲染方式，有table和canvas，使用canvas方式渲染性能相对来说比较好
                text : "emato../goods/goods?id=" + id +"&storeId=" + storeId,    //扫描二维码后显示的内容,可以直接填一个网址，扫描二维码后自动跳向该链接
                width : "100",               //二维码的宽度
                height : "100",              //二维码的高度
                background : "#ffffff",       //二维码的后景色
                foreground : "#000000",        //二维码的前景色
                src: '../../statics/img/logo.jpg'             //二维码中间的图片
            });

            var qrcSrc = $("canvas")[0].toDataURL();
            // console.log(qrcSrc);
            $("#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").show();
                    $("#qrcImg").print({});
                    $("#qrcImg").hide();
                    layer.close(index);
                }
            });

            $("#qrcImg").hide();
        },
        putOn: function (id) {
            if (id == null) {
                return;
            }
            $("#qrcodeCanvas").html("");
            $.get("../productstorerela/qrcodeCanvas/" + id, function (r) {
                var qrcSrc = r.url;
                $("#qrcImg2 .qrcImg").attr("src", qrcSrc);
                $("#qrcodeCanvas2").html($("#qrcImg2").html());
                openWindow({
                    title: "二维码",
                    area: ['450px', '450px'],
                    content: jQuery("#qrcode2"),
                    // btn: ["打印"],
                    btn1: function (index) {
                        $("#qrcImg2").show();
                        // $("#qrcImg").print({});
                        $("#qrcImg2").hide();
                        layer.close(index);
                    }
                });
            });
            $("#qrcImg2").hide();
        },
        uploadExcelSuccess: function (data) {
            if(data.code==0){
                alert('导入成功', function (index) {
                    vm.reload();
                });
            }else{
                if(data.msg == '导入成功！'){
                    alert(data.msg);
                    vm.reload();
                }else {
                    alert(data.msg);
                }
            }
        },
        uploadExcelError: function (data) {
            console.log(data);
            alert('上传出现异常，请重试！');
        },
        uploadExcelFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 xls 或 xlsx 格式的文件。'
            });
        }
    },
    mounted() {
        $.get("../category/getCategorySelect", function (r) {
            vm.queryCategories = r.list;
        });
        $.get("../store/queryAll", function (r) {
            vm.stores = r.list;
        });
        $.get("../sys/macro/queryMacrosByValue?value=goodsBizType", function (r) {
            vm.macros = r.list;
        });
        $.get("../thirdmerchantbiz/queryAll", function (r) {
            vm.thirdMerchantBizShowList = r.list;
        });
    }
});
