/**

 @Name: 用户模块

 */
 
layui.define(['laypage', 'fly', 'element', 'flow','table','form'], function(exports){

  var $ = layui.jquery;
  var layer = layui.layer;
  var util = layui.util;
  var laytpl = layui.laytpl;
  var form = layui.form;
  var laypage = layui.laypage;
  var fly = layui.fly;
  var flow = layui.flow;
  var element = layui.element;
  var upload = layui.upload;
  var table = layui.table;
  var ids = [];
  
  var gather = {}, dom = {
    mine: $('#LAY_mine')
    ,mineview: $('.mine-view')
    ,minemsg: $('#LAY_minemsg')
    ,infobtn: $('#LAY_btninfo')
  };

  //我的相关数据
  var elemUC = $('#LAY_uc'), elemUCM = $('#LAY_ucm');
  gather.minelog = {};
  gather.mine = function(index, type, url){
    var tpl = [
      //求解
      '{{# for(var i = 0; i < d.rows.length; i++){ }}\
      <li>\
        {{# if(d.rows[i].collection_time){ }}\
          <a class="jie-title" href="/jie/{{d.rows[i].id}}/" target="_blank">{{= d.rows[i].title}}</a>\
          <i>{{ d.rows[i].collection_time }} 收藏</i>\
        {{# } else { }}\
          {{# if(d.rows[i].status == 1){ }}\
          <span class="fly-jing layui-hide-xs">精</span>\
          {{# } }}\
          {{# if(d.rows[i].accept >= 0){ }}\
            <span class="jie-status jie-status-ok">已结</span>\
          {{# } else { }}\
            <span class="jie-status">未结</span>\
          {{# } }}\
          {{# if(d.rows[i].status == -1){ }}\
            <span class="jie-status">审核中</span>\
          {{# } }}\
          <a class="jie-title" href="/jie/{{d.rows[i].id}}/" target="_blank">{{= d.rows[i].title}}</a>\
          <i class="layui-hide-xs">{{ layui.util.timeAgo(d.rows[i].time, 1) }}</i>\
          {{# if(d.rows[i].accept == -1){ }}\
          <a class="mine-edit layui-hide-xs" href="/jie/edit/{{d.rows[i].id}}" target="_blank">编辑</a>\
          {{# } }}\
          <em class="layui-hide-xs">{{d.rows[i].hits}}阅/{{d.rows[i].comment}}答</em>\
        {{# } }}\
      </li>\
      {{# } }}'
    ];

    var view = function(res){
      var html = laytpl(tpl[0]).render(res);
      dom.mine.children().eq(index).find('span').html(res.count);
      elemUCM.children().eq(index).find('ul').html(res.rows.length === 0 ? '<div class="fly-msg">没有相关数据</div>' : html);
    };

    var page = function(now){
      var curr = now || 1;
      if(gather.minelog[type + '-page-' + curr]){
        view(gather.minelog[type + '-page-' + curr]);
      } else {
        //我收藏的帖
        if(type === 'collection'){
          var nums = 10; //每页出现的数据量
          fly.json(url, {}, function(res){
            res.count = res.rows.length;

            var rows = layui.sort(res.rows, 'collection_timestamp', 'desc')
            ,render = function(curr){
              var data = []
              ,start = curr*nums - nums
              ,last = start + nums - 1;

              if(last >= rows.length){
                last = curr > 1 ? start + (rows.length - start - 1) : rows.length - 1;
              }

              for(var i = start; i <= last; i++){
                data.push(rows[i]);
              }

              res.rows = data;
              
              view(res);
            };

            render(curr)
            gather.minelog['collect-page-' + curr] = res;

            now || laypage.render({
              elem: 'LAY_page1'
              ,count: rows.length
              ,curr: curr
              ,jump: function(e, first){
                if(!first){
                  render(e.curr);
                }
              }
            });
          });
        } else {
          fly.json('/api/'+ type +'/', {
            page: curr
          }, function(res){
            view(res);
            gather.minelog['mine-jie-page-' + curr] = res;
            now || laypage.render({
              elem: 'LAY_page'
              ,count: res.count
              ,curr: curr
              ,jump: function(e, first){
                if(!first){
                  page(e.curr);
                }
              }
            });
          });
        }
      }
    };

    if(!gather.minelog[type]){
      page();
    }
  };

  if(elemUC[0]){
    layui.each(dom.mine.children(), function(index, item){
      var othis = $(item)
      gather.mine(index, othis.data('type'), othis.data('url'));
    });
  }

  //显示当前tab
  if(location.hash){
    element.tabChange('user', location.hash.replace(/^#/, ''));
  }

  element.on('tab(user)', function(){
    var othis = $(this), layid = othis.attr('lay-id');
    if(layid){
      location.hash = layid;
    }
  });

  //根据ip获取城市
  if($('#L_city').val() === ''){
    $.getScript('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js', function(){
      $('#L_city').val(remote_ip_info.city||'');
    });
  }

  //上传图片
  if($('.upload-img')[0]){
    layui.use('upload', function(upload){
      var avatarAdd = $('.avatar-add');

      upload.render({
        elem: '.upload-img'
        ,url: '?User_Upload'
        ,size: 200
        ,before: function(){
          avatarAdd.find('.loading').show();
        }
        ,done: function(res){
          if(res.status == 0){
            $.post('?User_Settings', {
              avatar: res.url
            }, function(res){
              location.reload();
            });
          } else {
            layer.msg(res.msg, {icon: 5});
          }
          avatarAdd.find('.loading').hide();
        }
        ,error: function(){
          avatarAdd.find('.loading').hide();
        }
      });
    });
  }

  //合作平台
  if($('#LAY_coop')[0]){

    //资源上传
    $('#LAY_coop .uploadRes').each(function(index, item){
      var othis = $(this);
      upload.render({
        elem: item
        ,url: '/api/upload/cooperation/?filename='+ othis.data('filename')
        ,accept: 'file'
        ,exts: 'zip'
        ,size: 30*1024
        ,before: function(){
          layer.msg('正在上传', {
            icon: 16
            ,time: -1
            ,shade: 0.7
          });
        }
        ,done: function(res){
          if(res.code == 0){
            layer.msg(res.msg, {icon: 6})
          } else {
            layer.msg(res.msg)
          }
        }
      });
    });

    //成效展示
    var effectTpl = ['{{# layui.each(d.data, function(index, item){ }}'
    ,'<tr>'
      ,'<td><a href="?u_{{ item.uid }}" target="_blank" style="color: #01AAED;">{{ item.uid }}</a></td>'
      ,'<td>{{ item.authProduct }}</td>'
      ,'<td>￥{{ item.rmb }}</td>'
      ,'<td>{{ item.create_time }}</td>'
      ,'</tr>'
    ,'{{# }); }}'].join('');

    var effectView = function(res){
      var html = laytpl(effectTpl).render(res);
      $('#LAY_coop_effect').html(html);
      $('#LAY_effect_count').html('你共有 <strong style="color: #FF5722;">'+ (res.count||0) +'</strong> 笔合作授权订单');
    };

    var effectShow = function(page){
      fly.json('/cooperation/effect', {
        page: page||1
      }, function(res){
        effectView(res);
        laypage.render({
          elem: 'LAY_effect_page'
          ,count: res.count
          ,curr: page
          ,jump: function(e, first){
            if(!first){
              effectShow(e.curr);
            }
          }
        });
      });
    };

    effectShow();

  }

  //提交成功后刷新
  fly.form['set-mine'] = function(data, required){
    layer.msg('修改成功', {
      icon: 1
      ,time: 1000
      ,shade: 0.1
    }, function(){
      location.reload();
    });
  }

  //帐号绑定
  $('.acc-unbind').on('click', function(){
    var othis = $(this), type = othis.attr('type');
    layer.confirm('确定要解绑'+ ({
      qq_id: 'QQ'
      ,weibo_id: '微博'
    })[type] + '吗？', {icon: 5}, function(){
      fly.json('?User_Unbind', {
        type: type
      }, function(res){
        if(res.status === 0){
          layer.alert('已成功解绑。', {
            icon: 1
            ,end: function(){
              location.reload();
            }
          });
        } else {
          layer.msg(res.msg);
        }
      });
    });
  });
  
  //我的消息
  gather.minemsg = function(){
    var delAll = $('#LAY_delallmsg')
    ,tpl = '{{# var len = d.rows.length;\
    if(len === 0){ }}\
      <div class="fly-none">您暂时没有最新消息</div>\
    {{# } else { }}\
      <ul class="mine-msg">\
      {{# for(var i = 0; i < len; i++){ }}\
        <li data-id="{{d.rows[i].id}}">\
          <blockquote class="layui-elem-quote">{{ d.rows[i].content}}</blockquote>\
          <p><span>{{d.rows[i].time}}</span><a href="javascript:;" class="layui-btn layui-btn-sm layui-btn-danger fly-delete">删除</a></p>\
        </li>\
      {{# } }}\
      </ul>\
    {{# } }}'
    ,delEnd = function(clear){
      if(clear || dom.minemsg.find('.mine-msg li').length === 0){
        dom.minemsg.html('<div class="fly-none">您暂时没有最新消息</div>');
      }
    }
    
    
    /*
    fly.json('/message/find/', {}, function(res){
      var html = laytpl(tpl).render(res);
      dom.minemsg.html(html);
      if(res.rows.length > 0){
        delAll.removeClass('layui-hide');
      }
    });
    */
    
    //阅读后删除
    dom.minemsg.on('click', '.mine-msg li .fly-delete', function(){
      var othis = $(this).parents('li'), id = othis.data('id');
      fly.json('?user_removeMessage', {
        id: id
      }, function(res){
        if(res.status === 0){
          othis.remove();
          delEnd();
        }
      });
    });

    //删除全部
    $('#LAY_delallmsg').on('click', function(){
      var othis = $(this);
      layer.confirm('确定清空吗？', function(index){
        fly.json('?user_removeMessage', {
          all: true
        }, function(res){
          if(res.status === 0){
            layer.close(index);
            othis.addClass('layui-hide');
            delEnd(true);
          }
        });
      });
    });
  };
  
	$('#chatBtn').on('click', function(){
		var othis = $(this);
		if(layui.cache.user.uid == '-1') {
			layer.alert('请先登陆！', {icon: 7});			
		} else{
			layer.prompt({
				title:'发送小纸条'
			},function(val, index){
				fly.json('?user_SendMessage', {
				  FromUser: layui.cache.user.uid,
				  ToUser: othis.data("touser"),
				  Message:val
				}, function(res){					
				  if(res.status === 0){
					layer.alert('发送成功', {icon: 6});
					layer.close(index);
				  }
				});
				//layer.msg('得到了'+val);
				//layer.close(index);
			});			
		}
		
	});
	
	
	$('#ThreadStatus').on('click', function(){
		var othis = $(this);
		if(layui.cache.user.uid == '-1') {
			layer.alert('请先登陆！', {icon: 7});			
		} else{
			setStatusField( othis );
		}
	});
	
	$('#ReplyStatus').on('click', function(){
		var othis = $(this);
		if(layui.cache.user.uid == '-1') {
			layer.alert('请先登陆！', {icon: 7});			
		} else{
			setStatusField( othis );
		}
	});
	
	$('#UserStatus').on('click', function(){
		var othis = $(this);
		if(layui.cache.user.uid == '-1') {
			layer.alert('请先登陆！', {icon: 7});			
		} else{
			setStatusField( othis );
		}
	});
	
	$('#SelfStatus').on('click', function(){
		var othis = $(this);
		if(layui.cache.user.uid == '-1') {
			layer.alert('请先登陆！', {icon: 7});			
		} else{
			layer.confirm('确认要' + othis.html() + '？', function(){
				fly.json('?User_setStatusField', {
				  'id': othis.data("touser")
				  ,'FieldValue': othis.data("type")
				  ,'StatusField' : "UserStatus"
				}, function(res){					
				  if(res.status === 0){
					layer.msg("注销成功！");
					 location.href = '/';
				  }
				});	
			});
		}
	});
	
	function setStatusField( othis ) {
		fly.json('?Manage_setStatusField', {
		  'id': othis.data("touser")
		  ,'FieldValue': othis.data("type")
		  ,'StatusField' : othis.attr("id")
		}, function(res){					
		  if(res.status === 0){
			if ( othis.data("type") == '0' ) {
				othis.removeClass("layui-btn-danger") ;
				othis.data("type",'1') ;
				othis.html( '禁' + othis.html().slice(1) );
			} else {
				othis.addClass("layui-btn-danger") ;
				othis.data("type",'0') ;
				othis.html( '允' + othis.html().slice(1) );
			}
			layer.msg("设置成功");
		  }
		});	
	}
	
	function setStatusField( othis ) {
		fly.json('?Manage_setStatusField', {
		  'id': othis.data("touser")
		  ,'FieldValue': othis.data("type")
		  ,'StatusField' : othis.attr("id")
		}, function(res){					
		  if(res.status === 0){
			if ( othis.data("type") == '0' ) {
				othis.removeClass("layui-btn-danger") ;
				othis.data("type",'1') ;
				othis.html( '禁' + othis.html().slice(1) );
			} else {
				othis.addClass("layui-btn-danger") ;
				othis.data("type",'0') ;
				othis.html( '允' + othis.html().slice(1) );
			}
			layer.msg("设置成功");
		  }
		});	
	}
	
  dom.minemsg[0] && gather.minemsg();
  
  table.render({
    elem: '#userList'
	,url:'?c=user&a=search'
	,method: 'post'
	,id: 'userList'
	,cols: [[
      {type:'checkbox', fixed: 'left'}
      ,{field:'UserID', width:80, sort: true, fixed: true,title: 'ID'}
      ,{
		  field: "LoginName"
		, width:130
		, title: '用户名'
		, templet: function( d ){
			return(
				"<img src='" + d.Avatar + "'>" + d.LoginName
			);
		}
		}
      ,{field:'Nickname', width:130, title:'昵称'}
      ,{field:'GroupName', width:120, sort: true, title:'用户分组'}
      ,{field:'LastLoginTime', width:160, sort: true, title:'最近登陆时间'}
      ,{field:'Experience', width:80, sort: true, title: ASPBBS.ExperienceName }
      ,{fixed: 'right', width:80, align:'center', toolbar: '#barDemo'}
    ]]
	,page: true
	,width: 892
	,height:475
  });

  //监听工具条
  table.on('tool(userList)', function(obj){
    var data = obj.data;
    if(obj.event === 'detail'){	
		layer.open({
		  type: 2,
		  title: data.LoginName + ' 的个人主页',
		  shadeClose: true,
		  shade: 0.8,
		  area: ['600px', '400px'],
		  content: '?v_' + data.UserID
		}); 	
    } else if(obj.event === 'del'){
      layer.confirm('真的删除行么', function(index){
        obj.del();
        layer.close(index);
      });
    } else if(obj.event === 'edit'){
      layer.alert('编辑行：<br>'+ JSON.stringify(data))
    }
  });
  
  var active = {
    IncExperience: function(){ //获取选中数据，送积分
		layer.prompt({
			title:'赠送' + ASPBBS.ExperienceName
		},function(val, index){
			layer.close(index);
			SetField( '?user_IncExperience' , {
			  'id': ids.join(','),
			  'Experience' : val
			} );
		});		  
    }
    ,DecExperience: function(){ //获取选中数据，减积分
		layer.prompt({
			title:'减少' + ASPBBS.ExperienceName
		},function(val, index){
			layer.close(index);
			SetField( '?user_DecExperience' , {
			  'id': ids.join(','),
			  'Experience' : val
			} );
		});		  
    }
	,CloseThread : function(){
		layer.confirm('确认要将选中的用户禁止发帖吗？', function(){
			SetField( '?Manage_CloseStatusField' , {
			  'id': ids.join(','),
			  'StatusField' : 'ThreadStatus'
			} );
		});
	}
	,OpenThread : function(){
		layer.confirm('确认要将选中的用户允许发帖吗？', function(){
			SetField( '?Manage_OpenStatusField' , {
			  'id': ids.join(','),
			  'StatusField' : 'ThreadStatus'
			} );
		});
	}
	,CloseReply : function(){
		layer.confirm('确认要将选中的用户禁止回帖吗？', function(){
			SetField( '?Manage_CloseStatusField' , {
			  'id': ids.join(','),
			  'StatusField' : 'ReplyStatus'
			} );
		});
	}
	,OpenReply : function(){
		layer.confirm('确认要将选中的用户允许回帖吗？', function(){
			SetField( '?Manage_OpenStatusField' , {
			  'id': ids.join(','),
			  'StatusField' : 'ReplyStatus'
			} );
		});
	}
	,CloseStatus : function(){
		layer.confirm('确认要将选中的用户禁止登陆吗？', function(){
			SetField( '?Manage_CloseStatusField' , {
			  'id': ids.join(','),
			  'StatusField' : 'UserStatus'
			} );
		});
	}
	,OpenStatus : function(){
		layer.confirm('确认要将选中的用户允许登陆吗？', function(){
			SetField( '?Manage_OpenStatusField' , {
			  'id': ids.join(','),
			  'StatusField' : 'UserStatus'
			} );
		});
	}
	,OpenAdmin : function(){
		layer.confirm('确认要将选中的用户设为管理员吗？', function(){
			SetField( '?Manage_OpenAdmin' , {
			  'id': ids.join(','),
			  'IsAdmin' : '1'
			} );
		});
	}
	
	,CloseAdmin : function(){
		layer.confirm('确认要给选中的用户取消管理员吗?', function(){
			SetField( '?Manage_CloseAdmin' , {
			  'id': ids.join(','),
			  'IsAdmin' : '0'
			} );
		});
	}
	,OpenThreadReplyView : function(){
		layer.confirm('确认要给选中的用户开启回复查看功能吗？', function(){
			SetField( '?Manage_OpenStatusField' , {
			  'id': ids.join(','),
			  'StatusField' : 'ThreadReplyView'
			} );
		});
	}
    ,getCheckLength: function(){ //获取选中数目
      var checkStatus = table.checkStatus('userList')
      ,data = checkStatus.data;
      layer.msg('选中了：'+ data.length + ' 个');
    }
    ,isAll: function(){ //验证是否全选
      var checkStatus = table.checkStatus('userList');
      layer.msg(checkStatus.isAll ? '全选': '未全选')
    }
  };
	//用户操作
	function SetField( url , data ) {
		fly.json( url , data, function(res){					
		  if(res.status === 0){
			layer.alert(
				res.msg, 
				{icon: 6
				,time: 2*1000
				,end: function(){
					layer.closeAll();
				}
			});			
			tableReload(null);
		  }
		});
	}
  
    //重载表格
	function tableReload( ViewType , keyword ){
	  if ( ViewType == null ) {
		ViewType =  $("#ViewType").val();		  
	  }
	  if ( keyword == null ) {
		  keyword = $("#keyword").val();
	  }
      table.reload('userList', {
        page: {
          curr: 1 //重新从第 1 页开始
        }
        ,where: {
          'ViewType': ViewType
		  ,'keyword': keyword
        }
      });
	}
	
  //修改登陆名，仅限管理员
  $('.aspbbs-edit').on('click', function(){
	 var othis = $(this), type = othis.attr('type') , fieldValue = othis.attr('fieldValue');
    layer.confirm('确定要修改登陆名吗？', {icon: 7}, function(){
		 layer.closeAll();
		 layer.prompt({
			  value: fieldValue,
			  title: '新的登陆名',
		 },function(val, index){
		   layer.closeAll();
		  fly.json('?User_editLoginName', {
			  'fieldName' : type
			  ,'fieldValue' : val
		  }, function(res){
			if(res.status === 0){
			  layer.alert('登陆名修改完成!', {
				icon: 1
				,end: function(){
				  location.reload();
				}
			  });
			} else {
			  layer.msg(res.msg);
			}
		  });
		}); 
    });
  });
  
  //轮流显示头像
  $('.aspbbs-avatar').on('click', function(){
	 var othis = $(this), type = othis.attr('type') , prefix = othis.attr('fieldValue');
	 var index,fieldValue = $('#L_Avatar').attr("src");
		if ( fieldValue.indexOf(prefix) > -1 ) {
			index = fieldValue.match(/\d+\.jpg/i);
			index = parseInt(index);
			if ( isNaN(index) ) {
				index = 0;
			}
			if ( index == ASPBBS.AvatarCount - 1 ) {
				index = 0;
			} else {
				index = index + 1;
			}
			fieldValue = prefix + index + ".jpg";
		} else {
			fieldValue = prefix + "0.jpg"
		}
		$("#L_Avatar").attr( "src" , fieldValue );
  });
  
   //修改头像
  $('.aspbbs-editAvatar2').on('click', function(){
	 var othis = $(this), type = othis.attr('type');
    layer.confirm('确定要使用该内置头像吗？', {icon: 7}, function(){
		 layer.closeAll();
		  $('.fly-nav-avatar img').attr( 'src', othis.find("img").attr("src") );
		  fly.json('?User_editAvatar', {
			  'fieldName' : type
			  ,'fieldValue' : othis.find("img").attr("src")
		  }, function(res){
			if(res.status === 0){		
				layer.msg('头像修改完成!');
			} else {
			  layer.msg(res.msg);
			}			
		  });
    });
  });
  
  
   //修改头像
  $('.aspbbs-editAvatar').on('click', function(){
	 var othis = $(this), type = othis.attr('type');
    layer.confirm('确定要使用该内置头像吗？', {icon: 7}, function(){
		 layer.closeAll();
		 $('.fly-nav-avatar img').attr( 'src' ,  $('#L_Avatar').attr("src") );
		  fly.json('?User_editAvatar', {
			  'fieldName' : type
			  ,'fieldValue' : $('#L_Avatar').attr("src")
		  }, function(res){
			if(res.status === 0){		
				layer.msg('头像修改完成!');
			} else {
			  layer.msg(res.msg);
			}			
		  });
    });
  });

	form.on('select(ViewType)', function(data){
		//console.log(data.elem); //得到select原始DOM对象
		//console.log(data.value); //得到被选中的值
		//console.log(data.othis); //得到美化后的DOM对象
      //执行重载
	  tableReload( data.value );
	});
	
	$('#soBtn').on( 'click' , function(){
		tableReload();
	} );
	
	form.on('select(DealType)', function(data){
		var type = data.value;
		if (  type != ''  ) {
			ids = getIds( 'userList' );
			if ( ids.length == 0 ) {
				layer.alert( "未选中任何用户！" , {icon: 5} );
				return false;
			} else {
				active[type] ? active[type].call(this) : '';				
			}
		}
	});
	
	//得到选中的id，返回数组
	function getIds( tableId ){
      var checkStatus = table.checkStatus( tableId )
      ,data = checkStatus.data
	  ,ids=[];
	  $.each( data,function(index,item){
		ids.push( item.UserID );
	  } );	
	  return ids;
	}
	
	
  
  exports('user', null);
  
});