$(function () {
    $("#jqGrid").Grid({
        url: '../tbcfstationitem/list',
        colModel: [
			{label: 'itemId', name: 'itemId', index: 'item_id', key: true, hidden: true},
			{label: '商品编号', name: 'itemCode', index: 'item_code', width: 80},
			{label: '商品名字', name: 'itemName', index: 'item_name', width: 80},
			{label: '商品标题简介', name: 'itemBrief', index: 'item_brief', width: 80},
			{label: '商品链接', name: 'itemUrl', index: 'item_url', width: 80,formatter:linkFormat},
			{label: '商品图片', name: 'itemImg', index: 'item_img', width: 80,formatter: imageFormat},
			{label: '商品价格', name: 'itemPrice', index: 'item_price', width: 80},
			{label: '点击量', name: 'itemNum', index: 'item_num', width: 80},
			{label: '所属平台', name: 'platformCode', index: 'platform_code', width: 80},
			{label: '平台名', name: 'platformName', index: 'platform_name', width: 80},
			{label: '启用状态', name: 'enableFlag', index: 'enable_flag', width: 80},
			{label: '创建日期', name: 'createTime', index: 'create_time', width: 80},
			{label: '商品一级分类', name: 'goodtype', index: 'goodtype', width: 80},
			{label: '商品二级分类', name: 'title', index: 'title', width: 80},
			{label: '商品品名', name: 'dname', index: 'dname', width: 80}]
    });
});

let vm = new Vue({
	el: '#rrapp',
	data: {
        showList: true,
        title: null,
		tbCfStationItem: {},
		Goodstype:null,
		Goodstype2:null,
        uploadList : [],
		Goodstype3:null,
		ruleValidate: {
			name: [
				{required: true, message: '名称不能为空', trigger: 'blur'}
			]
		},
		q: {
		    name: ''
		}
	},
	methods: {
		//获取一级分类
		changeGoodstype(){
          //  console.log(this.tbCfStationItem.itemCategory);
			let url = "../tbcfstationitem/queryByItemType?typeId="+this.tbCfStationItem.itemCategory;
			// console.log('url',url)
			let that = this;
			Ajax.request({
				url: url,
				type: "get",
				contentType: "application/json",
				successCallback: function (r) {
					if(r.code===0){
						that.Goodstype2 = r.list
					}
				}
			});
		},
		changeGoodstype2(){
            let url = "../tbcfstationitem/queryByItemTypeTwo?typeTwoId="+this.tbCfStationItem.itemCategorytwo;
			let that = this;
			Ajax.request({
				url: url,
				type: "get",
				contentType: "application/json",
				successCallback: function (r) {

					if(r.code===0){
						that.Goodstype3 = r.descripiton
					}
				}
			});
		},
		query: function () {
			vm.reload();
		},
		add: function () {
			vm.showList = false;
			vm.title = "新增";
			vm.tbCfStationItem = {};
		},
		update: function (event) {
            let itemId = getSelectedRow("#jqGrid");
			if (itemId == null) {
				return;
			}
			vm.showList = false;
            vm.title = "修改";

            vm.getInfo(itemId);
		},
		saveOrUpdate: function (event) {
            vm.tbCfStationItem.itemImg = vm.uploadList[0];
            let url = vm.tbCfStationItem.itemId == null ? "../tbcfstationitem/save" : "../tbcfstationitem/update";
            Ajax.request({
			    url: url,
                params: JSON.stringify(vm.tbCfStationItem),
                type: "POST",
			    contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
			});
		},
		del: function (event) {
            let itemIds = getSelectedRows("#jqGrid");
			if (itemIds == null){
				return;
			}

			confirm('确定要删除选中的记录？', function () {
                Ajax.request({
				    url: "../tbcfstationitem/delete",
                    params: JSON.stringify(itemIds),
                    type: "POST",
				    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
					}
				});
			});
		},
		getInfo: function(itemId){
            Ajax.request({
                url: "../tbcfstationitem/info/"+itemId,
                async: true,
                successCallback: function (r) {
                    vm.tbCfStationItem = r.tbCfStationItem;
                    vm.uploadList[0] = vm.tbCfStationItem.itemImg;
                }
            });
		},
		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');
		},
        reloadSearch: function() {
            vm.q = {
                name: ''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
		/*
		tirggerFile : function (event) {
			var file = event.target.files[0]; // (利用console.log输出看file文件对象)
			var formData = new FormData();
			formData.append("file", file);
			$.ajax({
				url: "../tbcfstationitem/image/",
				type: "POST",
				data: formData,
				cache: false,         //不设置缓存
				processData: false,  // 不处理数据
				contentType: false,// 不设置内容类型
				success: function (result) {
					result = JSON.parse(result);
					console.log(result)
					if (result.errno == 0) {//成功
						vm.tbCfStationItem.itemImg = result.data;
						console.log(vm.tbCfStationItem.itemImg)
						vm.$forceUpdate();
					} else {
						iview.Message.error(result.errmsg);
					}
				}
			});
		}*/

		/** ******************************************************************************************** */
		handleSuccess (response, file, fileList) {
			// "http://diaosaas-prod.oss-cn-shenzhen.aliyuncs.com/education/155728894307110106.jpg"
			vm.uploadList.push(response);
			$("#itemImg").show();
		},
		handleBeforeUpload (file) {
			// 上传图片大小不超过5M
			if (file.size > 5 * 1024 * 1024 ) {
				alert('请上传不超过5M的图片');
				return false;
			}
            const check = this.uploadList.length < 1;
            if (!check) {
                this.$Notice.warning({
                    title: '最多只能上传一张图片'
                });
                return false;
            }
			// 限制上传文件的宽高
			// return this.checkImageWH(file,750,320);
		},
		// 限制上传图片的宽高
		checkImageWH : function(file, width, height) {
			let self = this;
			return new Promise(function (resolve, reject) {
				let filereader = new FileReader();
				filereader.onload = e => {

					let src = e.target.result;
					const image = new Image();
					image.onload = function () {
						if (width && image.width != width) {
							self.$Notice.error({
								title: '请上传宽为' + width + "的图片",
							});
							reject();
						} else if (height && image.height != height) {
							self.$Notice.error({
								title: '请上传高为' + height + "的图片",
							});
							reject();
						} else {
							resolve();
						}
					};
					image.onerror = reject;
					image.src = src;
				};
				filereader.readAsDataURL(file);
			});
		},
		// 删除上传图片
		delImg1:function(url){
			if (vm.title != "详情") {
				vm.uploadList.remove(url);
				console.log(url);
				Ajax.request({
					url: "../api/osstest/deletetest?url="+url,
					async: false,
					type: "POST",
					contentType: "application/json",
					successCallback: function (resultData) {
						// console.log(resultData);
						iview.Message.success(resultData.success);
					}
				});
			}

		},
		/** ******************************************************************************************** */

	},
	created(){
		var that = this
		$.get('../tbcfgoodstype/queryAll',function (res) {
			//console.log("成功");
			 that.Goodstype = res.list;
		})
	}
});