let cacheData = {
}
let broadcastMap = {
    101: '直播中',
    102: '未开始',
    103: '已结束',
    104: '禁播',
    105: '暂停',
    106: '异常',
    107: '已过期'
}
$(function () {
    var types = {
     0:'服饰',
     1:'家居',
     2:'数码',
     3:'美妆',
     4:'其他',
    }
     
     $("#jqGrid").Grid({
         url: '../liveRoom/getRoomList',
         rownumWidth:60,
         colModel: [{
             label: 'id', name: 'id', index: 'liveId', key: true, hidden: true
         }, 
         {
            label: 'liveId', name: 'liveId', index: 'liveId', hidden: true
        }, 
         {
             label: '最近开播', name: 'startTime', index: 'startTime', width: 80,formatter: function (value, col, row) {
                cacheData[col.rowId] = row
                return transDate(parseInt(value)*1000);
            }
         },
         {
            label: '直播名称', name: 'name', index: 'name', width: 80
        },
         {
            label: '直播分享图',align:'center', name: 'shareImgOss', index: 'shareImgOss', width: 120, formatter: function (value) {
                return transImg(value,100,'auto');
            }
        },
        {
            label: '房间号', name: 'roomId', index: 'roomId', width: 80
        },
        {
            label: '主播', name: 'anchorName', index: 'anchorName', width: 80
        },
        {
            label: '直播状态', name: 'liveStatus', index: 'liveStatus', width: 80, formatter (value) {
                return broadcastMap[value] || value
            }
        }
     ]
     });
  });

  const validateBrandIdCheck =function (rule, value, callback)  {
    if (value === '' || !value) {
        callback(new Error('VR场景不能为空'));
    }else {
        callback();
    }
};
  
  
  const validateSceneUrlCheck = function (rule, value, callback){
     var link1 ='https://test.4dkankan.com/eShopMobile.html?m='
     var link2 ='https://www.4dkankan.com/eShopMobile.html?m='
  
     if (value === ''||!value) {
         callback(new Error('场景地址不能为空'));
     } else if(!~value.indexOf(link1)&&!~value.indexOf(link2)){
         callback(new Error('场景地址需为'+link2+'或'+link1));
     } else {
         callback();
     }
  };

  const validateNotNullIdCheck =function (rule, value, callback)  {
    if (value === '' || !value) {
        callback(new Error(rule.name+'不能为空'));
    }else {
        callback();
    }
    }

    const validatezishu =function (rule, value, callback)  {
        
        let size = rule.size?parseInt(rule.size):50

        if (value === '' || !value) {
            callback(new Error(rule.name+'不能为空'));
        }
        else if(value.length>size){
            callback(new Error(rule.name+'不能超过'+rule.size+'个字符'));
        }else {
            callback();
        }
    };
  
  let user = JSON.parse(localStorage.getItem('userInfo'))

  var vm = new Vue({
     el: '#rrapp',
     data: {
        tmpUrl:'',
        loading:false,
        userInfo:user,
        showList: true,
         title: null,
         broadcast: {name: '',brandId:'',brandName:'',coverImg:'',startTime:'',endTime:'',anchorName:'',anchorWechat:'', shareImg: '',feedsImg: '',screenType:0,isFeedsPublic: 0,type: 0,closeLike:1, closeGoods: 1,closeKf:0, closeComment: 1,closeReplay: 0,closeShare: 1},
         func:['closeComment','closeGoods'],
         ruleValidate: {
            brandId: [
                {required: true, validator: validateBrandIdCheck, trigger: 'change'}
            ],
            name: [
                {required: true, name: '直播间标题', size:17,validator: validatezishu, trigger: 'blur'}
            ],
            startTime: [
                {required: true, name: '直播开始时间',validator: validateNotNullIdCheck,  trigger: 'change'},
                {required: true, name: '直播开始时间只能在十分钟后',validator: validateNotNullIdCheck,  trigger: 'change'},
            ],
            endTime: [
                {required: true, name: '直播结束时间',validator: validateNotNullIdCheck,  trigger: 'change'}
            ],
            anchorName: [
                {required: true, name: '主播名称', size:15,validator: validatezishu, trigger: 'blur'}
            ],
            anchorWechat: [
                {required: true,name: '主播微信账号', size:15,validator: validatezishu,  trigger: 'blur'}
            ],
            shareImg: [
                {required: true, message: '分享卡片封面不能为空', trigger: 'blur'}
            ],
            coverImg: [
                {required: true, message: '直播卡片封面不能为空', trigger: 'blur'}
            ],
            feedsImg: [
                {required: true, message: '直播间背景墙不能为空', trigger: 'blur'}
            ]
         },
         q: {
             name: ''
         },
         coverImg:'',
         shareImg:'',
         feedsImg:'',
         startTime:'',
         endTime:'',
         valiImg: '',
         brands:[]
     },
     methods: {
        handleRemove (file) {
            
        },
        getBrands: function () {
            Ajax.request({
                url: "../brand/queryAll",
                async: true,
                successCallback: function (r) {
                    vm.brands = r.list;
                    r.list.forEach(item=>{
                        if (item.id == vm.broadcast.brandId) {
                            vm.broadcast.brandName = item.name
                        }
                    })
                }
            });
        },
         query: function () {
             vm.reload();
         },
         add: function () {
             vm.showList = false;
             vm.title = "新增";
             vm.broadcast =   {name: '',brandId:'',brandName:'',coverImg:'',startTime:'',endTime:'',anchorName:'',anchorWechat:'', shareImg: '',feedsImg: '',screenType:0,isFeedsPublic: 0,type: 0,closeLike:1, closeGoods: 1,closeKf:0, closeComment: 1,closeReplay: 0,closeShare: 1}
         },
         share: function (event) {
             eyeImage('https://res.wx.qq.com/op_res/BbVNeczA1XudfjVqCVoKgfuWe7e3aUhokktRVOqf_F0IqS6kYR--atCpVNUUC3zr');
         },
         saveOrUpdate: function (event) {
             var url = vm.broadcast.slideId == null ? "../liveRoom/add" : "../liveRoom/update";
             // 判断时间
             if ((new Date().getTime() + 60000 * 10) >= vm.startTime * 1000) {
                 alert('开播时间需要在当前时间的10分钟后，并且不能在6 个月后')
                 return
             }
             if ((vm.endTime * 1000 - vm.startTime * 1000 < 30 * 60000) || (vm.endTime * 1000 - vm.startTime * 1000 >= 86400000)) {
                 alert('开播时间和结束时间间隔不得短于30分钟，不得超过24小时')
                 return
             }
             let params = Object.assign({}, vm.broadcast,{
                startTime:vm.startTime,
                endTime:vm.endTime
             })

             vm.brands.forEach(item=>{
                if (item.id == vm.broadcast.brandId) {
                    params.brandName = item.name
                }
            })

             params.updateUserDeptId=vm.userInfo.deptId
             params.updateUserId=vm.userInfo.userId
             params.createUserId=vm.userInfo.userId
             params.createUserDeptId=vm.userInfo.deptId
             Ajax.request({
                 type: "POST",
                 url: url,
                 contentType: "application/json",
                 params: JSON.stringify(params),
                 successCallback: function (r) {
                     if (r.errcode === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        })
                        return
                     }
                     const errcode = {
                        300002: '主播名称长度非法',
                        300001: '禁止创建/更新商品',
                        300002: '名称长度不符合规则',
                        300006: '图片上传失败',
                        300022: '此房间号不存在',
                        300023: '当前房间状态不允许此操作',
                        300028: '房间名称违规',
                        300029: '主播昵称违规',
                        300030: '主播微信号不合法',
                        300031: '直播间封面图不合规',
                        300032: '直播间分享图违规',
                        300034: '主播微信昵称长度不符合要求',
                        300035: '主播微信号不存在',
                        300036: '主播微信号未实名认证,请扫码进行验证',
                        300037: '购物直播频道封面图不合规',
                        300038: '未在小程序管理后台配置客服',
                        300039: '主播副号微信号不合法',
                        300040: '名称含有非限定字符（含有特殊字符）'
                     }
                     alert(errcode[r.errcode] || '添加失败')
                     if (r.errcode === 300036) {
                        vm.valiImg = r.qrcode_url
                     }
                 }
             });
         },
         handleChangeStart(val){
             let date = new Date(val)
             this.startTime = parseInt(date.getTime()/1000)
         },
         handleChangeEnd(val){
            let date = new Date(val)
            this.endTime = parseInt(date.getTime()/1000)
         },
         del: function (event) {
             
            let rowId = getSelectedRow("#jqGrid");
            if (rowId == null) {
                return;
            }
            var data = cacheData[rowId]
            
             confirm('确定要删除选中的记录？', function () {
  
                 Ajax.request({
                     type: "POST",
                     url: "..//liveRoom/update",
                     contentType: "application/json",
                     params: JSON.stringify(Object.assign(data,{
                        enable:0
                     })),
                     successCallback: function () {
                         alert('操作成功', function (index) {
                             vm.reload();
                         });
                     }
                 });
             });
         },
         getInfo: function (id) {
            vm.defaultList = []
             Ajax.request({
                 url: "../slideShow/getById?slideId=" + id,
                 async: true,
                 successCallback: function (r) {
                     vm.carousel = r.page;
                 }
             });
         },
         reload: function (event) {
             vm.showList = true;
             var page = $("#jqGrid").jqGrid('getGridParam', 'page');
             $("#jqGrid").jqGrid('setGridParam', {
                 postData: {'name': vm.q.name},
                 page: page
             }).trigger("reloadGrid");
             vm.handleReset('formValidate');
         },
         handleSuccessListPicUrl: function (res, file) {
             vm.brand.listPicUrl = file.response.url;
             vm.brand.appListPicUrl = file.response.url;
         },
         handleSuccessPicUrl: function (res, file) {
             vm.brand.picUrl = file.response.url;
         },
         handleSuccessAppListPicUrl: function (res, file) {
             vm.brand.appListPicUrl = file.response.url;
         },
         beforecoverImgUpload: function (file) {
            this.loading = true
            this.tmpUrl = URL.createObjectURL(file)
         },
         beforeShareImgUpload: function (file) {
            this.loading = true
            this.tmpUrl = URL.createObjectURL(file)
         },
         beforefeedsImgUpload: function (file) {
            this.loading = true
            this.tmpUrl = URL.createObjectURL(file)
         },

         
        handleSuccessShareImg: function (res, file) {
            this.loading = false
            this.shareImg = this.tmpUrl
            this.broadcast.shareImg = file.response.mediaId;
            this.broadcast.shareImgOss = file.response.ossUrl + window.fixImg + 'm_fixed,w_800,h_640';
            // this.broadcast.shareImgOss = file.response.ossUrl;

        },

        handleSuccesscoverImg: function (res, file) {
            this.loading = false
            this.coverImg = this.tmpUrl
            this.broadcast.coverImg = file.response.mediaId;
            this.broadcast.coverImgOss = file.response.ossUrl + window.fixImg + 'm_fixed,w_800,h_800';
            // this.broadcast.coverImgOss = file.response.ossUrl;
        },

        handleSuccessfeedsImg: function (res, file) {
            this.loading = false
            this.feedsImg = this.tmpUrl
            this.broadcast.feedsImg = file.response.mediaId;
            // this.broadcast.feedsImgOss = file.response.ossUrl
            this.broadcast.feedsImgOss = file.response.ossUrl + window.fixImg + 'm_fixed,w_1080,h_1920';

        },
      
        handleBefore(){
            this.loading = true
        },
         handleSuccessNewPicUrl: function (res, file) {
             vm.brand.newPicUrl = file.response.url;
         },
         handleFormatError: function (file) {
            this.loading = false
             this.$Notice.warning({
                 title: '文件格式不正确',
                 desc: '文件 ' + file.name + ' 格式不正确。'
             });
         },
         handleMaxSize: function (file) {
            this.loading = false
             this.$Notice.warning({
                 title: '超出文件大小限制',
                 desc: '文件 ' + file.name + ' 太大。'
             });
         },
         eyeImageListPicUrl: function () {
             var url = vm.brand.listPicUrl;
             eyeImage(url);
         },
         eyeImagePicUrl: function () {
             var url = vm.brand.picUrl;
             eyeImage(url);
         },
         eyeImageAppListPicUrl: function () {
             var url = vm.brand.appListPicUrl;
             eyeImage(url);
         },
         eyeImageNewPicUrl: function () {
             var url = vm.brand.newPicUrl;
             eyeImage(url);
         },
         handleSubmit: function (name) {
             handleSubmitValidate(this, name, function () {
                 vm.saveOrUpdate()
             });
         },
         handleReset: function (name) {
             handleResetForm(this, name);
         }
     },
    mounted () {
        this.getBrands()
    }
  });