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

-- =============================================                  
-- Author:  flobit                  
-- Create date: 2018年3月11日      
-- Description: 通用的同步员工的存储过程,默认情况是下是根据手机号来进行同步,如果不能满足需求则可以重新创建名为mps_syn_architechture_+cmpid的实现                  
-- =============================================    
CREATE PROC [dbo].[mps_sync_architechture_user_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'
--更新login_role表中的部门记录
update mps_login_role 
set lgu_dingdpid=dp_dingid
from mps_depart where lgu_dpid=dp_id
 --比对员工信息             
 --假设是以cu_account作为编号        
 --1.删除                
 select user_id,user_name,user_mobile                
 from mps_usersyn                
 where user_mobile not in (select cu_mobile from mps_employee where cu_cmpid=@cmpid and cu_use=0 and len(cu_mobile)>=11)
 or user_mobile in(select cu_mobile from mps_employee where CHARINDEX(@scope,cu_loginscope)=0)
 --2.新增                
 select cu_account as user_id,cu_code,cu_name,cu_gender,cu_mobile,cu_dpids,cu_title              
 from mps_employee,(select cu_id as dps_cuid,STUFF(REPLACE(REPLACE(stuff((select distinct lgu_dingdpid as i from mps_login_role where lgu_cuid=cu_id order by lgu_dingdpid for xml path('')),1,0,''),'<i>',','),'</i>',''),1,1,'') as cu_dpids from mps_employee) as A       
 where cu_cmpid=@cmpid 
 and len(cu_mobile)>=11
 and cu_use=0
 and dps_cuid=cu_id 
 and ( cu_mobile not in (select user_mobile from mps_usersyn)) 
 and CHARINDEX(@scope,cu_loginscope)>0
 --3.修改                
 select distinct user_id ,cu_code,cu_name,cu_gender,cu_mobile,cu_dpids,cu_title               
 from mps_employee,mps_usersyn,
 (select cu_id as dps_cuid,STUFF(REPLACE(REPLACE(stuff((select distinct lgu_dingdpid as i from mps_login_role where lgu_cuid=cu_id order by lgu_dingdpid for xml path('')),1,0,''),'<i>',','),'</i>',''),1,1,'') as cu_dpids from mps_employee) as A                
 where cu_cmpid=@cmpid 
 and dps_cuid=cu_id 
 and cu_use=0
 and cu_mobile=user_mobile 
 and (user_code!=cu_code or user_name!=cu_name or cu_title!=user_position or cu_dpids!=user_dpids)                
 and CHARINDEX(@scope,cu_loginscope)>0
end