var util = require('util');
var path = require('path');
var fs = require('fs');
var utils = require('utils');
var Service = require('Service');
var TaskUIComponents = require('../../../../web/inc/taskui/taskui_components_pc.js').components;

/**
 * 添加手机端数据添加页面
 */
var CreateDataAddTFP = function() { 
  Service.call(this);
};

util.inherits(CreateDataAddTFP, Service);

module.exports = CreateDataAddTFP;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
CreateDataAddTFP.prototype.process =  function(req, res) {
  if(!req.path) {
    this.onLogicError(1, "请提供保存路径！");
    return;
  }
	if(!req.filename) {
    this.onLogicError(2, "请提供文件名称！");
    return;
  }
  if(req.filename.match(/[^\w]/g)) {
    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.pageType=="dialog") {
    if(!req.dialogWidth) {
      this.onLogicError(9, "请提供窗口宽度！");
      return;
    }
    req.dialogWidth += "";
    if(!req.dialogHeight) {
      this.onLogicError(10, "请提供窗口高度！");
      return;
    }
    req.dialogHeight += "";
  }
  if(!req.table) {
    this.onLogicError(11, "请提供数据模型名称！");
    return;
  }
  if(!req.fields || req.fields.length==0) {
    this.onLogicError(12, "请提供要查询的字段信息！");
    return;
  }
  let fileName = req.filename.endWith(".tfp") ? req.filename : req.filename+".tfp";
  let filePath = utils.getPath(req.path+"/"+fileName);

  let serviceDir = req.path.substring(req.path.indexOf("/web/app/")+9);
  if(serviceDir.indexOf("/")>0) serviceDir.substring(0, serviceDir.indexOf("/"));
  serviceDir = serviceDir+"/service/";
  let tbsPath = serviceDir+req.table+"_add_"+req.filename+".tbs";

  var tfp = {
    client: "pc", //req.client,
    framework: "tfp",
    positionType: req.positionType,
    pageType: req.pageType,
    title: req.title,
    type: "Page",
    styles: {
      "background-color": "#222222"
    },
    components: [{
      "id": "panel_phonebg",
      "type": "panel",
      "styles": {
        "position": "absolute",
        "left": "200px",
        "top": "10px",
        "width": "431px",
        "height": "890px",
        "background-color": "#222222",
        "background-image": "url(images/phonebg.png)",
        "border": "0"
      }
    },
    {
      "id": "panel_main",
      "type": "Panel",
      "styles": {
        "position": "absolute",
        "left": "228px",
        "top": "117px",
        "width": "375px",
        "height": "668px",
        "background-color": "#FFFFFF",
        "border": "0",
        "overflow": "auto"
      },
      components: [{
        id: "form1",
        type: "Form",
        submitService: "service1",
        styles: {
          "left": "0",
          "top": "0",
          "right": "0",
          "bottom": "0",
          "position": "absolute",
          "overflow": "auto"
        },
        components: [{
          id: "label1",
          type: "Label",
          value: req.title,
          styles: {
            "left": "20px",
            "top": "20px",
            "position": "absolute",
            "font-weight": "bold",
            "font-size": "16px",
            "line-height": "40px"
          }
        }]
      }]
    }, {
      id: "service1",
      type: "Service",
      path: tbsPath,
      args: []
    }]
  };

  var statement = { 
    category: "db",
    type: "insert",
    table: req.table,
    fields: [],
    cbArg: "ret", 
    statements: [{
      category: "common",
      type: "custom",
      content: "res.id = ret.insertId;\r\n"
    },{
      category: "common",
      type: "end"
    }]
  };
  var resArg = {name:"id", type:"int"};
  var reqArgs = [];

  let top = 60;
  let form = tfp.components[1].components[0];
  for(var i=0;i<req.fields.length;i++) {
    let field = req.fields[i];
    form.components.push({
      id: "label_"+field.name,
      type: "Label",
      value: field.label+"：",
      styles: {
        "left": "20px",
        "top": top+"px",
        "position": "absolute",
        "line-height": "40px",
        "font-size": "16px",
        "color": "#000000"
      }
    });
    if(field.notnull) {
      form.components.push({
        id: "panel_"+field.name+"_required",
        type: "Panel",
        styles: {
          "left": "10px",
          "top": (top+10)+"px",
          "position": "absolute",
          "width": "3px",
          "height": "20px",
          "background-color": "#FF6600"
        }
      });
    }
    top += 50;
    let cptType = TaskUIComponents[field.type];
    let cpt = {
      id: field.type+"_"+field.name,
      type: field.type,
      comment: field.label,
      styles: {
        "left": "20px",
        "top": top+"px",
        "position": "absolute",
      }
    };
    if(field.notnull) cpt.required = true;
    if(cptType.defaultStyles) {
      for(styleName in cptType.defaultStyles) {
        cpt.styles[styleName] = cptType.defaultStyles[styleName];
      }
    }
    if(field.width) cpt.styles.width = field.width;
    form.components.push(cpt);
    if(cpt.type=="textarea") {
      let height = 120;
      if(cptType.defaultStyles.height) 
        height = parseInt((cptType.defaultStyles.height+"").replace("px", ""));
      top += height;
    } else if(cpt.type=="richtext") {
      let height = 180;
      if(cptType.defaultStyles.height) 
        height = parseInt((cptType.defaultStyles.height+"").replace("px", ""));
      top += height;
    } else if(cpt.type=="radio" || cpt.type=="checkbox") {
      top += 40;
    } else if(cpt.type=="switch") {
      top += 40;
    } else {
      top += 40;
      if(cpt.type=="select" && field.options) cpt.options = field.options;
    }

    if(field.options && ["radio","checkbox","select"].contains(cpt.type)) {
      cpt.options = [];
      if(typeof(field.options)=="string") {
        if(field.options.startWith("[") && field.options.endWith("[")) {
          cpt.options = JSON.parse(field.options);
        } else {
          let options = field.options.split(",");
          for(var j=0;j<options.length;j++) {
            cpt.options.push({value:options[j], text:options[j]});
          }
        }
      } else if(Array.isArray(field.options)) {
        cpt.options = field.options;
        /*for(var j=0;j<field.options.length;j++) {
          cpt.options.push({value:field.options[j], text:field.options[j]});
        }*/
      }
    }
  
    statement.fields.push({
      name: field.name,
      value: "{req."+field.type+"_"+field.name+"}"
    });

    let reqArg = {
      name: field.type+"_"+field.name, 
      type:"字符串"
    };
    if(field.notnull) reqArg.notNull = true;
    reqArgs.push(reqArg);
  }
  form.components.push({
    id: "panel_bottom",
    type: "Panel",
    styles: {
      "top": top+"px",
      "left": "0",
      "height": "50px",
      "right": "0",
      "position": "absolute",
      "overflow": "auto"
    },
    components: [{
      id: "button_submit",
      type: "Button",
      buttonType: "primary",
      value: "确定",
      theme: "rect",
      styles: {
        "float": "left",
        "width": "60px",
        "margin-top": "10px",
        "margin-left": "calc(50% - 70px)",
        "cursor": "pointer",
        "text-align": "center"
      },
      onClick: "tfp('#form1').submit()"
    },{
      id: "button_cancel",
      type: "Button",
      buttonType: "default",
      value: "取消",
      theme: "rect",
      styles: {
        "float": "left",
        "width": "60px",
        "margin-top": "10px",
        "margin-left": "20px",
        "cursor": "pointer",
        "text-align": "center"
      },
      onClick: "history.back()"
    }]
  });
  if(req.pageType=="dialog") {
    tfp.width = req.dialogWidth.indexOf("px")>0 ? req.dialogWidth : req.dialogWidth+"px";
    tfp.height = req.dialogHeight.indexOf("px")>0 ? req.dialogHeight : req.dialogHeight+"px";
    //tfp.components[0].components[1].components[1].onClick = "closeCurDialog()";
  }

  fs.writeFileSync(filePath, JSON.stringify(tfp, null, "  "));

  var tbs = {
    name: req.table+"_Add",
    reqArgs: reqArgs,
    resArgs: [retArg],
    methods: [{
      name: "process",
      comment: "处理服务请求",
      args: [{
        name: "req",
        type: "object",
        comment: "服务请求对象"
      },{
        name: "res",
        type: "object",
        comment: "服务响应对象"
      }],
      statements: [statement]
    }]
  };

  tbsPath = utils.getPath("/app/"+tbsPath);

  fs.writeFileSync(tbsPath, JSON.stringify(tbs, null, "  "));

  this.end(res);
};