$(function () {
    // $('#promBegTime').datepicker({
    //     format : 'yyyy-mm-dd HH:mm:ss',
    //     language : 'zh-CN',
    //     autoclose : true,
    //     clearBtn : true,
    //     todayHighlight : true,
    //     endDate : new Date()
    // });
    $("#jqGrid").jqGrid({
        url: '../mkstoreprom/list',
        datatype: "json",
        colModel: [
            {label: '活动状态', name: 'isFinished', index: 'is_finished', width: 40, align: 'center',
                formatter: function (value) {
                    if (value == '0') {
                        return '<span style="font-weight: bolder;background: #B2AEBC;color: white;">已结束</span>';
                    } else if (value == '1') {
                        return '<span style="font-weight: bolder;background: #58d44d;color: white">进行中</span>';
                    } else if (value == '2') {
                        return '<span style="font-weight: bolder;background: red;color: white">未开始</span>';
                    }
                    return '';
                }},
            {
                label: '活动图片', name: 'promPicUrl', index: 'promPicUrl', width: 40, align: 'center',
                formatter: function (value) {
                    return transImg(value);
                }
            },
			{label: '推广信息', name: 'promInfo', width: 160, align: 'left'},
            {label: '推广ID', name: 'promId', index: 'prom_id', key: true, width: 40, align: 'center'},
            {label: '所属门店', name: 'storeName', index: 'storeName', width: 70, align: 'center'},
			{label: '推广分类', name: 'promType', index: 'prom_type', width: 80, align: 'center',
                formatter: function (value) {
                    if (value == '00') {
                        return '活动链接';
                    } else if (value == '10') {
                        return '商品链接';
                    }
                    return '';
                }},
			{label: '推广渠道', name: 'promChnName', index: 'promChnName', width: 80, align: 'center'},
            {label: '统计', name: 'promStat', index: 'promStat', width: 130, align: 'center'},
            {
                label: '操作', width: 120, align: 'center', sortable: false, formatter: function (value, col, row) {
                let htmlStr = '';
                if (row.isFinished == '0') {//已结束
                    htmlStr = "<button class='btn btn-outline btn-primary' " +
                        "onclick='vm.showInfo(" + row.promId + ")'><i class='fa fa-qrcode'></i>查看</button>&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "<button class='btn btn-outline btn-primary' " +
                        "onclick='vm.delById(" + row.promId + ")'><i class='fa fa-qrcode'></i>删除</button>";
                }
                if (row.isFinished == '1') {//进行中
                    htmlStr = "<button class='btn btn-outline btn-primary' " +
                        "onclick='vm.putOn(" + row.promId + ")'><i class='fa fa-qrcode'></i>投放</button>&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "<button class='btn btn-outline btn-primary' " +
                        "onclick='vm.updateFinished(" + row.promId + ")'><i class='fa fa-qrcode'></i>立即结束</button>&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "<button class='btn btn-outline btn-primary' " +
                        "onclick='vm.updateById(" + row.promId + ")'><i class='fa fa-qrcode'></i>编辑</button>";
                }
                if (row.isFinished == '2') {//未开始
                    htmlStr = "<button class='btn btn-outline btn-primary' " +
                        "onclick='vm.updateStarted(" + row.promId + ")'><i class='fa fa-qrcode'></i>立即开始</button>&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "<button class='btn btn-outline btn-primary' " +
                        "onclick='vm.updateById(" + row.promId + ")'><i class='fa fa-qrcode'></i>编辑</button>";
                }
                return htmlStr;
            }}
            // {label: '推广商品', name: 'goodsName', index: 'goodsName', width: 80, align: 'center'},
            // {label: '活动分类', name: 'promTypeId', index: 'prom_type_id', width: 80},
            // {label: '活动ID', name: 'storeTopicId', index: 'store_topic_id', width: 80},
            // {label: '推广url', name: 'promUrl', index: 'prom_url', width: 80},
            // {label: '是否投放', name: 'isPut', index: 'is_put', width: 80, align: 'center',
            //    formatter: function (value) {
            //        if (value == '0') {
            //            return '是';
            //        } else if (value == '1') {
            //            return '否';
            //        }
            //        return '';
            //    }},

            // {label: '浏览量', name: 'browseNum', index: 'browseNum', width: 80, align: 'center'},
            // {label: '支付单数', name: 'payOrderNum', index: 'payOrderNum', width: 80, align: 'center'},
            // {label: '应收金额', name: 'receivMoney', index: 'receivMoney', width: 80, align: 'center'},
			// {label: '是否有效', name: 'isValid', index: 'is_valid', width: 80,
             //    formatter: function (value) {
             //        if (value == '0') {
             //            return '有效';
             //        } else if (value == '1') {
             //            return '无效';
             //        }
             //        return '';
             //    }},
            // {label: '备注', name: 'note', index: 'note', width: 80},
            // {label: '创建人编号', name: 'createrSn', index: 'creater_sn', width: 80},
            // {label: '创建时间', name: 'createTime', index: 'create_time', width: 80,
            //     formatter: function (value) {
            //         return transDate(value, 'yyyy-MM-dd hh:mm:ss');
            //     }},
            // {label: '修改人编号', name: 'moderSn', index: 'moder_sn', width: 80},
            // {label: '修改时间', name: 'modTime', index: 'mod_time', width: 80,
            //     formatter: function (value) {
            //         return transDate(value, 'yyyy-MM-dd hh:mm:ss');
            //     }}
            ],
		viewrecords: true,
        height: 580,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: false,
        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"});
        }
    });
});

let vm = new Vue({
	el: '#rrapp',
	data: {
        showList: true,
        title: null,
		mkStoreProm: {},
		ruleValidate: {
			name: [
				{required: true, message: '名称不能为空', trigger: 'blur'}
			]
		},
        chnlRuleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]
        },
		q: {
            promName: '',
            promType: '',
            isFinished:'',
            storeId:'',
            goodsId:''
		},
        thirdMerchantBizList: [],
        goodsList: [],
        storeList: [],
        isPomTypeBy00: false,
        isPomTypeBy10: false,
        storeTopicList: [],
        promChnlList: [],
        mkStorePromChnl: {isValid:0},
        showChnlList: true,
        storeId: "",
        isOperatorShow: false,
        showViewList: false,
        showInfoList: true,
        queryGoodsList:[],
        queryStoreList:[]
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function () {
			vm.showList = false;
            vm.showViewList = true;
            vm.showInfoList = true;
            vm.showChnlList = true;
			vm.title = "新增";
            vm.thirdMerchantBizList = [];
            vm.storeList = [];
            vm.goodsList = [];
			vm.mkStoreProm = {isPut:1};
            vm.isOperatorShow = false;
			vm.getThirdMerchantBizList();
		},
		update: function (event) {
            let promId = getSelectedRow();
			if (promId == null) {
				return;
			}
            vm.showList = false;
            vm.showViewList = true;
            vm.showInfoList = true;
            vm.showChnlList = true;
            vm.title = "修改";
            vm.isOperatorShow = true;
            vm.getThirdMerchantBizList();

            vm.getInfo(promId)
		},
		saveOrUpdate: function (event) {
            let url = vm.mkStoreProm.promId == null ? "../mkstoreprom/save" : "../mkstoreprom/update";
			$.ajax({
				type: "POST",
			    url: url,
			    contentType: "application/json",
			    data: JSON.stringify(vm.mkStoreProm),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
			});
		},
        del: function (event) {
            let promIds = getSelectedRows();
            if (promIds == null){
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: "../mkstoreprom/delete",
                    contentType: "application/json",
                    data: JSON.stringify(promIds),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        addPromChnl:function () {
            if(vm.mkStoreProm.storeId){
                vm.showList = true;
                vm.showViewList = true;
                vm.showInfoList = true;
                vm.showChnlList = false;
                vm.title = "新增推广渠道";
                vm.mkStorePromChnl = {isValid:0};
                vm.getThirdMerchantBizList();
            }else {
                alert("请先选择所属第三方商户和门店，再进行操作新增推广渠道");
            }
        },
        updateById: function (promId) {
            if (promId == null) {
                return;
            }
            vm.showList = false;
            vm.showViewList = true;
            vm.showChnlList = true;
            vm.showInfoList = true;
            vm.title = "修改";
            vm.isOperatorShow = true;
            vm.getThirdMerchantBizList();

            vm.getInfo(promId)
        },
        putOn: function (promId) {
            if (promId == null) {
                return;
            }
            $("#qrcodeCanvas").html("");
            $.get("../mkstoreprom/qrcodeCanvas/" + promId, 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();
        },
        delById: function (promId) {
            if (promId == null){
                return;
            }
            var promIds = [promId];
            confirm('确定要删除该推广？删除后将不能恢复', function () {
                $.ajax({
                    type: "POST",
                    url: "../mkstoreprom/delete",
                    contentType: "application/json",
                    data: JSON.stringify(promIds),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        updateFinished: function (promId) {
            if (promId == null){
                return;
            }

            confirm('结束进行中的活动会影响用户正常购买，建议您提前告知或说明，确定要结束活动吗？', function () {
                $.ajax({
                    type: "POST",
                    url: "../mkstoreprom/updateFinished",
                    contentType: "application/json",
                    data: JSON.stringify(promId),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        updateStarted: function (promId) {
            if (promId == null){
                return;
            }

            confirm('开始后，活动立即生效，确定要开始活动吗？', function () {
                $.ajax({
                    type: "POST",
                    url: "../mkstoreprom/updateStarted",
                    contentType: "application/json",
                    data: JSON.stringify(promId),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        showInfo: function(promId){
		    if(promId == null){
		        return;
            }
            vm.title = "查看推广渠道信息"
            vm.showList = true;
            vm.showViewList = true;
            vm.showChnlList = true;
            vm.showInfoList = false;
            vm.getInfo(promId);
        },
		getInfo: function(promId){
			$.get("../mkstoreprom/info/"+promId, function (r) {
                vm.mkStoreProm = r.mkStoreProm;
            });
		},
        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;
                vm.getGoodsList(storeId);
                vm.getStoreTopicList(storeId);
                vm.getPromChnlList(storeId);
            }
        },
        getGoodsList: function(storeId){
            if(storeId){
                $.get("../productstorerela/queryAll?storeId=" + storeId, function (r) {
                    vm.goodsList = r.list;
                });
            }
        },
        getStoreTopicList: function(storeId){
            if(storeId){
                $.get("../storetopic/queryAll?storeId=" + storeId, function (r) {
                    vm.storeTopicList = r.list;
                });
            }
        },
        getPromChnlList: function(storeId){
            if(storeId){
                $.get("../mkstorepromchnl/queryAll?storeId=" + storeId, function (r) {
                    vm.promChnlList = r.list;
                });
            }
        },
        changeProm: function (opt) {
            var pomType = opt.value;
            if(pomType){
                if(pomType == '00'){//活动
                    vm.isPomTypeBy00 = true;
                    vm.isPomTypeBy10 = false;
                }else{//商品
                    vm.isPomTypeBy10 = true;
                    vm.isPomTypeBy00 = false;
                }
            }
        },
        queryChangeGoodsByStore: function (storeId) {
            if(storeId){
                $.get("../productstorerela/queryAll?storeId=" + storeId, function (r) {
                    vm.queryGoodsList = r.list;
                });
            }
        },
        reloadSearch: function() {
            vm.q = {
                promName: '',
                promType: '',
                isFinished:'',
                storeId:'',
                goodsId:''
            }
            vm.reload();
		},
		reload: function (event) {
            vm.showList = true;
            vm.showViewList = false;
            vm.showChnlList = true;
            vm.showInfoList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
			$("#jqGrid").jqGrid('setGridParam', {
                postData: {'promName': vm.q.promName,'promType': vm.q.promType,'isFinished':vm.q.isFinished,
                    'storeId':vm.q.storeId,
                    'goodsId':vm.q.goodsId},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
		},
        reloadChnl: function (event) {
            vm.showList = false;
            vm.showViewList = true;
            vm.showChnlList = true;
            vm.showInfoList = true;
            $.get("../mkstorepromchnl/queryAll?storeId=" + vm.storeId, function (r) {
                vm.promChnlList = r.list;
            });
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        chnlHandleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveChnlOrUpdate()
            });
        },
        saveChnlOrUpdate: function (event) {
            let url = "../mkstorepromchnl/save";
            vm.mkStorePromChnl.storeId = vm.mkStoreProm.storeId;
            $.ajax({
                type: "POST",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(vm.mkStorePromChnl),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.showList = false;
                            vm.showViewList = true;
                            vm.showChnlList = true;
                            vm.showInfoList = true;
                            $.get("../mkstorepromchnl/queryAll?storeId=" + vm.storeId, function (r) {
                                vm.promChnlList = r.list;
                            });
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        }
	},
    mounted() {
        $.get("../store/queryAll", function (r) {
            vm.queryStoreList = r.list;
        });
    }
});