let cacheData = {
}
$(function () {
    $("#jqGrid").Grid({
        url: '../coupon/list',
        rownumWidth:60,
        loadComplete: function(){
            var re_records = $("#list").getGridParam('records');
            if(re_records == 0 || re_records == null){
            if($(".norecords").html() == null){
            $("#list").parent().append("<div class=\"norecords\">没有符合数据</div>");
            }
            $(".norecords").show();
            }
        },
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
            {label: 'VR场景名称', name: 'brandName', index: 'brandName', width: 120},
            {label: '优惠券名称', name: 'name', index: 'name', width: 120},
            {
                label: '发放类型', name: 'sendType', index: 'send_type', width: 80, formatter: function (value) {
                    if (value == 0) {
                        return '全场赠券';
                    } else if (value == 1) {
                        return '会员赠券';
                    } else if (value == 2) {
                        return '购物赠券';
                    } else if (value == 3) {
                        return '注册赠券';
                    }
                    return '-';
                }
            },
            {label: '优惠券面额（元）', name: 'typeMoney', index: 'type_money', width: 80},
            {label: '最低消费额（元）', name: 'minGoodsAmount', index: 'min_goods_amount', width: 80},
            {
                label: '使用开始时间',
                name: 'useStartDate',
                index: 'use_start_date',
                width: 120,
                formatter: function (value) {
                    return transDate(value);
                }
            },
            {
                label: '使用结束时间', name: 'useEndDate', index: 'use_end_date', width: 120, formatter: function (value) {
                    return transDate(value);
                }
            },
            {label: '发放数量', name: 'number', index: 'number', width: 80},
            {label: '已领取数量', name: 'receiveNumber', index: 'receive_number', width: 80},
            {label: '优惠券状态', name: 'couponStatus', index: 'coupon_status', width: 80,
                formatter: function (value) {
                    if (value == 4) {
                        return '停止发放';
                    } else if (value == 1) {
                        return '未生效';
                    } else if (value == 2) {
                        return '生效中';
                    } else if (value == 3) {
                        return '已失效';
                    }
                    return '-';
            }},
            {
                label: '操作', width: 100,  align:'center', sortable: false, formatter: function (value, col, row) {
                    cacheData[col.rowId] = row
                    let name = ''
                    if (row.couponStatus == 2) {
                        name = '停止'
                    }
                    if (row.couponStatus == 4) {
                        name = '恢复'
                    }
                    let view = '<button class="btn btn-outline btn-info" onclick="vm.lookDetail(' + col.rowId + ');event.cancelBubble=true;"><i></i>&nbsp;查看</button>'
                    let recover = '<button class="btn btn-outline btn-primary" style="margin-left:10px;" onclick="vm.changeStatus(' + col.rowId + ');event.cancelBubble=true;"><i></i>&nbsp;'+name+'</button>'
                    return view + (name&&recover);
                }
            }]
    });
});
var vm = ''

vm = new Vue({
    el: '#rrapp',
    data(){
        const validateBrandIdCheck =function (rule, value, callback)  {
            if (value === '' || !value) {
                callback(new Error('VR场景不能为空'));
            }else {
                callback();
            }
        };

        const validateNameCheck =function (rule, value, callback) {
            if (value === '' || !value ) {
                callback(new Error('优惠券名称不能为空'));
            } 
            else if(value.length>20){
                callback(new Error('优惠券名称不能超过20个字符'));
            }
            else {
                callback();
            }
        };

        const validateDescCheck =function (rule, value, callback) {
            if (value === '' || !value ) {
                callback(new Error('使用说明不能为空'));
            } 
            else if(value.length>200){
                callback(new Error('使用说明不能超过200个字符'));
            }
            else {
                callback();
            }
        };

        const validateNotNullIdCheck =function (rule, value, callback)  {
            if (value === '' || !value) {
                callback(new Error(rule.name+'不能为空'));
            }else {
                callback();
            }
        };
        let user = JSON.parse(localStorage.getItem('userInfo'))

        return {
            userInfo:user,
            showList: true,
            showCard: false,
            showGoods: false,
            title: null,
            coupon: {
                sendType: 0,
                brandId:'',
                brandName:'',
                name:'',
                typeMoney:'',
                minGoodsAmount:'',
                number:'',
                useStartDate:'',
                useEndDate:'',
                useDesc:'',
            },
            ruleValidate: {
                name: [
                    {required: true, validator: validateNameCheck, trigger: 'blur'}
                ],
                brandId: [
                    {required: true, validator: validateBrandIdCheck, trigger: 'change'}
                ],
                typeMoney: [
                    {required: true,name:'面值金额', validator: validateNotNullIdCheck, trigger: 'change'}
                ],
                minGoodsAmount: [
                    {required: true,name:'最小订单金额', validator: validateNotNullIdCheck, trigger: 'change'}
                ],
                number: [
                    {required: true, name: '发放数量',validator: validateNotNullIdCheck,  trigger: 'change'}
                ],
                useStartDate: [
                    {required: true, name: '使用开始时间',validator: validateNotNullIdCheck,  trigger: 'change'}
                ],
                useEndDate: [
                    {required: true, name: '使用结束时间',validator: validateNotNullIdCheck,  trigger: 'change'}
                ],
                useDesc: [
                    {required: true, validator: validateDescCheck,trigger: 'blur'}
                ],
            },
            q: {
                name: '',
                couponStatus: ' ',
                brandName: ''
            },
            goods: [],
            goodss: [],
            brands:[],
            user: [],
            users: [],
            selectData: {},
            sendSms: ''//是否发送短信
        }
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.showCard = true;
            vm.showGoods = false;
            vm.title = "新增";
            vm.coupon = {
                sendType: 0,
                brandId:'',
                brandName:'',
                name:'',
                typeMoney:'',
                minGoodsAmount:'',
                number:'',
                useStartDate:'',
                useEndDate:'',
                useDesc:''
            };
            
            vm.getBrands();
        },
        update: function (event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.showCard = true;
            vm.showGoods = false;
            vm.title = "修改";
            vm.getBrands();
            vm.getInfo(id)
        },
        saveOrUpdate: function (event) {
            if (vm.coupon.minGoodsAmount < vm.coupon.typeMoney) {
                return alert('面值金额 需小于 最小订单金额，才可新增优惠券')
            }
            var url = vm.coupon.id == null ? "../coupon/save" : "../coupon/update";
            vm.brands.forEach(item=>{
                if (item.id == vm.coupon.brandId) {
                    vm.coupon.brandName = item.name
                }
            })

            vm.coupon.updateUserDeptId=vm.userInfo.deptId
            vm.coupon.updateUserId=vm.userInfo.userId
            vm.coupon.createUserId=vm.userInfo.userId
            vm.coupon.createUserDeptId=vm.userInfo.deptId
            Ajax.request({
                type: "POST",
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.coupon),
                successCallback: function () {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../coupon/deleteCoupons",
                    contentType: "application/json",
                    params: JSON.stringify({
                        idList: ids
                    }),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../coupon/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.coupon = r.coupon;
                }
            });
        },
        
        getBrands: function () {
            Ajax.request({
                url: "../brand/queryAll",
                async: true,
                successCallback: function (r) {
                    vm.brands = r.list;
                    r.list.forEach(item=>{
                        if (item.id == vm.coupon.brandId) {
                            vm.coupon.brandName = item.name
                        }
                    })
                }
            });
        },
        reload: function (event) {
            this.getBrands();
            vm.showList = true;
            vm.showCard = false;
            vm.showGoods = false;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'name': vm.q.name,
                    'brandName': vm.q.brandName,
                    'couponStatus': vm.q.couponStatus
                },
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        publish: function (id, sendType) {
            vm.showGoods = true;
            vm.goods = [];
            vm.user = [];
            vm.getGoodss();
            vm.getUsers();
            vm.selectData = {id: id, sendType: sendType};
            vm.sendSms = false;
            openWindow({
                title: "发放",
                area: ['600px', '350px'],
                content: jQuery("#sendDiv")
            })
        },
        getUsers: function () {
            Ajax.request({
                url: "../user/queryAll",
                async: true,
                successCallback: function (r) {
                    vm.users = r.list;
                }
            });
        },
        lookDetail:function (rowId) {
            let id = cacheData[rowId].id
            let brandName = cacheData[rowId].brandName
            let name = cacheData[rowId].name


            if (id == null) {
                return;
            }
            
            openWindow({
                title: '优惠券明细',
                type: 2,
                content: '../shop/coupondetail.html?couponId=' + id + '&brandName=' + brandName +'&name=' + name
            })
            return false
        },
        changeStatus:function (rowId) {
            let row = cacheData[rowId]
            let msg = row.couponStatus == 2?'停止后，优惠券将不再发放，是否继续？':'恢复后，优惠券将允许发放，是否继续？'
            confirm(msg, function () {
                vm.coupon.couponStatus = row.couponStatus == 2?4:2

                Ajax.request({
                    url: '../coupon/updateStatus?status='+(row.couponStatus == 2?4:2)+'&couponId='+row.id,
                    contentType: "application/json",
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            })

        },
        publishSubmit: function () {

            var sendType = vm.selectData.sendType;
            if (sendType == 1 && vm.user.length == 0) {
                vm.$Message.error('请选择下发会员');
                return;
            }
            if (sendType == 3 && vm.goods.length == 0) {
                vm.$Message.error('请选择下发商品');
                return;
            }
            confirm('确定下发优惠券？', function () {
                Ajax.request({
                    type: "POST",
                    dataType: 'json',
                    url: "../coupon/publish",
                    contentType: "application/json",
                    params: JSON.stringify({
                        sendType: vm.selectData.sendType,
                        couponId: vm.selectData.id,
                        goodsIds: vm.goods.toString(),
                        userIds: vm.user.toString(),
                        sendSms: vm.sendSms
                    }),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                            vm.showGoods = false;
                            vm.showList = true;
                        });
                    }
                });
            });
        },
        getGoodss: function () {
            Ajax.request({
                url: "../goods/queryAll/",
                async: true,
                successCallback: function (r) {
                    vm.goodss = r.list;
                }
            });
        }
    },
    mounted:function() {
        this.getBrands()
    }
});

window.vm = vm
