var util = require('util');
var path = require('path');
var fs = require('fs');
var utils = require('utils');
var Service = require('Service');
var TBSCompiler = require('TBSCompiler');

/**
 * 添加数据查询页面
 */
var CreateDataQueryTFP = function() { 
  Service.call(this);
  this.sqlInject = {
    check: false   
  };
};

util.inherits(CreateDataQueryTFP, Service);

module.exports = CreateDataQueryTFP;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
CreateDataQueryTFP.prototype.process =  function(req, res) {
  if(!req.proj) {
    this.onLogicError(1, "请提供项目名称！");
    return;
  }
  if(!req.path) {
    this.onLogicError(1, "请提供保存路径！");
    return;
  }
	req.path = req.path.endWith(".tfp") ? req.path : req.path+".tfp";
  let fileName = req.path.substr(req.path.lastIndexOf("/")+1);
  if(!fileName) {
    this.onLogicError(3, "请提供文件名称！");
    return;
  }
  if(!req.model) {
    this.onLogicError(11, "请提供数据模型名称！");
    return;
  }
  if(!req.title) {
    this.onLogicError(4, "请提供页面标题！");
    return;
  }
  if(!req.pageType) {
    this.onLogicError(7, "请提供页面类型！");
    return;
  }
  if(req.pageType=="dialog") {
    if(!req.dialogWidth) {
      this.onLogicError(9, "请提供窗口宽度！");
      return;
    }
    req.dialogWidth += "";
    if(!req.dialogHeight) {
      this.onLogicError(10, "请提供窗口高度！");
      return;
    }
    req.dialogHeight += "";
  }
  if(!req.client) {
    this.onLogicError(5, "请提供客户端类型！");
    return;
  }
  if(!req.positionType) {
    this.onLogicError(8, "请提供定位方式！");
    return;
  }
  if(!req.bgColorMode) {
    this.onLogicError(8, "请提供背景颜色！");
    return;
  }
  if(!req.fields || req.fields.length==0) {
    this.onLogicError(12, "请提供要查询的字段信息！");
    return;
  }
  if(!req.gridColumns || req.gridColumns.length==0) {
    this.onLogicError(12, "请提供要显示设置信息！");
    return;
  }

  let tfpFilePath = utils.getPath(req.path);
  if(fs.existsSync(tfpFilePath)) {
    this.onLogicError(14, "TFP文件已存在！");
    return;
  }

  let queryServicePath = "";
  let queryServiceType = ".tbs";
  let queryServiceFilePath = "";
  if(req.createQueryService) {
    if(!req.queryServicePath) {
      this.onLogicError(15, "请提供查询数据的服务路径！");
      return;
    }
    if(req.queryServiceType==".js") queryServiceType = ".js";
    queryServicePath = req.queryServicePath+queryServiceType;
    queryServiceFilePath = utils.getPath("/app/"+queryServicePath);
    if(fs.existsSync(queryServiceFilePath)) {
      this.onLogicError(16, "查询数据的服务已存在！");
      return;
    }
  }

  let deleteServicePath = "";
  let deleteServiceType = ".tbs";
  let deleteServiceFilePath = "";
  if(req.createDeleteService) {
    if(!req.deleteServicePath) {
      this.onLogicError(17, "请提供删除数据的服务路径！");
      return;
    }
    if(req.deleteServiceType==".js") deleteServiceType = ".js";
    deleteServicePath = req.deleteServicePath+deleteServiceType;
    deleteServiceFilePath = utils.getPath("/app/"+deleteServicePath);
    if(fs.existsSync(deleteServiceFilePath)) {
      this.onLogicError(18, "删除数据的服务已存在！");
      return;
    }
  }
  
  var pageDM = {
    client: req.client,
    framework: "tfp",
    positionType: req.positionType,
    pageType: req.pageType,
    title: req.title,
    bgColorMode: req.bgColorMode,
    type: "Page",
    components: [{
      id: "panel1",
      type: "Panel",
      styles: {
        "left": "10px",
        "top": "10px",
        "right": "10px",
        "bottom": "10px",
        "position": "absolute",
        "background-color": "#FFFFFF",
        "border-radius": " 6px 6px 6px 6px",
        "border-color": "#CCCCCC",
        "border-width": "0",
        "box-shadow": " 3px 5px 5px #cccccc",
        "min-width": "780px",
        "overflow": "auto"
      },
      components: [{
        id: "label1",
        type: "Label",
        value: "查询条件",
        styles: {
          "left": "20px",
          "top": "20px",
          "position": "absolute",
          "font-weight": "bold",
          "line-height": "40px"
        }
      },{
        id: "panel2",
        type: "Panel",
        styles: {
          "left": "20px",
          "top": "60px",
          "right": "20px",
          "height": "50px",
          "position": "absolute",
          "background-color": "#f0f0ff",
          "overflow": "auto"
        },
        components: []
      },{
        id: "label2",
        type: "Label",
        value: "查询结果",
        styles: {
          "left": "20px",
          "top": "110px",
          "position": "absolute",
          "font-weight": "bold",
          "line-height": "40px"
        }
      },
      {
        "id": "grid1",
        "type": "Grid",
        "showHeader": true,
        "showFooter": true,
        "loadDataService": "serviceGetList",
        "dataBindingMember": "data",
        "styles": {
          "position": "absolute",
          "left": "20px",
          "right": "20px",
          "bottom": "20px",
          "top": "150px"
        },
        "columns": req.gridColumns
      }]
    }, {
      id: "serviceGetList",
      type: "Service",
      path: queryServicePath,
      argSettings: []
    }]
  };

  var dbQuery = { 
    category: "db",
    type: "query",
    model: {
      name: req.model,
      path: "/app/"+req.proj+"/model/"+req.model+".tdm"
    },
    fields: req.fields,
    where: "",
    cbArg: "rows", 
    statements: [{
      category: "common",
      type: "assign",
      varName: "res.data",
      operator: "=",
      value: "rows"
    },{
      category: "common",
      type: "end"
    }]
  };
  if(req.orderConditions) dbQuery.orders = req.orderConditions;
  if(req.pageSize) dbQuery.pageSize = parseInt(req.pageSize);
  if(req.count) dbQuery.count = parseInt(req.count);
  if(req.distinct) dbQuery.distinct = true;
  if(req.where) dbQuery.where = req.where;
  var resArg = {name:"data", type:"array"};
  if(req.enableDataPage) {
    dbQuery.enableDataPage = true;
    resArg = {name:"data", type:"object"};
  }
  var reqArgs = [];

  var labelQuery = pageDM.components[0].components[0];
  var panelQuery = pageDM.components[0].components[1];
  var labelGrid = pageDM.components[0].components[2];
  var grid = pageDM.components[0].components[3];
  if(req.operates && req.operates.indexOf("add")>=0) {
    panelQuery.components.push({
      id: "button_add",
      type: "Button",
      buttonType: "primary",
      theme: "rect",
      value: "添加",
      styles: {
        "float": "left",
        "width": "50px",
        "margin-top": "10px",
        "margin-left": "10px",
        "cursor": "pointer",
        "padding-left": "10px",
        "padding-right": "10px",
        "text-align": "center"
      },
      onClick: "tfp.gotoPage('add.tfp')"
    });
  }
  if(req.queryArgs && req.queryArgs.length>0) {
    dbQuery.queryArgs = [];
    for(var i=0;i<req.queryArgs.length;i++) {
      let queryArg = req.queryArgs[i];
      dbQuery.queryArgs.push({
        name: queryArg.name,
        comment: queryArg.comment,
        condition: queryArg.condition
      });
      panelQuery.components.push({
        id: "label_"+queryArg.name,
        type: "Label",
        value: queryArg.comment+"：",
        styles: {
          "float": "left",
          "line-height": "50px",
          "margin-left": "10px"
        }
      });
      let ipt = {
        id: queryArg.name,
        type: queryArg.type,
        styles: {
          "float": "left",
          "margin-top": "12px",
          "margin-left": "5px"
        }
      };
      if(queryArg.width) {
        ipt.styles.width = queryArg.width;
      } 
      if(queryArg.type=="Text" || queryArg.type=="Select") {
        if(!ipt.styles.width) ipt.styles["width"] = "80px";
        ipt.styles["height"] = "24px";
        ipt.styles["padding-left"] = "2px";
        ipt.styles["padding-right"] = "2px";
        ipt.styles["background-color"] = "#FFFFFF";
      } else if(queryArg.type=="Switch") {
        ipt.styles["margin-top"] = "14px";
      }
      if(queryArg.type=="Select" || queryArg.type=="Radio" 
        || queryArg.type=="CheckBox" || queryArg.type=="Switch") {
        try {
          //console.log(queryArg.options);
          if(queryArg.options){
            if(typeof(queryArg.options)=="string") {
              if(queryArg.type=="Switch") {
                ipt.options = queryArg.options.split(",");
              } else {
                if(queryArg.options.startWith("[") && queryArg.options.endWith("]")) {
                  ipt.options = JSON.parse(queryArg.options);
                } else {
                  let arrTmp = queryArg.options.split(",");
                  ipt.options = [];
                  for(var j=0;j<arrTmp.length;j++) {
                    ipt.options.push({value:arrTmp[j]});
                  }
                }
              }
            } else if(Array.isArray(queryArg.options)) {
              ipt.options = queryArg.options;
            }
          }
        } catch(e) {
          logger.log(e);
        }
      }
      if(queryArg.default) ipt.value = queryArg.default;
      panelQuery.components.push(ipt);
      reqArgs.push({name: queryArg.name, type:"string"});
      pageDM.components[1].argSettings.push({
        "name": queryArg.name,
        "type": "ComponentVal",
        "value": queryArg.name
      });
    }
  }
  if(req.queryArgs && req.queryArgs.length>0) {
    panelQuery.components.push({
      id: "button_query",
      type: "Button",
      buttonType: "primary",
      value: "查询",
      theme: "rect",
      styles: {
        "float": "left",
        "width": "50px",
        "margin-top": "10px",
        "margin-left": "10px",
        "cursor": "pointer",
        "padding-left": "10px",
        "padding-right": "10px",
        "text-align": "center"
      },
      onClick: "grid1.gotoPage(1)"
    });
  }
  let gridKeys = "";
  let delReqArgs = [];
  let updateArgs = "";
  let deleteArgs = "";
  let delSmWhere = "";
  for(var i=0;i<req.dataKeys.length;i++) {
    let key = req.dataKeys[i];
    if(i>0) {
      gridKeys += ",";
      updateArgs += "&";
      deleteArgs += " , ";
      delSmWhere += " and ";
    }
    gridKeys += key.name;
    updateArgs += key.name+"={"+key.name+"}";
    delReqArgs.push({
      name: key.name,
      type: key.type,
      notNull: true
    });
    if(key.type=="int" || key.type=="numeric") {
      deleteArgs += "{"+key.name+"}";
      delSmWhere += key.name+"={req."+key.name+"}";
    } else {
      deleteArgs += "'{"+key.name+"}'";
      delSmWhere += key.name+"='{req."+key.name+"}'";
    }
    let isAddKey = false;
    for(var j=0;j<dbQuery.fields.length;j++) {
      if(dbQuery.fields[j].name==key.name) {
        isAddKey = true;
        break;
      }
    }
    if(!isAddKey) dbQuery.fields.push({name: key.name});
  }
  grid.dataBindingKey = gridKeys;
  if(req.operates && req.operates.indexOf("update")>=0) {
    grid.columns.push({
      "align": "center",
      "color": "#000099",
      "format": "修改",
      "name": "修改",
      "onClick": "tfp.gotoPage('update.tfp?"+updateArgs+"')",
      "width": "50"
    });
  }
  if(req.operates && req.operates.indexOf("delete")>=0) {
    grid.columns.push({
      "align": "center",
      "color": "#FF0000",
      "format": "删除",
      "name": "删除",
      "onClick": "grid1.deleteRow("+deleteArgs+")",
      "width": "50"
    });
    pageDM.components.push({
      id: "serviceDelete",
      type: "Service",
      path: deleteServicePath
    });
    grid.delDataService = "serviceDelete";
  }
  if(panelQuery.components.length==0) {
    labelQuery.styles.display = "none";
    panelQuery.styles.display = "none";
    labelGrid.styles.top = "20px";
    grid.styles.top = "60px";
  }
  if(req.enableDataPage) {
    grid.allowPaging = true;
    if(req.pageSize) grid.pageSize = req.pageSize;
  }
  if(req.pageType=="dialog") {
    pageDM.width = req.dialogWidth.indexOf("px")>0 ? req.dialogWidth : req.dialogWidth+"px";
    pageDM.height = req.dialogHeight.indexOf("px")>0 ? req.dialogHeight : req.dialogHeight+"px";
  }

  fs.writeFileSync(tfpFilePath, JSON.stringify(pageDM, null, "\t"));

  if(!req.createQueryService && !req.createDeleteService) {
    this.end(res);
    return;
  }

  let modelName = req.model.substr(0, 1).toUpperCase()+req.model.substr(1);
  
  let options = {
    modelName: modelName,
    reqArgs: reqArgs,
    resArg: resArg,
    dbQuery: dbQuery,
    queryServiceFilePath: queryServiceFilePath,
    delReqArgs: delReqArgs,
    delSmWhere: delSmWhere,
    deleteServiceFilePath: deleteServiceFilePath
  };

  this.createQueryService(req, res, options);
};

CreateDataQueryTFP.prototype.createServiceDir = function(req, res, servicePath, cb) {
 let arrDir = servicePath.split("/");
  try {
    let serviceDir = utils.getPath("/app");
    for(let i=0;i<arrDir.length-1;i++) {
      if(arrDir[i]=="") continue;
      serviceDir += "\\"+arrDir[i];
      if(!fs.existsSync(serviceDir)) fs.mkdirSync(serviceDir);
    }
    cb();
  } catch(err) {
    logger.log(err);
    cb(err);
    return;
  }
};

CreateDataQueryTFP.prototype.createQueryService = function(req, res, options) {
  if(!req.createQueryService) {
    this.createDeleteService(req, res, options);
    return;
  }
  var tbsQuery = {
    name: modelName+"_GetList",
    comment: "获得"+req.model+"列表",
    reqArgs: options.reqArgs,
    resArgs: [options.resArg],
    methods: [{
      name: "process",
      comment: "处理服务请求",
      args: [{
        name: "req",
        type: "object",
        comment: "服务请求对象"
      },{
        name: "res",
        type: "object",
        comment: "服务响应对象"
      }],
      statements: []
    }]
  };
  tbsQuery.methods[0].statements.push(options.dbQuery);

  var self = this;
  this.createServiceDir(req, res, req.queryServicePath, function(err) {
    if(err) {
      self.onLogicError(16, "创建服务目录失败："+err.message);
      return;
    }
    if(req.queryServiceType==".js") {
      var compilerQuery = new TBSCompiler();
      compilerQuery.process({tbs: tbsQuery}, {code: 0}, function(res2) {
        if(res2.code!=0) {
          self.onLogicError(6, "TBS文件编译失败："+res2.message);
          return;
        }
        fs.writeFileSync(options.queryServiceFilePath, res2.jsCode);
        self.createDeleteService(req, res, options);
      });
    } else {
      fs.writeFileSync(options.queryServiceFilePath, JSON.stringify(tbsQuery, null, "\t"));
      self.createDeleteService(req, res, options);
    }
  });
};

CreateDataQueryTFP.prototype.createDeleteService = function(req, res, options) {
  if(!req.createDeleteService) {
    this.end(res);
    return;
  }
  var tbsDelete = {
    name: modelName+"_Delete",
    comment: "删除"+req.model,
    reqArgs: options.delReqArgs,
    methods: [{
      name: "process",
      comment: "处理服务请求",
      args: [{
        name: "req",
        type: "object",
        comment: "服务请求对象"
      },{
        name: "res",
        type: "object",
        comment: "服务响应对象"
      }],
      statements: [{
        category: "db",
        type: "delete",
        model: {
          name: req.model,
          path: "/app/"+req.proj+"/model/"+req.model+".tdm"
        },
        where: options.delSmWhere,
        statements: [{
          category: "common",
          type: "end"
        }]
      }]
    }]
  };

  var self = this;
  this.createServiceDir(req, res, req.deleteServicePath, function(err) {
    if(err) {
      self.onLogicError(16, "创建服务目录失败："+err.message);
      return;
    }
    if(req.deleteServiceType==".js") {
      var compilerDelete = new TBSCompiler();
      compilerDelete.process({tbs: tbsDelete}, {code: 0}, function(res3) {
        if(res3.code!=0) {
          self.onLogicError(6, "TBS文件编译失败："+res3.message);
          return;
        }
        fs.writeFileSync(options.deleteServiceFilePath, res3.jsCode);
        self.end(res);
      });
    } else {
      fs.writeFileSync(options.deleteServiceFilePath, JSON.stringify(tbsDelete, null, "\t"));
      self.end(res);
    }
  });
};