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 CreateDataDetailTFP = function() { 
  Service.call(this);
};

util.inherits(CreateDataDetailTFP, Service);

module.exports = CreateDataDetailTFP;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
CreateDataDetailTFP.prototype.process =  function(req, res) {
  if(!req.proj) {
    this.onLogicError(1, "请提供项目名称！");
    return;
  }
  if(!req.path) {
    this.onLogicError(2, "请提供保存路径！");
    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.title) {
    this.onLogicError(4, "请提供页面标题！");
    return;
  }
  if(!req.client) {
    this.onLogicError(5, "请提供客户端类型！");
    return;
  }
  if(!req.pageType) {
    this.onLogicError(7, "请提供页面类型！");
    return;
  }
  if(!req.positionType) {
    this.onLogicError(8, "请提供定位方式！");
    return;
  }
  if(!req.bgColorMode) {
    this.onLogicError(8, "请提供背景颜色！");
    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.model) {
    this.onLogicError(11, "请提供数据模型名称！");
    return;
  }
  if(!req.fields || req.fields.length==0) {
    this.onLogicError(12, "请提供要查询的字段信息！");
    return;
  }
  let filePath = utils.getPath(req.path);
  if(fs.existsSync(filePath)) {
    this.onLogicError(14, "TFP文件已存在！");
    return;
  }

  let getServicePath = "";
  let getServiceType = ".tbs";
  let getServiceFilePath = "";
  if(req.createGetService) {
    if(!req.getServicePath) {
      this.onLogicError(15, "请提供查询数据的服务路径！");
      return;
    }
    if(req.getServiceType==".js") getServiceType = ".js";
    getServicePath = req.getServicePath+getServiceType;
    getServiceFilePath = utils.getPath("/app/"+getServicePath);
    if(fs.existsSync(getServiceFilePath)) {
      this.onLogicError(16, "查询数据的服务已存在！");
      return;
    }
  }
  
  var pageDM = {
    client: req.client,
    framework: "tfp",
    positionType: req.positionType,
    pageType: req.pageType,
    bgColorMode: "light",
    title: req.title,
    type: "Page",
    components: [{
      id: "panel_page",
      type: "Panel",
      components: [{
        id: "panel_title",
        type: "Panel",
        styles: {
          "width": "100%",
          "height": "50px",
        },
        components: [{
          id: "label_page_title",
          type: "Label",
          value: req.title,
          styles: {
            "float": "left",
            "margin-left": "20px",
            "font-weight": "bold",
            "line-height": "50px"
          }
        }]
      },{
        id: "form1",
        type: "Form",
        loadDataService: "serviceGet",
        dataBindingMember: "data",
        styles: {
          "left": "0",
          "top": "50px",
          "right": "0",
          "bottom": "0",
          "position": "absolute",
          "overflow": "auto"
        },
        components: []
      }]
    }, {
      id: "serviceGet",
      type: "Service",
      path: getServicePath,
      argSettings: []
    }]
  };

  if(pageDM.pageType=="page") {
    pageDM.components[0].styles = {
      "left": "10px",
      "top": "10px",
      "right": "10px",
      "bottom": "10px",
      "position": "absolute",
      "border-radius": " 6px 6px 6px 6px",
      "border": "1px solid #eee",
      "box-shadow": " 3px 5px 5px #cccccc",
      "overflow": "auto"
    };
  } else {
    pageDM.components[0].styles = {
      "left": "0",
      "top": "0",
      "right": "0",
      "bottom": "0",
      "position": "absolute",
      "overflow": "auto"
    };
    pageDM.width = req.dialogWidth.indexOf("px")>0 ? req.dialogWidth : req.dialogWidth+"px";
    pageDM.height = req.dialogHeight.indexOf("px")>0 ? req.dialogHeight : req.dialogHeight+"px";
    //对话框不显示标题栏
    pageDM.components[0].components[0].styles["display"] = "none";
    pageDM.components[0].components[1].styles["top"] = "0";
    //pageDM.components[0].components[2].components[1].onClick = "tfp.closeCurDialog()";
  }
  if(pageDM.bgColorMode=="light") {
    pageDM.components[0].styles["background-color"] = "#FFFFFF";
  } else {
    pageDM.components[0].styles["background-color"] = "#333333";
  }

  var statementGet = { 
    category: "db",
    type: "query",
    model: {
      name: req.model,
      path: "/app/"+req.proj+"/model/"+req.model+".tdm"
    },
    fields: [],
    count: 1,
    where: "",
    cbArg: "rows", 
    statements: [{
      category: "common",
      type: "assign",
      varName: "res.data",
      operator: "=",
      value: "rows[0]"
    },{
      category: "common",
      type: "end"
    }]
  };
  
  this.curCptTop = 60;
  let cptMetaDatas = global.server.tfpLibFilesCache[req.client].metaDatas;
  let formDM = pageDM.components[0].components[1];
  for(var i=0;i<req.fields.length;i++) {
    let field = req.fields[i];
    this.addRow(pageDM, cptMetaDatas, formDM, field, i);
    statementGet.fields.push({name: field.name});
  }
  
  let smWhere = "";
  let reqArgsGet = [];
  for(var i=0;i<req.dataKeys.length;i++) {
    let key = req.dataKeys[i];
    pageDM.components[1].argSettings.push({name: key.name, type: "QueryString"});
    reqArgsGet.push({name: key.name, type: key.type, notNull: true});
    if(i>0) smWhere += " and ";
    smWhere += key.name + "={req."+key.name+"}";
    let isAddKey = false;
    for(var j=0;j<statementGet.fields.length;j++) {
      if(statementGet.fields[j].name==key.name) {
        isAddKey = true;
        break;
      }
    }
    if(!isAddKey) {
      statementGet.fields.push({name: key.name});
    }
  }
  statementGet.where = smWhere;

  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";
    pageDM.components[0].components[1].components[1].onClick = "closeCurDialog()";
  }

  fs.writeFileSync(filePath, JSON.stringify(pageDM, null, "  "));
  if(!req.createService) {
    this.end(res);
    return;
  }

  var options = {
    reqArgsGet: reqArgsGet,
    statementGet: statementGet,
    getServiceFilePath: getServiceFilePath
  };

  this.createGetService();
};

CreateDataDetailTFP.prototype.addRow =  function(pageDM, cptMetaDatas, formDM, field, index) {
  let cptLabelDM = {
    id: "label_"+field.name,
    type: "Label",
    value: field.label+"："
  };
  if(pageDM.positionType=="float") {
    cptLabelDM.styles = {
      "float": "left"
    };
  } else {
    cptLabelDM.styles = {
      "position": "absolute",
      "z-index": "1",
      "left": "20px",
      "top": this.curCptTop+"px"
    };
  }
  let cptType = cptMetaDatas[field.type];

  let cptDM = {
    id: field.name,
    type: field.type,
    comment: field.label,
    dataBindingFormat: field.format
  };
  if(field.type=="Text" || field.type=="textarea") {
    cptDM.readonly = true;
  }
  if(pageDM.positionType=="float") {
    cptDM.styles = {
      "float": "left"
    };
  } else {
    cptDM.styles = {
      "position": "absolute",
      "z-index": "1",
      "left": "180px",
      "top": this.curCptTop+"px",
    };
  }

  /*if(field.notnull) {
    cptDM.required = true;
    formDM.components.push({
      id: "panel_"+field.name+"_required",
      type: "Panel",
      styles: {
        "left": "130px",
        "top": (this.curCptTop+10)+"px",
        "position": "absolute",
        "width": "3px",
        "height": "20px",
        "background-color": "#FF6600"
      }
    });
  }*/
  if(field.default) cptDM.value = field.default;
  if(cptType.defaultStyles) {
    for(styleName in cptType.defaultStyles) {
      cptDM.styles[styleName] = cptType.defaultStyles[styleName];
    }
  }
  if(field.width) cptDM.styles.width = field.width;

  let labelContainerDM = formDM;
  let cptContainerDM = formDM;
  if(pageDM.positionType=="float") {
    let flexDM = {
      "type": "FlexBox",
      "id": "flexBox"+index,
      "styles": {
        "display": "flex",
        "width": "100%",
        "padding": "5px 20px 5px 20px"
      },
      "components": [
        {
          "id": "flexBox"+index+"_panel1",
          "type": "Panel",
          "styles": {
            "flex-grow": 0,
            "flex-shrink": 0,
            "flex-basis": "180px",
            "height": "30px",
            "line-height": "30px"
          },
          "components": []
        },
        {
          "id": "flexBox"+index+"_panel2",
          "type": "Panel",
          "styles": {
            "flex-grow": 1,
            "flex-shrink": 0,
            "flex-basis": "auto",
            "height": "30px",
            "line-height": "30px"
          },
          "components": []
        }
      ]
    };
    labelContainerDM = flexDM.components[0];
    cptContainerDM = flexDM.components[1];
    if(cptDM.type=="TextArea" || cptDM.type=="RichText") {
      labelContainerDM.styles["height"] = cptType.defaultStyles.height;
      labelContainerDM.styles["line-height"] = cptType.defaultStyles.height;
    }
    formDM.components.push(flexDM);
  } else {
    if(cptDM.type=="TextArea") {
      let height = 120;
      if(field.height) {
        cptDM.styles.height = (field.height+"").indexOf("px")<0 ? field.height+"px" : field.height;
        height = parseInt((cptDM.styles.height+"").replace("px", ""));
      } else if(cptType.defaultStyles.height) {
        height = parseInt((cptType.defaultStyles.height+"").replace("px", ""));
      }
      this.curCptTop += height+20;
    } else if(cptDM.type=="RichText") {
      let height = 220;
      if(field.height) {
        cptDM.styles.height = (field.height+"").indexOf("px")<0 ? field.height+"px" : field.height;
        height = parseInt((cptDM.styles.height+"").replace("px", ""));
      } else if(cptType.defaultStyles.height) {
        height = parseInt((cptType.defaultStyles.height+"").replace("px", ""));
      }
      this.curCptTop += height+20;
    } else {
      this.curCptTop += 40;
    }
  }

  labelContainerDM.components.push(cptLabelDM);
  cptContainerDM.components.push(cptDM);
};

CreateDataDetailTFP.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;
  }
};

CreateDataDetailTFP.prototype.createGetService =  function(req, res, options) {
  if(!req.createService) {
    this.end(res);
    return;
  }
  var tbsGet = {
    name: req.model.substr(0, 1).toUpperCase()+req.model.substr(1)+"_Get",
    comment: "获得"+req.model,
    reqArgs: options.reqArgsGet,
    methods: [{
      name: "process",
      comment: "处理服务请求",
      args: [{
        name: "req",
        type: "object",
        comment: "服务请求对象"
      },{
        name: "res",
        type: "object",
        comment: "服务响应对象"
      }],
      statements: [options.statementGet]
    }]
  };

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