
$(function () {
    $("#jqGrid").jqGrid({
        url: '../mkstoreticketdiscount/list',
        datatype: "json",
        colModel: [
			{label: 'tickDiscId', name: 'tickDiscId', index: 'tick_disc_id', key: true, hidden: true},
            {label: '优惠券名称', name: 'name', index: 'name', width: 80, align: 'center'},
            // {label: '优惠券副标题', name: 'tickDiscSubTitle', index: 'tick_disc_sub_title', width: 80},
			{label: '优惠类型', name: 'tickDiscType', index: 'tick_disc_type', width: 60, align: 'center',
                formatter: function (value) {
                    if (value == '00') {
                        return '代金券';
                    } else if (value == '01') {
                        return '折扣券';
                    } else if (value == '02') {
                        return '兑换券';
                    }
                    return '';
                }},
			// {label: '商户编号', name: 'merchSn', index: 'merch_sn', width: 80},
			// {label: '第三方商户id', name: 'thirdMerchSn', index: 'third_merch_sn', width: 80},
			{label: '所属门店', name: 'storeName', index: 'storeName', width: 80, align: 'center'},
			// {label: '活动id', name: 'storeTopicId', index: 'store_topic_id', width: 80},
			// {label: '代金券减免金额(元)', name: 'voucherMoney', index: 'voucher_money', width: 80},
			// {label: '代金券使用条件(元)', name: 'voucherCond', index: 'voucher_cond', width: 80},
			// {label: '折扣券折扣(折)', name: 'discRatio', index: 'disc_ratio', width: 80},
			// {label: '折扣券使用条件(元)', name: 'discCond', index: 'disc_cond', width: 80},
			// {label: '兑换券使用条件(元)', name: 'exchCond', index: 'exch_cond', width: 80},
			// {label: '生效时间类型', name: 'effectTimeType', index: 'effect_time_type', width: 80, align: 'center',
             //    formatter: function (value) {
             //        if (value == '00') {
             //            return '固定时间';
             //        } else if (value == '01') {
             //            return '领取后生效';
             //        }
             //        return '';
             //    }},
            {label: '有效时间', name: 'inValidTime', index: 'inValidTime', width: 120, align: 'center'},
            {label: '状态', name: 'isPast', index: 'isPast', width: 60, align: 'center',
                formatter: function (value) {
                    if (value == '0') {
                        return '<span style="font-weight: bolder;background: #58d44d;color: white">进行中</span>';
                    } else if (value == '1') {
                        return '<span style="font-weight: bolder;background: #B2AEBC;color: white;">已结束</span>';
                    } else if (value == '2') {
                        return '<span style="font-weight: bolder;background: red;color: white">未开始</span>';
                    }
                    return '';
                }},
			// {label: '固定开始时间', name: 'fixBegTime', index: 'fix_beg_time', width: 80},
			// {label: '固定结束时间', name: 'fixEndTime', index: 'fix_end_time', width: 80},
			// {label: '领券延期生效天数(天)', name: 'postponeNum', index: 'postpone_num', width: 80},
			// {label: '领券使用有效天数(天)', name: 'validDayNum', index: 'valid_day_num', width: 80},
			{label: '库存', name: 'ticketNum', index: 'ticket_num', width: 60, align: 'center'},
			// {label: '适用类型', name: 'applyType', index: 'apply_type', width: 80, align: 'center',
             //    formatter: function (value) {
             //        if (value == '00') {
             //            return '全部商品参与';
             //        } else if (value == '01') {
             //            return '指定商品参与';
             //        } else if (value == '02') {
             //            return '指定商品不参与';
             //        }
             //        return '';
             //    }},
            {label: '是否有效', name: 'isValid', index: 'is_valid', width: 60, align: 'center',
                formatter: function (value) {
                    if (value == '0') {
                        return '有效';
                    } else if (value == '1') {
                        return '无效';
                    }
                    return '';
                }},
            {
                label: '操作', width: 180, align: 'center', sortable: false, formatter: function (value, col, row) {
                    let htmlStr = "";
                // if (hasPermission('order:refund')) {}
                    if(row.isPast != 1 && row.isValid == 0){
                        htmlStr = "<button class='btn btn-outline btn-primary' " +
                            "onclick='vm.showInfo(" + row.tickDiscId + ")'><i class='fa fa-qrcode'></i>详情</button>&nbsp;&nbsp;&nbsp;&nbsp;" +
                            "<button class='btn btn-outline btn-primary' " +
                            "onclick='vm.updateById(" + row.tickDiscId + ")'><i class='fa fa-qrcode'></i>修改</button>&nbsp;&nbsp;&nbsp;&nbsp;" +
                            "<button class='btn btn-outline btn-primary' " +
                            "onclick='vm.putOn(" + row.tickDiscId + ")'><i class='fa fa-qrcode'></i>投放</button>&nbsp;&nbsp;&nbsp;&nbsp;" +

                            "<button class='btn btn-outline btn-primary' " +
                            "onclick='vm.getUserCoupon(" + row.tickDiscId + ")'><i class='fa fa-qrcode'></i>码库</button>";
                    }
                    if(row.isPast == 1 || row.isValid == 1){
                        htmlStr = "<button class='btn btn-outline btn-primary' " +
                            "onclick='vm.showInfo(" + row.tickDiscId + ")'><i class='fa fa-qrcode'></i>详情</button>&nbsp;&nbsp;&nbsp;&nbsp;"+

                            "<button class='btn btn-outline btn-primary' " +
                            "onclick='vm.getUserCoupon(" + row.tickDiscId + ")'><i class='fa fa-qrcode'></i>码库</button>";
                    }
                return htmlStr;
            }}
			// {label: '领取入口，格式：1,2,...,n，【get_enter，1:商品详情页/购物车等商城页面】', name: 'getEnter', index: 'get_enter', width: 80},
			// {label: '能否分享领取', name: 'canShareGet', index: 'can_share_get', width: 80, align: 'center',
             //    formatter: function (value) {
             //        if (value == '0') {
             //            return '能';
             //        } else if (value == '1') {
             //            return '否';
             //        }
             //        return '';
             //    }},
			// {label: '每人限领数', name: 'limitNum', index: 'limit_num', width: 80},
			// {label: '活动图片url(小图)', name: 'advImgUrl', index: 'adv_img_url', width: 80},
			// {label: '门店logo图url', name: 'storeLogoUrl', index: 'store_logo_url', width: 80},
			// {label: '门店名称', name: 'storeName', index: 'store_name', width: 80},
			// {label: '券面颜色，如:#ababab', name: 'ticketColor', index: 'ticket_color', width: 80},
			// {label: '操作说明', name: 'optDecl', index: 'opt_decl', width: 80},
			// {label: '优惠说明', name: 'discDecl', index: 'disc_decl', width: 80},
			// {label: '使用须知', name: 'useNoti', index: 'use_noti', width: 80},
			// {label: '客服电话，手机或固话', name: 'svrTel', index: 'svr_tel', width: 80},
			// {label: '备注', name: 'note', index: 'note', width: 80},
			// {label: '创建人编号', name: 'createrSn', index: 'creater_sn', width: 80},
			// {label: '创建时间', name: 'createTime', index: 'create_time', width: 80},
			// {label: '修改人编号', name: 'moderSn', index: 'moder_sn', width: 80},
			// {label: '修改时间', name: 'modTime', index: 'mod_time', width: 80},
			// {label: '时间戳', name: 'tstm', index: 'tstm', width: 80},
			// {label: '发放方式 0：按订单发放 1：按用户发放(通用优惠券，用户点击领取) 2:商品转发送券 3：按商品发放 4:新用户注册 5：线下发放 6评价好评红包（固定或随机红包） 7包邮（不入会员优惠券表）', name: 'sendType', index: 'send_type', width: 80}
			],
		viewrecords: true,
        height: 580,
        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"});
        }
    });


    $("#jqGridOrder").jqGrid({
        url: '../usercoupon/getUserCouponByDiscIdList',
        datatype: "json",
        colModel: [
            {label: '所属门店', name: 'storeName', index: 'storeName', width: 80, align: 'center'},
            {label: '优惠券码', name: 'couponNumber', index: 'couponNumber', width: 80, align: 'center'},
            {label: '领取人', name: 'nickname', index: 'nickname', width: 60, align: 'center'},
            {label: '领取时间', name: 'addTime', index: 'add_time', width: 120, align: 'center',
                formatter: function (value) {
                    // console.log(value);
                    return transDate(value, 'yyyy-MM-dd hh:mm:ss');
                }
            },
            {label: '生效时间', name: 'validTime', index: 'validTime', width: 120, align: 'center',
                formatter: function (value) {
                    // console.log(value);
                    return transDate(value, 'yyyy-MM-dd hh:mm:ss');
                }
            },
            {label: '更新时间', name: 'modTime', index: 'modTime', width: 120, align: 'center',
                formatter: function (value) {
                    // console.log(value);
                    return transDate(value, 'yyyy-MM-dd hh:mm:ss');
                }
            },
            {label: '失效时间', name: 'endTime', index: 'endTime', width: 120, align: 'center',
                formatter: function (value) {
                    // console.log(value);
                    return transDate(value, 'yyyy-MM-dd hh:mm:ss');
                }
            },
            {label: '状态', name: 'isUsed', index: 'isUsed', width: 60, align: 'center',
                formatter: function (value) {
                    if (value == '0') {
                        return '未使用';
                    } else if (value == '1') {
                        return '已使用';
                    }
                    return value;
                }
            }
        ],
        viewrecords: true,
        height: 400,
        width:1600,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: false,
        multiselect: true,
        pager: "#jqGridPagerOrder",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            $("#jqGridOrder").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
});

let vm = new Vue({
	el: '#rrapp',
	data: {
        title: null,
		mkStoreTicketDiscount: {advImgUrl: '', storeLogoUrl: ''},
		ruleValidate: {
			name: [
				{required: true, message: '名称不能为空', trigger: 'blur'}
			]
		},
		q: {
		    name: ''
		},
        g: {
          goodsName: ''
        },
        thirdMerchantBizList: [],
        goodsList: [],
        storeList: [],
		isVoucher: true,//代金券
		isDisc: false,//折扣券
		isExch: false,//兑换券
		isEffectTimeType00:true,//固定时间
        isEffectTimeType01: false,//领取后生效
        isApplyType: false,//商品是否显示
        storeId: '',
        value3: false,
        productStoreRela: {},
        currentPage: 1,
        limit:16,
        totalPage:'',
        totalCount:'',
        checkGoodsByHtmlList:[],//选择商品前端储存的数组
        mkStoreTicketDiscountGoods:{checkGoodsList:[]},
        applyType:'',
        checkGoodsDataList:[],//选择完商品后查询的商品列表
        checkGoodsTotalCount: 0,
        checkGoodsLimit: 6,
        checkGoodsCurrentPage:1,
        tid:'',//唯一id
        ticketColor: '',
        queryColorList:[{color:'00CC00',back:'g'},{color:'009900',back:'g'},{color:'66CCCC',back:'g'},{color:'009999',back:'g'},
            {color:'FF9966',back:'r'},{color:'FF0066',back:'r'},{color:'CC00FF',back:'r'},{color:'CC0000',back:'r'}],
        colorList:[],
        isOperatorShow: false,
        showList: true,
        showViewList: false,
        showInfoList: true,
        showOrderList: true,
        tickDiscId:'',
        macros: [],
        goodsBizType:'',
        c:{
            isUsed: ''
        },
        tickDiscType:''
	},
	methods: {
        getColor: function (value,isColor) {
          vm.ticketColor = '#'+value;
          var classValue = 'tick-color-g';
          if(isColor == 'g'){
              classValue = 'tick-color-g';
          }else {
              classValue = 'tick-color-r';
          }
          if($("#"+value).attr('name')=='noCheck') {
              $("#" + value).attr("class", classValue);
              $("#" + value).attr("name", "check");
              vm.colorList.push(value);
              for (var g = 0; g < vm.queryColorList.length; g++) {
                  if (value != vm.queryColorList[g].color) {
                      $("#" + vm.queryColorList[g].color).attr("class", "");
                      vm.colorList.remove(vm.queryColorList[g].color);
                      $("#"+ vm.queryColorList[g].color).attr("name","noCheck");
                  }else{
                      $("#"+ vm.queryColorList[g].color).attr("name","check");
                  }
              }
          }else{
              $("#"+value).attr("class","");
              $("#"+value).attr("name","noCheck");
              // console.log(vm.colorList);
              for (var g = 0; g < vm.colorList.length; g++) {
                  if(value == vm.colorList[g]){
                      vm.colorList.remove(vm.colorList[g]);
                  }
              }
          }
            // console.log(value);
            // console.log(vm.colorList);
            if(vm.colorList.length > 0){
                vm.ticketColor = "#"+vm.colorList[0];
            }else{
                vm.ticketColor = "";
            }
        },
		query: function () {
			vm.reload();
		},
        /**
         * 生成唯一id
         * @returns {string}
         */
        guid: function () {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                return v.toString(16);
            });
        },
        /**
         * 选择指定商品ok按钮
         */
        ok : function () {
            // this.$Message.info('Clicked ok');
            vm.checkGoodsDataList =[];
            vm.mkStoreTicketDiscountGoods.checkGoodsList = vm.checkGoodsByHtmlList;
            vm.mkStoreTicketDiscountGoods.guid = vm.tid;
            vm.mkStoreTicketDiscountGoods.isSubmit = 0;//ok按钮提交的数据则为0

            $.ajax({
                type: "POST",
                url: '../mkstoreticketgoodstemp/batchSaveDiscountGoods',
                contentType: "application/json",
                data: JSON.stringify(vm.mkStoreTicketDiscountGoods),
                success: function (r) {
                    if (r.code === 0) {
                        vm.getCheckGoodsList(vm.storeId);
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        /**
         * 选择指定商品cancel按钮
         */
        cancel: function () {
            vm.checkGoodsByHtmlList =[];
            // console.log(vm.checkGoodsByHtmlList);
            //点击取消按钮如有分页记录的数据就删除
            vm.mkStoreTicketDiscountGoods.checkGoodsList=vm.checkGoodsByHtmlList;
            vm.mkStoreTicketDiscountGoods.guid=vm.tid;
            vm.mkStoreTicketDiscountGoods.isSubmit = 1;//cancel按钮提交的数据则为1
            $.ajax({
                type: "POST",
                url: '../mkstoreticketgoodstemp/batchSaveDiscountGoods',
                contentType: "application/json",
                data: JSON.stringify(vm.mkStoreTicketDiscountGoods),
                success: function (r) {
                    if (r.code === 0) {
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        /**
         * 指定商品分页
         */
        loadGoodsDataByPage: function (value) {
            vm.currentPage = value;
            vm.mkStoreTicketDiscountGoods.checkGoodsList=vm.checkGoodsByHtmlList;
            vm.mkStoreTicketDiscountGoods.guid=vm.tid;
            vm.mkStoreTicketDiscountGoods.isSubmit = 1;//分页记录的数据则为1
            $.ajax({
                type: "POST",
                url: '../mkstoreticketgoodstemp/batchSaveDiscountGoods',
                contentType: "application/json",
                data: JSON.stringify(vm.mkStoreTicketDiscountGoods),
                success: function (r) {
                    if (r.code === 0) {
                    } else {
                        alert(r.msg);
                    }
                }
            });
            vm.getGoodsList(vm.storeId);
        },
        handlePageSize: function (value) {
            vm.limit = value;
            vm.currentPage = 1;
            vm.getGoodsList(vm.storeId);
        },
        /**
         * 已选中商品分页
         * @param value
         */
        loadCheckGoodsDataByPage: function (value) {
            vm.checkGoodsCurrentPage = value;
            vm.getCheckGoodsList(vm.storeId);
        },
        /**
         * 已选中商品分页
         * @param value
         */
        handleCheckGoodsPageSize: function (value) {
            vm.checkGoodsLimit = value;
            vm.checkGoodsCurrentPage = 1;
            vm.getCheckGoodsList(vm.storeId);
        },
        /**
         * 获取已选中商品
         * @param storeId
         */
        getCheckGoodsList: function(storeId){
            if(storeId){
                $.get("../mkstoreticketgoodstemp/queryAllDiscountByStoreId?storeId=" + vm.storeId+"&guid="+vm.tid+"&page="+vm.checkGoodsCurrentPage+"&limit="+vm.checkGoodsLimit, function (r) {
                    if(r.code == 0){
                        vm.checkGoodsDataList = r.page.list;
                        // vm.totalPage = r.page.totalPage;
                        vm.checkGoodsTotalCount = r.page.totalCount;
                        vm.checkGoodsCurrentPage = r.page.currPage;
                        vm.checkGoodsLimit = r.page.pageSize;
                    }
                });
            }
        },
        /**
         * 删除已选中商品
         * @param discGoodTempId
         * @param goodsId
         */
        delCheckGoods: function (discGoodTempId,goodsId) {
            var checkGoodsIds = [discGoodTempId];
            $.ajax({
                type: "POST",
                url: "../mkstoreticketgoodstemp/updateIsValidById",
                contentType: "application/json",
                data: JSON.stringify(checkGoodsIds),
                success: function (r) {
                    if (r.code == 0) {
                        vm.getCheckGoodsList(vm.storeId);
                        for (var g = 0; g < vm.checkGoodsByHtmlList.length; g++) {
                            if(goodsId == vm.checkGoodsByHtmlList[g].goodsId){
                                vm.checkGoodsByHtmlList.remove(vm.checkGoodsByHtmlList[g]);
                            }
                        }
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        /**
         * 生效时间类型联动
         * @param value
         */
        changeEffectTimeType: function (value) {
			if(value == '00'){
				vm.isEffectTimeType00 = true;
				vm.isEffectTimeType01 = false;
			}else if(value == '01'){
                vm.isEffectTimeType00 = false;
                vm.isEffectTimeType01 = true;
			}
        },
        /**
         * 适用商品联动
         * @param value
         */
        changeApplyType: function (value) {
            // vm.storeId = '8';
            console.log(vm.goodsBizType)
            if(value == '00'){
                vm.isApplyType = false;
            }else if(value == '01'){
                console.log(vm.storeId=='')
                if(vm.storeId==''){
                    alert("请先在基本属性中选择所属门店");
                    vm.mkStoreTicketDiscount.applyType = '00';
                }else if(vm.goodsBizType==''){
                    alert("请先在基本属性中选择所属商品业务类型");
                    vm.mkStoreTicketDiscount.applyType = '00';
                }else if(vm.storeId && vm.goodsBizType){
                    vm.isApplyType = true;
                    vm.applyType ='01';
                    // vm.getCheckGoodsList(vm.storeId);
                }
            }else if(value == '02'){
                if(vm.storeId == ''){
                    alert("请先在基本属性中选择所属门店");
                    vm.mkStoreTicketDiscount.applyType = '00';
                }
                if(vm.goodsBizType == ''){
                    alert("请先在基本属性中选择所属商品业务类型");
                    vm.mkStoreTicketDiscount.applyType = '00';
                }
                if(vm.storeId && vm.goodsBizType){
                    vm.isApplyType = true;
                    vm.applyType ='02';
                }
            }
        },
        /**
         * 选择商品弹框按钮
         */
        checkGoods: function () {
            vm.value3 = true;
            vm.limit = 16;
            vm.getGoodsList(vm.storeId,vm.goodsBizType);
        },
        /**
         * 选择商品参数查询
         */
        reloadGoodsByStore: function (){
            if(vm.storeId){
                vm.getGoodsList(vm.storeId,vm.goodsBizType);
            }else{
                alert("请先在基本属性中选择所属门店");
            }
        },
        /**
         * 选择商品重置参数查询
         */
        reloadGoodsSearch: function (){
            if(vm.storeId){
                vm.g.goodsName='';
                vm.getGoodsList(vm.storeId,vm.goodsBizType);
            }else{
                alert("请先在基本属性中选择所属门店");
            }
        },
        /**
         * 查询选择商品分页
         * @param storeId
         */
        getGoodsList: function(storeId,goodsBizType){
            if(storeId){
                $.get("../productstorerela/queryGoodsRealListByDiscountTid?storeId=" + storeId+"&goodsName="+vm.g.goodsName+"&guid="+vm.tid+"&applyType="+vm.applyType+"&goodsBizType="+goodsBizType
                    +"&promTypeId="+6+"&page="+1+"&limit="+vm.limit, function (r) {
                    // console.log(r)
                    if(r.code == 0){
                        vm.goodsList = r.page.list;
                        vm.totalPage = r.page.totalPage;
                        vm.totalCount = r.page.totalCount;
                        vm.currentPage = r.page.currPage;
                        vm.limit = r.page.pageSize;
                    }
                });
            }
        },
        /**
         * 商品选中
         * @param item 商品信息
         */
        selectThisGoods: function (item) {
            // $.get("../mkstoreticketgoodstemp/queryGoodsTempByGuidAndSubmit?storeId="+vm.storeId+"&guid="+vm.tid+"&applyType="+vm.applyType, function (r) {
            //     for(var j=0;j<r.list.length;j++){
            //         vm.checkGoodsByHtmlList.push(r.list[j]);
            //     }
            // });
            if(item.isCheck==0){
                for(var i = 0; i < vm.goodsList.length; i++){
                    if(vm.goodsList[i].goodsId == item.goodsId){
                        vm.goodsList[i].isCheck = 1;
                    }
                }
                vm.checkGoodsByHtmlList.push({goodsId: item.goodsId, storeRealId: item.id, goodsName: item.goodsName, applyType: vm.applyType, guid:vm.tid, discGoodTempId:item.discGoodTempId});
            }else{
                for(var i = 0; i < vm.goodsList.length; i++){
                    if(vm.goodsList[i].goodsId == item.goodsId){
                        vm.goodsList[i].isCheck = 0;
                    }
                }
                for (var g = 0; g < vm.checkGoodsByHtmlList.length; g++) {
                    if(item.goodsId == vm.checkGoodsByHtmlList[g].goodsId){
                        vm.checkGoodsByHtmlList.remove(vm.checkGoodsByHtmlList[g]);
                    }
                }
                //删除取消选中的商品
                vm.mkStoreTicketDiscountGoods.storeRelaId=item.id;
                vm.mkStoreTicketDiscountGoods.guid=vm.tid;
                $.ajax({
                    type: "POST",
                    url: '../mkstoreticketgoodstemp/updateTempByIsValid',
                    contentType: "application/json",
                    data: JSON.stringify(vm.mkStoreTicketDiscountGoods),
                    success: function (r) {
                    }
                });
            }

        },
		add: function () {
            vm.tid = vm.guid();
            vm.storeId = '';
            vm.tickDiscId = '';
            vm.goodsBizType = '';
            vm.applyType = '';
            vm.isApplyType = false;
            vm.showList = false;
            vm.showViewList = true;
            vm.showInfoList = true;
            vm.showOrderList = true;
			vm.title = "新增";
            vm.thirdMerchantBizList = [];
            vm.storeList = [];
            vm.goodsList = [];
            // vm.macros = [];
            vm.checkGoodsDataList = [];
            vm.checkGoodsByHtmlList = [];
            vm.checkGoodsTotalCount = 0;
			vm.mkStoreTicketDiscount = {tickDiscType:'00',effectTimeType:'00',applyType:'00',getEnter:'1',isValid:'0',isStoreShow:'0', advImgUrl: '', storeLogoUrl: '',limitNum:'',discDecl:'',useNoti:'',
                fixBegTime:'',fixEndTime:'',thirdMerchSn:'',storeId:''};
            vm.getThirdMerchantBizList();
            vm.isOperatorShow = false;
            vm.getColor('00CC00','g');
		},
		update: function (event) {
            let tickDiscId = getSelectedRow();
			if (tickDiscId == null) {
				return;
			}
            vm.showList = false;
            vm.showViewList = true;
            vm.showInfoList = true;
            vm.showOrderList = true;
            vm.title = "修改";
            vm.getThirdMerchantBizList();

            vm.getInfo(tickDiscId);
            vm.isOperatorShow = true;
		},
        updateById: function (tickDiscId) {
            if (tickDiscId == null) {
                return;
            }
            vm.showList = false;
            vm.showViewList = true;
            vm.showInfoList = true;
            vm.showOrderList = true;
            vm.title = "修改";
            vm.getThirdMerchantBizList();

            vm.getInfo(tickDiscId);
            vm.isOperatorShow = true;
        },
        showInfo: function(tickDiscId){
            if(tickDiscId == null){
                return;
            }
            vm.title = "查看优惠券信息";
            vm.showList = true;
            vm.showViewList = true;
            vm.showOrderList = true;
            vm.showInfoList = false;
            vm.getShowInfo(tickDiscId);
        },
        putOn: function (tickDiscId) {
            if (tickDiscId == null) {
                return;
            }
            $("#qrcodeCanvas").html("");
            $.get("../mkstoreticketdiscount/qrcodeCanvasByTickDiscId/" + tickDiscId, function (r) {
                // console.log(r.url);
                var qrcSrc = r.url;
                $("#qrcImg .qrcImg").attr("src", qrcSrc);

                $("#qrcodeCanvas").html($("#qrcImg").html());

                openWindow({
                    title: "二维码",
                    area: ['450px', '450px'],
                    content: jQuery("#qrcode"),
                    // btn: ["打印"],
                    btn1: function (index) {
                        $("#qrcImg").show();
                        // $("#qrcImg").print({});
                        $("#qrcImg").hide();
                        layer.close(index);
                    }
                });
            });

            $("#qrcImg").hide();
        },
        getUserCoupon: function (tickDiscId) {
            if (tickDiscId == null) {
                return;
            }
            $.get("../mkstoreticketdiscount/info/"+tickDiscId, function (r) {
                vm.title = r.mkStoreTicketDiscount.name+"码库";
                vm.showList = true;
                vm.showViewList = true;
                vm.showInfoList = true;
                vm.tickDiscId = tickDiscId;
                vm.showOrderList = false;
                let page = $("#jqGridOrder").jqGrid('getGridParam', 'page');
                $("#jqGridOrder").jqGrid('setGridParam', {
                    postData: {'isUsed': vm.c.isUsed, 'tickDiscId': tickDiscId},
                    page: page
                }).trigger("reloadGrid");
            });
        },
        queryOrder: function () {
            vm.reloadOrder();
        },
        reloadOrderSearch: function() {
            vm.c = {
                isUsed: ''
            }
            vm.reloadOrder();
        },
        reloadOrder: function () {
            let page = $("#jqGridOrder").jqGrid('getGridParam', 'page');
            $("#jqGridOrder").jqGrid('setGridParam', {
                postData: {'isUsed': vm.c.isUsed, 'tickDiscId': vm.tickDiscId},
                page: page
            }).trigger("reloadGrid");
        },
		saveOrUpdate: function (event) {
            let url = vm.mkStoreTicketDiscount.tickDiscId == null ? "../mkstoreticketdiscount/save" : "../mkstoreticketdiscount/update";

            if(vm.ticketColor != '' && vm.ticketColor != null){
                vm.mkStoreTicketDiscount.ticketColor = vm.ticketColor;
            }else{
                vm.mkStoreTicketDiscount.ticketColor = "#00CC00";
            }
            vm.mkStoreTicketDiscount.guid = vm.tid;
			$.ajax({
				type: "POST",
			    url: url,
			    contentType: "application/json",
			    data: JSON.stringify(vm.mkStoreTicketDiscount),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
			});
		},
		del: function (event) {
            let tickDiscIds = getSelectedRows();
			if (tickDiscIds == null){
				return;
			}

			confirm('确定要删除选中的记录？', function () {
				$.ajax({
					type: "POST",
				    url: "../mkstoreticketdiscount/delete",
				    contentType: "application/json",
				    data: JSON.stringify(tickDiscIds),
				    success: function (r) {
						if (r.code == 0) {
							alert('操作成功', function (index) {
								$("#jqGrid").trigger("reloadGrid");
							});
						} else {
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(tickDiscId){
			$.get("../mkstoreticketdiscount/info/"+tickDiscId, function (r) {
                vm.mkStoreTicketDiscount = r.mkStoreTicketDiscount;
                vm.storeId = r.mkStoreTicketDiscount.storeId;
                vm.tid = r.mkStoreTicketDiscount.guid;
                vm.tickDiscId = r.mkStoreTicketDiscount.tickDiscId;
                vm.goodsBizType = r.mkStoreTicketDiscount.goodsBizType;
                vm.changeApplyType(r.mkStoreTicketDiscount.applyType);
                vm.changeEffectTimeType(r.mkStoreTicketDiscount.effectTimeType);
                vm.getCheckGoodsList(r.mkStoreTicketDiscount.storeId);
                var ticketColor = r.mkStoreTicketDiscount.ticketColor.substring(1, r.mkStoreTicketDiscount.ticketColor.length);
                var back = '';
                for (var g = 0; g < vm.queryColorList.length; g++) {
                    if (ticketColor == vm.queryColorList[g].color) {
                        back = vm.queryColorList[g].back;
                    }
                }
                vm.getColor(ticketColor, back);
            });
		},
        getShowInfo: function(tickDiscId){
            $.get("../mkstoreticketdiscount/info/"+tickDiscId, function (r) {
                vm.mkStoreTicketDiscount = r.mkStoreTicketDiscount;
                vm.storeId = r.mkStoreTicketDiscount.storeId;
                vm.tid = r.mkStoreTicketDiscount.guid;
                vm.goodsBizType = r.mkStoreTicketDiscount.goodsBizType;
                vm.changeApplyType(r.mkStoreTicketDiscount.applyType);
                vm.getCheckGoodsList(r.mkStoreTicketDiscount.storeId);
                var ticketColor = r.mkStoreTicketDiscount.ticketColor.substring(1, r.mkStoreTicketDiscount.ticketColor.length);
                var back = '';
                for (var g = 0; g < vm.queryColorList.length; g++) {
                    if (ticketColor == vm.queryColorList[g].color) {
                        back = vm.queryColorList[g].back;
                    }
                }
                $("#ticketColorId").css("background-color", r.mkStoreTicketDiscount.ticketColor);
                if(back == 'g'){
                    $("#ticketColorId").attr("class", 'tick-color-g');
                }else{
                    $("#ticketColorId").attr("class", 'tick-color-r');
                }
                vm.changeEffectTimeType(r.mkStoreTicketDiscount.effectTimeType);
            });
        },
        getThirdMerchantBizList: function() {
            $.get("../thirdmerchantbiz/queryAll", function (r) {
                vm.thirdMerchantBizList = r.list;
            });
        },
        changeStore: function (option) {
            var thirdMerchSn = option.value;
            if(thirdMerchSn){
                vm.getStoreList(thirdMerchSn);
            }
        },
        getStoreList: function(thirdMerchSn){
            $.get("../store/queryAll?thirdMerchSn=" + thirdMerchSn, function (r) {
                vm.storeList = r.list;
            });
        },
        changeGoods: function (option) {
            var storeId = option.value;
            if(storeId){
                vm.storeId = storeId;
            }
        },
        changeGoodsBizType: function(opt) {
            var goodsBizType = opt.value;
            if(goodsBizType){
                vm.goodsBizType = goodsBizType;
            }

        },
        chanTick: function (value) {
            if(value == '00'){
                vm.isVoucher = true;
                vm.isDisc = false;
                vm.isExch = false;
                vm.tickDiscType = '00';
            }else if(value == '01'){
                vm.isVoucher = false;
                vm.isDisc = true;
                vm.isExch = false;
                vm.tickDiscType = '01';
            }else if(value == '02'){
                vm.isVoucher = false;
                vm.isDisc = false;
                vm.isExch = true;
                vm.tickDiscType = '02';
            }
        },
        tabsClick:function (value) {
            if(value == 'name3') {
                var limitNum = vm.mkStoreTicketDiscount.limitNum;
                if(!limitNum){
                    limitNum = 1;
                }
                vm.mkStoreTicketDiscount.useNoti = "每人限领"+limitNum+"张，不可转赠好友，仅限商城下单使用";
                var applyTypeName = "";
                if(vm.mkStoreTicketDiscount.applyType === '00'){
                    applyTypeName = '全部商品可用';
                }
                if (vm.mkStoreTicketDiscount.applyType === '01'){
                    applyTypeName = '部分商品可用';
                }
                if (vm.mkStoreTicketDiscount.applyType === '02'){
                    applyTypeName = '部分商品不可用';
                }
                var voucherCoud = 0;
                var voucherMoney = 0;
                var discCond = 0;
                var discRatio = 0;
                var discDecl = "";
                if(vm.mkStoreTicketDiscount.tickDiscType === '00'){
                    if(vm.mkStoreTicketDiscount.voucherCond){
                        voucherCoud = vm.mkStoreTicketDiscount.voucherCond;
                    }
                    if(vm.mkStoreTicketDiscount.voucherMoney){
                        voucherMoney = vm.mkStoreTicketDiscount.voucherMoney;
                    }
                    discDecl="满"+voucherCoud +"元，减"+voucherMoney+"元，"+applyTypeName;
                }
                if(vm.mkStoreTicketDiscount.tickDiscType === '01'){
                    if(vm.mkStoreTicketDiscount.discCond){
                        discCond = vm.mkStoreTicketDiscount.discCond;
                    }
                    if(vm.mkStoreTicketDiscount.discRatio){
                        discRatio = vm.mkStoreTicketDiscount.discRatio;
                    }
                    discDecl="满" + discCond + "元，" + discRatio + "折，" + applyTypeName;
                }
                vm.mkStoreTicketDiscount.discDecl = discDecl;
            }

        },
        reloadSearch: function() {
            vm.q = {
                name: ''
            }
            vm.reload();
		},
		reload: function (event) {
            vm.showList = true;
            vm.showViewList = false;
            vm.showInfoList = true;
            vm.showOrderList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
			$("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
            for (var g = 0; g < vm.queryColorList.length; g++) {
                $("#" + vm.queryColorList[g].color).attr("class", "");
                vm.colorList.remove(vm.queryColorList[g].color);
                $("#"+ vm.queryColorList[g].color).attr("name","noCheck");
            }
		},
        /**
         * 详情页返回
         * @param event
         */
        reloadInfoBack: function (event) {
            vm.showList = true;
            vm.showViewList = false;
            vm.showInfoList = true;
            vm.showOrderList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name},
                page: page
            }).trigger("reloadGrid");
        },
        /**
         * 修改页返回
         * @param event
         */
        reloadBack: function (event) {
            vm.showList = true;
            vm.showViewList = false;
            vm.showInfoList = true;
            vm.showOrderList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
            for (var g = 0; g < vm.queryColorList.length; g++) {
                $("#" + vm.queryColorList[g].color).attr("class", "");
                vm.colorList.remove(vm.queryColorList[g].color);
                $("#"+ vm.queryColorList[g].color).attr("name","noCheck");
            }
            console.log(vm.isOperatorShow);
            if(vm.isOperatorShow){
                //触发返回按钮时，将失效的商品还原为有效
                var tempObj = {tickDiscId:vm.tickDiscId};
                $.ajax({
                    type: "POST",
                    url: "../mkstoreticketgoodstemp/resetIsValidByTemp",
                    contentType: "application/json",
                    data: JSON.stringify(tempObj),
                    success: function (r) {
                        if (r.code == 0) {
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            }else{
                //新增页面触发返回按钮时，将临时数据删除
                var tempObj = {guid:vm.tid};
                $.ajax({
                    type: "POST",
                    url: "../mkstoreticketgoodstemp/resetIsValidByTemp",
                    contentType: "application/json",
                    data: JSON.stringify(tempObj),
                    success: function (r) {
                        if (r.code == 0) {
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            }
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        handleSuccessAdvImgUrl: function (res, file) {
            vm.mkStoreTicketDiscount.advImgUrl = file.response.url;
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 100K。'
            });
        },
        eyeImageAdvImgUrl: function () {
            var url = vm.mkStoreTicketDiscount.advImgUrl;
            eyeImage(url);
        },
        handleSuccessStoreLogoUrl: function (res, file) {
            vm.mkStoreTicketDiscount.storeLogoUrl = res.url;
        },
        eyeImageStoreLogoUrl: function () {
            var url = vm.mkStoreTicketDiscount.storeLogoUrl;
            eyeImage(url);
        },
	},
    mounted() {
        $.get("../sys/macro/queryMacrosByValue?value=goodsBizType", function (r) {
            vm.macros = r.list;
        });

    }
});