var isRequest = false;
var editor;

$(function() {
  var mime = 'text/x-mysql';
  editor = CodeMirror($("#sqlEditer").get(0), {
    mode: mime,
    indentWithTabs: true,
    smartIndent: true,
    lineNumbers: true,
    styleActiveLine: true,
    matchBrackets: true,
    autofocus: true,
    selectionPointer: true,
    keyMap: "sublime",
    theme: "monokai",
    hintOptions: {completeSingle: false, tables: {}}
  });

  CodeMirror.on(editor, 'change', function(instance, object) {
    var str = object.text[0];
    if(str.length==1 && /^[a-zA-Z.]+$/.test(str) && str!="u" && str!="U") {
      CodeMirror.showHint(editor, CodeMirror.hint.custom);
    }
  });
  $("#sqlEditer").find(".CodeMirror").css("width", "100%");
});

function run() {
  var sql = editor.getSelection();
  if(!sql) sql = editor.getValue();
  if(!sql) {
    alert("请提供要执行的SQL语句！");
    return;
  }
  if(isRequest) {
    alert("兄弟，心急吃不了热豆腐，上一条语句还没执行完呢！");
    return;
  }
  isRequest = true;
  //alert(sql);
  top.taskBuilder.requestByIPC("dev/service/db/exeSql", {sql: sql}, onResponse);
}

function onResponse(args, res) {
  isRequest = false;
  $("#queryResult").empty();
  var d = new Date();
  var str = d.format("hh:mm:ss")+"."+d.getMilliseconds()+"<br>执行sql："+args.sql+"<br>";
  if(res.code!=0)  {
    str += "执行失败，错误描述：<br>"+res.message + "<br>";
  } else {
    str += "执行成功。<br>";
    if(res.ret) {
      //console.log(res.ret);
      str += "影响的行数："+res.ret.affectedRows;
      if(res.ret.insertId>0) str += " 新增记录编号："+res.ret.insertId;
      if(res.ret.changedRows>0) str += " 修改的行数："+res.ret.changedRows;
      if(res.ret.message) str += "\r\n"+res.ret.message;
    } else if(res.dataset) {
      if(res.dataset.rows.length==0) {
        str += "共查询到 0 条符合条件的记录。";
      } else {
        str += "共查询到 "+res.dataset.rows.length+" 条符合条件的记录。\r\n"
          +"<table cellpadding=\"3\" cellspacing=\"0\" border=\"1\" bordercolor=\"#CCCCCC\">";
        str += "<tr>";
        for(var i=0;i<res.dataset.columns.length;i++) {
          str += "<td>"+res.dataset.columns[i]+"</td>";
        }
        str += "</tr>";
        for(var i=0;i<res.dataset.rows.length;i++) {
          var row = res.dataset.rows[i];
          str += "<tr>";
          for(var j=0;j<row.length;j++) {
            str += "<td>"+row[j]+"</td>";
          }
          str += "</tr>";
        }
        str += "</table>";
      }
    }
  }
  $("#queryResult").html(str);
}