const system=require("../../../system");
const ServiceBase=require("../../sve.base");
class OrgService extends ServiceBase{
  constructor(){
     super("auth",ServiceBase.getDaoName(OrgService));
  }

  async delete(p,q,req){
    var self=this;
    var orgid=p.id;
    var uone=await this.db.models.user.findOne({where:{org_id:orgid}});
    if(!uone){
          //先检查是否组织下有人员存在
          return  this.db.transaction(async function (t) {
            var inst=await self.dao.model.findById(orgid);
            var parentid=inst.org_id;
            await inst.destroy({force:true,transaction:t});
            //删除组织对应的角色
            self.db.models.orgrole.destroy({where:{org_id:orgid},force:true,transaction:t});
            //查询出父元素
            var orgparent=await self.dao.model.findOne({
              order:[["code","ASC"]],
              where:{id:parentid},transaction:t,
              include:[
                {model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
                  {model:self.db.models.org,as:"orgs",order:[["code","ASC"]]}
                ]}
              ]});
            return orgparent.orgs;
      });
    }else{
      return null;
    }
  }
  async update(p,q,req){
    var self=this;
    var cmkey=p.comkey;//如果是来自租户界面的修改
    return  this.db.transaction(async function (t) {
      p.isLeaf=p.isPosition;
      var orgupdate=await self.dao.model.findOne({where:{id:p.id},transaction:t});
      await self.dao.model.update(p,{where:{id:p.id},transaction:t});
      var usersupdate=await self.db.models.user.findAll({where:{org_id:orgupdate.id}});
      //如果节点名称或岗位性质发生变化
     //if(p.name!=orgupdate.name || p.isMain!=orgupdate.isMain){
        for(var ud of usersupdate){
             ud.opath=p.orgpath;
             var n=p.orgpath.lastIndexOf("/");
             ud.ppath=p.isMain?p.orgpath.substring(0,n):p.orgpath;
             await ud.save({transaction:t});
        }
     //}
      if(p.Roles && !cmkey){//如果不是来自租户界面的修改
        var roles=await self.db.models.role.findAll({where:{id:{[self.db.Op.in]:p.Roles}}});
        await orgupdate.setRoles(roles,{transaction:t});
        //同时要给这个岗位下的user,更新角色 todo
        for(var ud of usersupdate){
          await ud.setRoles(roles,{transaction:t});
        }
      }
      var orgparent=await self.dao.model.findOne({
        order:[["code","ASC"]],
        where:{id:orgupdate.org_id},transaction:t,
        include:[
          {model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
            {model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
              {model:self.db.models.role,as:"roles",attributes:['id','code','name']},
            ]},
            {model:self.db.models.role,as:"roles",attributes:['id','code','name']},
          ]},
          {model:self.db.models.role,as:"roles",attributes:['id','code','name']},
        ]});
      return orgparent.orgs;
    });
  }
  async checkMainPosition(p,q,req){
    var orgmain=await this.dao.model.findOne({where:{org_id:p.org_id,isMain:true}});
    if(orgmain){
      return {"isHave":true};
    }else{
      return null;
    }
  }
  async  changePos(toorgid,uid){
    //查询出当前用户，设置当前用户的orgid为修改目标
    var self=this;
    return  this.db.transaction(async function (t) {
      var ufind=await self.db.models.user.findById(uid);
    
   
      var org=await self.dao.model.findOne({
        where:{id:toorgid},
        include:[
          {model:self.db.models.role,as:"roles"},
        ]});
        ufind.org_id=toorgid;
        ufind.opath=org.orgpath;
        if(org.isMain){//如果是主岗
          var n=org.orgpath.lastIndexOf("/");
          ufind.ppath=org.orgpath.substring(0,n);
         }else{
          ufind.ppath= org.orgpath;
         }
        await ufind.save({transaction:t});
        await ufind.setRoles(org.roles,{transaction:t});
        return ufind;
    });
    //查询出目标org,关联查询出角色

    //设置当前用户的角色

  }
  async create(p,q,req){
    var self=this;
    var cmkey=p.comkey;
 
    return  this.db.transaction(async function (t) {
      if(cmkey){
         var  tmpcompany =await self.db.models.company.findOne({where:{companykey:cmkey},transaction:t});
          p.company_id=tmpcompany.id;
       }
      var roles=await self.db.models.role.findAll({where:{id:{[self.db.Op.in]:p.Roles}}});
      p.isLeaf=p.isPosition;
      p.app_id=null;
      var orgnew=await self.dao.model.create(p,{transaction:t});
      if(roles && roles.length>0){
        await orgnew.setRoles(roles,{transaction:t});
      }
      var orgparent=await self.dao.model.findOne({
        order:[["code","ASC"]],
        where:{id:orgnew.org_id},transaction:t,
        include:[
          {model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
            {model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
              {model:self.db.models.role,as:"roles",attributes:['id','code','name']},
            ]},
            {model:self.db.models.role,as:"roles",attributes:['id','code','name']},
          ]},
          {model:self.db.models.role,as:"roles",attributes:['id','code','name']},
          
        ]});
      return orgparent.orgs;
    });
  }
  async findOrgById(id){
    var org=await this.dao.model.findOne({
      order:[["code","ASC"]],
      where:{id:id},
      include:[
        {model:this.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
          {model:this.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
            {model:this.db.models.role,as:"roles",attributes:['id','code','name']},
          ]},
          {model:this.db.models.role,as:"roles",attributes:['id','code','name']},
        ]},
        {model:this.db.models.role,as:"roles",attributes:['id','code','name']},
      ]});
      return org.orgs;
  }
  async initOrgs(company,appid){
    var self=this;
    return  this.db.transaction(async function (t) {
      var org=await self.dao.model.findOne({
        order:[["code","ASC"]],
        //where:{name:company.name,company_id:company.id,app_id:appid},transaction:t,
        where:{name:company.name,company_id:company.id},transaction:t,
        include:[
          {model:self.db.models.org,as:"orgs", order:[["code","ASC"]],include:[
            {model:self.db.models.org,as:"orgs",order:[["code","ASC"]],include:[
              {model:self.db.models.role,as:"roles",attributes:['id','code','name']},
            ]},
            {model:self.db.models.role,as:"roles",attributes:['id','code','name']},
          ]},
          {model:self.db.models.role,as:"roles",attributes:['id','code','name']},
        ]});
        if(org!=null){
           return org;
        }else{
         var root= await self.dao.model.create({
            code:"root"+company.id,
            name:company.name,
            isLeaf:false,
            isPostion:false,
            isMain:false,
            orgpath:"/",
            company_id:company.id,
            app_id:null,
          },{transaction:t});
            return root;
        }
    });
  }
}
module.exports=OrgService;
