//表名变更 messages -> messages_1
var messageDao = {
    db: "dianwutong",
    table: "messages_1",
    open: {}, //打开数据库
    initTable: {}, //创建数据库
    updateData: {}, //同步服务器数据
}

messageDao.open = function(callback) {
    var db = api.require("db");
    db.openDatabase({
        name: messageDao.db
    }, function(ret, err) {
        if (!err && ret.status) {
            if (typeof(callback) == "function") {
                callback(db);
            }
        }
    })
}

//查询
messageDao.query = function(sql, callback) {
    messageDao.open(function(db) {
        db.selectSql({
            name: messageDao.db,
            sql: sql
        }, function(ret, err) {
            if (typeof(callback) == "function") {
                callback(ret, err);
                // console.log(sql);
								// console.log("查到的数据");
								// console.log(JSON.stringify(ret));
            }
        })
    })
}

//执行
messageDao.exec = function(sql, callback) {

    messageDao.open(function(db) {

        db.executeSql({
            name: messageDao.db,
            sql: sql
        }, function(ret, err) {
          // console.log(sql);
          // console.log("执行结果");
          // console.log(JSON.stringify(err));
            if (typeof(callback) == "function") {
                callback(ret, err);
            }
        })
    })
}

//创建message表
messageDao.initTable = function(callback) {
    var sql = " CREATE TABLE IF NOT EXISTS `" + this.table + "` ( " +
        " `msg_id` INT(11) NOT NULL, " +
        " `user_id` INT(11) NOT NULL, " +
        " `msg_type` INT(11), " +
        " `msg_content` LONGTEXT, " +
        " `content_id` INT(11), " +
        " `is_read` INT(11), " +
        " `msg_title` VARCHAR(256), " +
        " `create_time` TIMESTAMP, " +
        " `click_enable` INT(11), " +
        " PRIMARY KEY (`msg_id`) " +
        " )";

    messageDao.exec(sql, function(ret, err){
        if(callback){
          callback(ret, err);
        }
    });

}

//从数据库同步数据
messageDao.updateData = function(callback) {

    if( !userMaxMessageIdDao ){
      console.error("找不到：userMaxMessageIdDao");
      return false;
    }
    var userId = $api.getStorage("userId");

    userMaxMessageIdDao.getMaxId(userId, function(maxId) {
        if( !maxId ){
          maxId = null;
        }
        fetchMessages(maxId, writeDB);
    })

    function fetchMessages(maxId, callback) {
        var data = {
            userId: userId,
            msgId: maxId
        }

        var url = "/ems/rest/message/list";

        $api.get(url, data, function(ret, err) {
            if (!err && ret && ret.code == "200") {

                if (typeof(callback) == "function") {
                    callback(ret.body);
                }

            } else {
                api.toast({
                    msg: 'code:'+ret.code
                });
            }
        });
    }

    function writeDB(list) {
        var length = list.length;
        var maxId = 0;
        if (length == 0) {
            if (typeof(callback) == "function") {
                callback();
            }
            api.sendEvent({
                name: 'messageUpdated'
            });
            return false;
        }
        var userId = $api.getStorage("userId");

        var sql = 'insert into ' + messageDao.table + ' values';

        for (var i = 0; i < length; i++) {
            sql += "(";
            sql += list[i].msgId + ",";
            sql += userId + ",";
            sql += list[i].msgType + ",";
            sql += "'" + list[i].msgContent + "',";
            sql += list[i].contentId + ",";
            sql += "0,";
            sql += "'" + list[i].msgTitle + "',";
            sql += list[i].createTime/1000 + ",";   // 避免数据溢出 除以1000
            sql += (list[i].onlyRead == 0 ? 1 : 0);
            sql += "),";

            if(maxId < list[i].msgId){
              maxId = list[i].msgId;
            }
        }

        sql = sql.slice(0, -1);
        messageDao.exec(sql, function(ret, err) {
        //   console.log(JSON.stringify(ret), 'messageDao157')
            if (!err) {
                api.sendEvent({
                    name: 'messageUpdated'
                });

                userMaxMessageIdDao.updateUserMessageId(userId, maxId);
            }

            if (typeof(callback) == "function") {
                callback();
            }
        })

    }

}

//获取每类未读消息的数量
messageDao.getTypeUnReadCount = function(callback) {
    var userId = $api.getStorage("userId");
    var sql = "select substr(msg_type, 1,2) type, count(msg_id) sum from " + this.table + " where user_id=" + userId + " and is_read=0 group by substr(msg_type, 1,2)";
    this.query(sql, function(ret, err) {
        if (!err && ret && ret.status && typeof(callback) == "function") {
            callback(ret.data);
        }
    })
}

//获取没类消息的最新消息的时间
messageDao.getTypeLatestTime = function(callback){

	var userId = $api.getStorage('userId');
	var sql = "select max(create_time) create_time, substr(msg_type, 1, 2) type from " + this.table + " where user_id="+ userId + " group by substr(msg_type, 1,2)";
	this.query(sql, function(ret, err) {
			if (!err && ret && ret.status && typeof(callback) == "function") {
          var data = ret.data;
          var length = data.length;
          for(var i=0; i<length; i++){
            data[i].create_time = data[i].create_time*1000;
          }
					callback(ret.data);
			}
	})
}

//获取所有未读消息的数量
messageDao.getAllUnReadCount = function(callback) {
    var userId = $api.getStorage("userId");
    var sql = "select count(msg_id) sum from " + this.table + " where user_id=" + userId + " and is_read=0";
    this.query(sql, function(ret, err) {
        if (!err && ret && ret.status && typeof(callback) == "function") {
            if (ret.data[0]) {
                callback(ret.data[0].sum);
            } else {
                callback(0);
            }
        }
    })
}

//分页获取消息列表
messageDao.getOldMessages = function(types, page, pageSize, oldMaxId , callback) {
    var from = page * pageSize;
    var to = (page + 1) * pageSize;
    var userId = $api.getStorage("userId");
    types = types.join(',');

    var sql = "select * from " + this.table + " where user_id=" + userId + " and msg_type in (" + types + ") ";

    if ( oldMaxId ) {

      sql += ' and msg_id < ' + oldMaxId;

    }

    sql += " order by msg_id desc limit " + pageSize;

    // console.log(sql);

    messageDao.query(sql, function(ret, err) {
        // _log(ret);
        if (!err && ret && ret.data && typeof(callback) == "function") {

            var data = ret.data;
            var length = data.length;
            for(var i=0; i<length; i++){
              data[i].create_time = data[i].create_time*1000;
            }
            callback(ret.data);

        } else if (typeof(callback) == "function") {
            callback([]);
        }
    })
}

//获取新消息
messageDao.getNewMessages = function(types, newMinId, callback ){

  if(!newMinId){
    if (typeof(callback) == "function") {
        callback([]);
    }
    return false;
  }

    var types = types.join(',');
    var userId = $api.getStorage("userId");

    var sql = "select * from " + this.table + " where user_id=" + userId + " and msg_type in (" + types + ") ";

    if ( newMinId ) {

      sql += ' and msg_id > ' + newMinId;

    }

    sql += " order by msg_id asc ";

    messageDao.query(sql, function(ret, err) {
        if (!err && ret && ret.data && typeof(callback) == "function") {
            var data = ret.data;
            var length = data.length;
            for(var i=0; i<length; i++){
              data[i].create_time = data[i].create_time*1000;
            }
            callback(ret.data);
        } else if (typeof(callback) == "function") {
            callback([]);
        }
    })


}

//更新一类/或多类的消息为已读
messageDao.batchUpdateMessageToIsRead = function(msgTypes, callback) {
    var types = msgTypes.join(',');
    var sql = "update " + this.table + " set is_read = 1 where msg_type in ( " + types + ')';
    messageDao.exec(sql, function(ret, err) {
        if (!err) {
            api.sendEvent({
                name: 'messageUpdated'
            });

            if (typeof(callback) == "function") {
                callback(ret);
            }
        }
    })
}

//更新消息为已读
messageDao.updateMessageToIsRead = function(msgId, callback) {
    var sql = "update " + this.table + " set is_read = 1 where msg_id = " + msgId;
    messageDao.exec(sql, function(ret, err) {
        if (!err) {
            api.sendEvent({
                name: 'messageUpdated'
            });

            if (typeof(callback) == "function") {
                callback(ret);
            }
        }
    })
}

//清空所有记录
messageDao.clearAll = function(callback) {
    var userId = $api.getStorage("userId");
    var sql = "delete from " + this.table + " where user_id = " + userId;


    messageDao.exec(sql, function(ret, err) {

        if (!err) {
            api.sendEvent({
                name: 'messageUpdated'
            });

            if (typeof(callback) == "function") {
                callback(ret);
            }
        }
    })
}

// 删除一条消息
messageDao.deleteOne = function(msgId, callback){
  var sql = "delete from `" + this.table + "` where msg_id=" + msgId;

  this.exec(sql, function(ret, err) {

      if (!err) {
          api.sendEvent({
              name: 'messageUpdated',
              extra: {
                  type: 'delete',
                  msgId: msgId
              }
          });

          if (typeof(callback) == "function") {
              callback(ret);
          }
      }
  })

}

// 获取表中各个用户最大的消息id
messageDao.getMaxIds = function(callback){
  var sql = "select max(msg_id) as msg_id, user_id from `" + this.table +  "` group by user_id";
  this.query(sql, function(ret,err){
    var list = [];
    if(ret){
        list = ret.data;
    }

    if(callback){
      callback(list);
    }
  })
}
