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

/**
 * 创建数据导出服务
 */
var CreateExportTBS = function() { 
  Service.call(this);
};

util.inherits(CreateExportTBS, Service);

module.exports = CreateExportTBS;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
CreateExportTBS.prototype.process =  function(req, res) {
  if(!req.path) {
    this.onLogicError(1, '请提供服务路径！');
    return;
  }
  if(!req.type) {
    this.onLogicError(2, '请提供服务类型！');
    return;
  }
  if(!req.model) {
    this.onLogicError(3, '请提供数据对象名称！');
    return;
  }
  if(!req.fields) {
    this.onLogicError(4, '请提供要查询的字段！');
    return;
  }
  if(!req.appCode) {
    this.onLogicError(4, '请提供应用代码！');
    return;
  }
  if(!req.fileName) {
    this.onLogicError(4, '请提供文件名称！');
    return;
  }
  var queryFields = [];
  var importFields = [];
  for(var i=0;i<req.fields.length;i++) {
    var field = req.fields[i];
    var queryField = {};
    for(var p in field) {
      if(p=="column") continue;
      queryField[p] = field[p];
    }
    queryFields.push(queryField);
    if(!field.column) field.column = field.name;
    importFields.push({
      name: field.name,
      column: field.column
    });
  }
  var filePath = utils.getPath(req.path);
  if(fs.existsSync(filePath)) {
    this.onLogicError(5, '文件已存在！');
    return;
  }
  if(!req.retArg) req.retArg = "data";
  var dbQuery = { 
    category: "db",
    type: "query",
    distinct: true,
    model: {
      name: req.model,
      path: "/app/"+req.proj+"/model/"+req.model+".tdm"
    },
    fields: queryFields,
    cbArg: "rows", 
    statements: [{
      category: "import-export",
      type: "excelExport",
      dataVarName: "rows",
      fields: importFields,
      appCode: req.appCode,
      fileName: req.fileName,
      statements: [{
        category: "common",
        type: "end"
      }]
    }]
  };
  if(req.orders) dbQuery.orders = req.orders;
  if(req.groups) dbQuery.groups = req.groups;
  if(req.where) dbQuery.where = req.where;
  if(req.count) dbQuery.count = parseInt(req.count);
  
  let tbsName = req.path.substr(req.path.lastIndexOf("/")+1);
  tbsName = tbsName.substr(0, tbsName.lastIndexOf("."));
  tbsName = tbsName.substr(0, 1).toUpperCase()+tbsName.substr(1);
  var tbs = {
    name: tbsName,
    comment: "导出"+req.model,
    reqArgs: [],
    methods: [{
      name: "process",
      comment: "处理服务请求",
      args: [{
        name: "req",
        type: "object",
        comment: "服务请求对象"
      },{
        name: "res",
        type: "object",
        comment: "服务响应对象"
      }],
      statements: [dbQuery]
    }]
  };
  if(req.reqArgs) tbs.reqArgs = req.reqArgs;

  if(req.type=="tbs") {
    fs.writeFileSync(filePath, JSON.stringify(tbs, null, "\t"));
    this.end(res);
  } else {
    var self = this;
    var compiler = new TBSCompiler();
    compiler.process({tbs: tbs}, {code: 0}, function(res2) {
      if(res2.code!=0) {
        self.onLogicError(6, "TBS文件编译失败："+res2.message);
        return;
      }
      fs.writeFileSync(filePath, res2.jsCode);
      self.end(res);
    });
  }
};