/**

 @Name: 用户模块

 */
 
layui.define(['laypage', 'fly', 'element', 'flow', 'table'], 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;

  //我发的贴
  table.render({
    elem: '#LAY_mySendCard'
    ,url: '/api/my_send_card/'
    ,method: 'post'
    ,cols: [[
      {field: 'title', title: '帖子标题', minWidth: 300, templet: '<div><a href="/jie/{{ d.id }}/" target="_blank" class="layui-table-link">{{ d.title }}</a></div>'}
      ,{field: 'status', title: '状态', width: 100, align: 'center', templet: function(d){
        if(d.status == 1){
          return '<span style="color: #FF5722;">加精</span>';
        } else if(d.status == -1){
          return '<span style="color: #ccc;">审核中</span>';
        } else {
          return '<span style="color: #999;">正常</span>'
        }
      }}
      ,{field: 'status', title: '结贴', width: 100, align: 'center', templet: function(d){
        return d.accept >= 0 ? '<span style="color: #5FB878;">已结</span>' : '<span style="color: #ccc;">未结</span>'
      }}
      ,{field: 'time', title: '发表时间', width: 120, align: 'center', templet: '<div>{{ layui.util.timeAgo(d.time, 1) }}</div>'}
      ,{title: '数据', width: 150, templet: '<div><span style="font-size: 12px;">{{d.hits}}阅/{{d.comment}}答</span></div>'}
      ,{title: '操作', width: 100, templet: function(d){
        return d.accept == -1 ? '<a class="layui-btn layui-btn-xs" href="/jie/edit/'+ d.id +'" target="_blank">编辑</a>' : ''
      }}
    ]]
    ,page: true
    ,skin: 'line'
  });

  //我收藏的帖
  if($('#LAY_myCollectioncard')[0]){
    fly.json('/collection/find/', function(res){
      table.render({
        elem: '#LAY_myCollectioncard'
        ,data: layui.sort(res.rows, 'collection_timestamp', 'desc')
        ,cols: [[
          {field: 'title', title: '帖子标题', minWidth: 300, templet: '<div><a href="/jie/{{ d.id }}/" target="_blank" class="layui-table-link">{{ d.title }}</a></div>'}
          ,{field: 'collection_timestamp', title: '收藏时间', width: 120, align: 'center', templet: '<div>{{ layui.util.timeAgo(d.collection_timestamp, 1) }}</div>'}
        ]]
        ,page: true
        ,skin: 'line'
      });
    });
  }

  //显示当前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;
    }
  });


  var gather = {}, dom = {
    mine: $('#LAY_mine')
    ,mineview: $('.mine-view')
    ,minemsg: $('#LAY_minemsg')
    ,infobtn: $('#LAY_btninfo')
  };

  //根据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: 50
        ,before: function(){
          avatarAdd.find('.loading').show();
        }
        ,done: function(res){
          if(res.status == 0){
            $.post('/user/set/', {
              avatar: res.url
            }, function(res){
              location.reload();
            });
          } else {
            layer.msg(res.msg, {icon: 5});
          }
          avatarAdd.find('.loading').hide();
        }
        ,error: function(){
          avatarAdd.find('.loading').hide();
        }
      });
    });
  }

  //提交成功后刷新
  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('/api/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 layui-text">{{ 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');
      layer.confirm('确定删除该条消息吗？', function(index){
        layer.close(index);
        fly.json('/message/remove/', {
          id: id
        }, function(res){
          if(res.status === 0){
            othis.remove();
            delEnd();
          }
        });
      });
    });

    //删除全部
    $('#LAY_delallmsg').on('click', function(){
      var othis = $(this);
      layer.confirm('确定清空吗？', function(index){
        layer.close(index);
        fly.json('/message/remove/', {
          all: true
        }, function(res){
          if(res.status === 0){
            othis.addClass('layui-hide');
            delEnd(true);
          }
        });
      });
    });

  };

  dom.minemsg[0] && gather.minemsg();


  //已购产品
  table.render({
    elem: '#LAY_productList'
    ,url: '/product/mine/'
    ,method: 'post'
    ,where: function(){
      var where = {}
      ,alias = layui.data.alias;
      if(alias) where.alias = alias;
      return where;
    }()
    ,cols: [[
      {title: '产品名称', minWidth: 200, templet: function(d){
        var href = d.product.homepage || ('/download/'+ d.item.id);
        return '<a href="'+ href +'" target="_blank" class="layui-table-link">'+ (d.product.title || d.authProduct) + '</a>'
      }}
      ,{field:'authProduct', title: '别名', width: 130}
      ,{field:'version', title: '版本', width: 100, templet: function(d){
        return 'v'+ d.product.version || '';
      }}
      ,{title: '属性', width: 150, templet: function(d){
        var arr = [];
        layui.each(d.attr, function(index, item){
          if(item.name){
            arr.push(item.name + '：' + (item.value || ''));
          }
        });
        return arr.join('、')
      }}
      ,{field: 'price', title: '付费金额', width: 100, templet: function(d){
        return '<span style="color: #FF5722;">￥'+ (d.price || 0) +'</span>';
      }}
      ,{field: 'expiry_time', title: '有效期', width: 110, templet: function(d){
        return d.expiry_time ? layui.util.toDateString(d.expiry_time, "yyyy-MM-dd") : '永久';
      }}
      ,{field: 'create_time', title: '创建时间', width: 110, templet: function(d){
        return layui.util.toDateString(d.create_time, "yyyy-MM-dd");
      }}
      

      ,{title: '操作', width: 120, fixed: 'right', templet: function(d){
        var arr = []
        if(d.is_expiry){
          arr.push('<a href="/order/bill?itemid='+ d.item.id +'" target="_blank" class="layui-btn layui-btn-danger layui-btn-xs">重新授权</a>');
        } else {
          arr.push('<a href="/download/'+ d.item.id +'" target="_blank" class="layui-btn layui-btn-normal layui-btn-xs">下载</a>');

          if(d.item.upid){
            arr.push('<a href="/order/bill?itemid='+ d.item.upid +'" target="_blank" class="layui-btn layui-btn-danger layui-btn-xs">升级</a>');
          }
        }

        return arr.join('');
      }}
    ]]
    ,page: true
    ,text: {
      none: function(){
        var where = {}
        ,alias = layui.data.alias;
        return alias ? '未查询到你的 '+ alias +' 授权记录' : '您还没有任何产品授权（推荐：<a href="http://www.layui.com/admin/" target="_blank" class="fly-link">layuiAdmin</a>）'
      }()
    }
    ,done: function(res, curr){
      //无数据
      if(res.data.length === 0 && curr == 1){
        
      }
    }
  });


  //我发布的组件
  table.render({
    elem: '#LAY_mySendExtend'
    ,url: '/extend/mine/'
    ,method: 'post'
    ,cols: [[
      {field: 'title', title: '组件', minWidth: 200, templet: '<div><a href="/extend/{{ d.alias }}/" target="_blank" class="layui-table-link">{{ d.title }}</a></div>'}
      ,{field: 'alias', title: '组件模块名', align: 'center', width: 120}
      ,{field: 'status', title: '状态', width: 100, align: 'center', templet: function(d){
        if(d.status == 1){
          return '<span style="color: #FF5722;">加精</span>';
        } else if(d.status == -1){
          return '<span style="color: #ccc;">审核中</span>';
        } else {
          return '<span style="color: #999;">正常</span>'
        }
      }}
      ,{field: 'create_time', title: '发布时间', width: 120, align: 'center', templet: '<div>{{ layui.util.timeAgo(d.create_time, 1) }}</div>'}
      ,{title: '操作', width: 100, align: 'center', templet: function(d){
        return !d.lock ? '<a class="layui-btn layui-btn-xs" href="/extend/release/'+ d.alias +'/" target="_blank">编辑</a>' : ''
      }}
    ]]
    ,page: true
    ,text: {
      none: '您还没有贡献过组件（<a href="/extend/" target="_blank" class="fly-link">前往发布</a>）'
    }
    //,skin: 'line'
  });


  exports('user', {});
  
});