var Service = require('Service');
var utils = require('utils');
var DaoApp = require('../../dao/app');
var DaoOrgApp = require('../../dao/org_app');
var DaoVOrgApp = require('../../dao/vorg_app');
var DaoUser = require('../../dao/user');
var DaoAppAuth = require('../../dao/vapp_auth');
var util = require('util');
var fs= require('fs');

/**
 * 修改应用
 */
var Update = function() { 
  Service.call(this);
};

util.inherits(Update, Service);

module.exports = Update;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
Update.prototype.process =  function(req, res) {
  if(!req.id) {
    this.onLogicError(1, '请提供应用编号！');
    return;
  }

  if(!utils.isInt(req.id)) {
    this.onLogicError(2, '请提供正确的应用编号！');
    return;
  }
  req.id = parseInt(req.id);

  if(!req.name) {
    this.onLogicError(3, '请提供应用名称！');
    return;
  }

  /*if(!req.deploy) {
    this.onLogicError(3, '请提供应用部署方式！');
    return;
  }*/
  req.deploy = 'url';

  if(!req.terminal) {
    this.onLogicError(4, '请提供应用支持的终端类型！');
    return;
  }

  if(!req.version) {
    this.onLogicError(5, '请提供应用版本！');
    return;
  }

  if(!req.order_no) {
    this.onLogicError(6, '请提供序号！');
    return;
  }

  if(!utils.isInt(req.order_no)) {
    this.onLogicError(6, '请提供正确的序号！');
    return;
  }

  var url_phone = '';
  var url_pad = '';
  var url_pc = '';
  var url_web = '';
  var url_phone_detail = '';
  var url_pad_detail = '';
  var url_pc_detail = '';
  var url_web_detail = '';
  var pc_open_type = 0;
  var pc_show_on_sysbar = 0;
  if(req.deploy=='url') {
    if(req.terminal.indexOf('phone')>=0) {
      if(!req.url_phone) {
        this.onLogicError(7, '请提供手机版首页URL路径！');
        return;
      } else {
        url_phone = req.url_phone;
      }
      if(req.url_phone_detail) {
        url_phone_detail = req.url_phone_detail;
      }
    }
    if(req.terminal.indexOf('pad')>=0) {
      if(!req.url_pad) {
        this.onLogicError(7, '请提供平板版首页URL路径！');
        return;
      } else {
        url_pad = req.url_pad;
      }
      if(req.url_pad_detail) {
        url_pad_detail = req.url_pad_detail;
      }
    }
    if(req.terminal.indexOf('pc')>=0) {
      if(!req.url_pc) {
        this.onLogicError(7, '请提供电脑版首页URL路径！');
        return;
      } else {
        url_pc = req.url_pc;
      }
      if(req.url_pc_detail) {
        url_pc_detail = req.url_pc_detail;
      }
      if(req.pc_open_type) pc_open_type = req.pc_open_type;
      if(req.pc_show_on_sysbar) pc_show_on_sysbar = req.pc_show_on_sysbar;
    }
    if(req.terminal.indexOf('web')>=0) {
      if(!req.url_web) {
        this.onLogicError(7, '请提供Web版首页URL路径！');
        return;
      } else {
        url_web = req.url_web;
      }
      if(req.url_web_detail) {
        url_web_detail = req.url_web_detail;
      }
    }
  }

  var category_id = 0;
  if(req.categoryId) category_id = parseInt(req.categoryId);
  var order_no = parseInt(req.order_no);
  var description = '';
  if(req.description) description = req.description;
  
  var self = this;
  var daoApp = new DaoApp(this);
  var daoOrgApp = new DaoOrgApp(this);
  var daoVOrgApp = new DaoVOrgApp(this);
  daoVOrgApp.query({where: 'org_id='+req.session.orgId+' and app_id='+req.id}, function(rows) {
    if(rows.length==0) {
      self.onLogicError(8, '请提供正确的应用编号！');
      return;
    }
    if(rows[0].org_id!=rows[0].developer_id) {
      if(rows[0].category_id!=category_id || rows[0].order_no!=order_no) {
        req.appInfo = {};
        req.appInfo.category_id = category_id;
        req.appInfo.order_no = order_no;
        daoOrgApp.update(req.appInfo, {where: 'org_id='
          +req.session.orgId+' and app_id='+req.id}, function() {
            self.updateCache(req, res);
        });
      } else {
        self.end(res);
      }
    } else {
      daoVOrgApp.query({where: 'org_id=? and app_name=? and app_id<>?', 
        params:[req.session.orgId,req.name,req.id]}, function(rows2) {
        if(rows2.length>0) {
          self.onLogicError(9, '应用名称与其他应用重复！');
          return;
        }
        req.appInfo = {
          name: req.name , 
          deploy: req.deploy , 
          terminal: req.terminal, 
          version: req.version, 
          url_phone: url_phone,
          url_pad: url_pad,
          url_pc: url_pc,
          url_web: url_web,
          icon_code:req.app_icon.code,
          icon_path: '',
          url_phone_detail: url_phone_detail,
          url_pad_detail: url_pad_detail,
          url_pc_detail: url_pc_detail,
          url_web_detail: url_web_detail,
          titlebar_color:req.titlebar_color,
          msg_group:req.msg_group,
          get_badge_service:req.get_badge_service,
          pc_open_type: pc_open_type,
          pc_show_on_sysbar: pc_show_on_sysbar,
          description: description
        };
        daoApp.update(req.appInfo, {
            where: 'developer_id='+req.session.orgId+' and id='+req.id
          }, function(ret) {
            if(rows[0].category_id!=category_id || rows[0].order_no!=order_no) {
              req.appInfo.category_id = category_id;
              req.appInfo.order_no = order_no;
              daoOrgApp.update({category_id: category_id,order_no: order_no}, 
                {where: 'org_id='+req.session.orgId+' and app_id='+req.id}, function() {
                  self.updateCache(req, res);
              });
            } else {
              self.updateCache(req, res);
            }
        });
      });
    }
  }); 
};

Update.prototype.updateCache =  function(req, res) {
  var self = this;
  req.appInfo.id = parseInt(req.id);
  req.appInfo.app_name = req.appInfo.name;
  req.session.cache.set('app', req.id, req.appInfo, true, function(err) {
    if(err) {
      self.onError(err);
      return;
    }
    self.end(res);
    //self.getReceivers(req, res);
  });
};

Update.prototype.getReceivers =  function(req, res) {
  var self = this;
  var daoUser = new DaoUser(this);
  daoUser.query({fields:'id',where:'org_id='+req.session.orgId+' and '
    +'(id in (select owner_id from sys_app_auth where org_id='+req.session.orgId
    +' and app_id='+req.id+' and owner_type="user") or id in (select sys_dep_user.'
    +'user_id from sys_app_auth,sys_dep_user where sys_app_auth.org_id='+req.session.orgId
    +' and sys_app_auth.app_id='+req.id+' and sys_app_auth.owner_type="dep" '
    +' and sys_app_auth.owner_id=sys_dep_user.dep_id and sys_dep_user.org_id='
    +req.session.orgId+') or id in (select sys_role_user.user_id from sys_app_auth,'
    +'sys_role_user where sys_app_auth.org_id='+req.session.orgId+' and sys_app_auth.'
    +'app_id='+req.id+' and sys_app_auth.owner_type="role" and sys_app_auth.owner_id='
    +'sys_role_user.role_id and sys_role_user.org_id='+req.session.orgId+'))'},function(rows){
    if(rows.length==0) {
      self.end(res);
      return;
    }
    for(var i=0;i<rows.length;i++){
      if(req.receiversId != '') req.receiversId += ',';
      req.receiversId += rows[i].id;
    }
    var daoAppAuth = new DaoAppAuth(self);
    daoAppAuth.query({where:'org_id='+req.session.orgId+' and status=0 and app_id='
      +req.id, limit:1}, function(rowsApp) {
      if(rowsApp.length===0) {
        self.end(res);
        //self.onLogicError(1, '没有找到符合条件的应用信息！');
        return;
      }
      self.end(res);
      //self.sendMsg(req, res, rowsApp[0]);
    });
  });
};

Update.prototype.sendMsg =  function(req, res, app) {
  req.msgToSelf = true;
  req.appCode = 'sys';
  req.appDataType = 'updateApp';
  req.appDataId = req.id;
  req.content = {
    app_id: app.app_id,
    app_code: app.app_code,
    app_name: app.app_name,
    icon_path: app.icon_path,
    icon_code: app.icon_code,
    category_id: app.category_id,
    deploy: app.deploy,
    version: app.version,
    titlebar_color: app.titlebar_color,
    msg_group: app.msg_group,
    url_phone: app.url_phone,
    url_phone_detail: app.url_phone_detail,
    url_pad: app.url_pad,
    url_pad_detail: app.url_pad_detail,
    url_pc_detail: app.url_pc_detail,
    url_web_detail: app.url_web_detail,
    url_pc: app.url_pc,
    url_web: app.url_web,
    order_no: app.order_no,
    get_badge_service: app.get_badge_service,
    pc_show_on_sysbar: app.pc_show_on_sysbar,
    pc_open_type: app.pc_open_type
  };
  //this.sendAppMsg(req, res);
};