IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID('[dbo].[mps_sync_architechture_depart_dingtalk]') AND type = 'P')
DROP PROCEDURE [dbo].[mps_sync_architechture_depart_dingtalk]
GO

-- =============================================                      
-- Author:  flobit                      
-- Create date: 2018年3月11日          
-- Description: 通用的同步员工的存储过程,默认情况是下是根据手机号来进行同步,如果不能满足需求则可以重新创建名为mps_syn_architechture_+cmpid的实现                      
-- =============================================        
CREATE PROC [dbo].[mps_sync_architechture_depart_dingtalk]              
@cmpid int        
as        
begin        
set nocount on    
--获取钉钉账号确定要同步的部门
declare @scope varchar(128) =''
select top 1 @scope = wx_code 
from ebs_kernel.dbo.pub_weixin 
where wx_cmpid=@cmpid and wx_type='ding'


declare @branch_count int =0
select  @branch_count=COUNT(*) from mps_groupbranch 
declare @cmp_dingid bigint = 0
select @cmp_dingid=bc_dingid from mps_groupbranch where bc_cmpid=@cmpid

--首先要根据dp_id更新dp_dingbcid
update mps_depart set dp_dingbcid=bc_dingid from mps_groupbranch 
where dp_bcid=bc_id and bc_cmpid=@cmpid and dp_fdpid=0

--根据部门的上下级关系,修正dp_dingbcid(实际上就是钉钉服务器上的父级ID)
update mps_depart set dp_dingbcid=(select dp_dingid from mps_depart _depart where _depart.dp_id=mps_depart.dp_fdpid)
where dp_cmpid=1 and dp_fdpid!=0

--比对部门信息                 
--1.删除                      
select distinct arch_id,
case when charindex('__待删除',arch_name) > 0
then arch_name
else arch_name+'__待删除' end arch_name                   
from mps_archsyn,mps_depart             
where 
(arch_id not in (select dp_dingid from mps_depart where dp_cmpid=@cmpid) 
and (arch_parentId > 1  or (@branch_count=1 and arch_parentId>0)))
or
(arch_id in (select dp_dingid from mps_depart where CHARINDEX(@scope,dp_loginscope)=0))
order by arch_id desc

--2.新增,如果是集团总部的时候,不知道ID,那么是否可以考虑将这个存储过程分成三个                  

--比对数据
select * from
(
select dp_id,dp_depart,dp_dingbcid dp_bcid                      
from mps_depart                      
where (dp_dingid not in (select arch_id from mps_archsyn where(arch_parentId > 1  or (@branch_count=1 and arch_parentId>0))) or dp_dingid is null) and dp_cmpid=@cmpid                      
and dp_depart!='' 
and CHARINDEX(@scope,dp_loginscope)>0
) as data
where dp_bcid!=0
--3.修改                      
select dp_dingid dp_id,dp_depart,dp_dingbcid dp_bcid 
from mps_depart,mps_archsyn                      
where dp_dingid=arch_id 
and ((arch_parentId > 1  or (@branch_count=1 and arch_parentId>0)) )and dp_cmpid = @cmpid and  (( dp_bcid!=0 and (arch_name != dp_depart or arch_parentId !=dp_dingbcid)) or (dp_bcid=0 and arch_name != dp_depart))
and CHARINDEX(@scope,dp_loginscope)>0
end