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

CREATE proc [dbo].[mps_update_weixin_bind] (@cmpid int,@account varchar(50),@pass varchar(50),@type varchar(10),@code varchar(64),@userid varchar(64))
as
begin

set nocount on
declare @data varchar(64)
declare @cu_id int
declare @count int

select @cu_id=cu_id
from mps_login
where cu_cmpid=@cmpid and (cu_account=@account or cu_mobile=@account) and cu_pass=@pass

if (@type = '-1')
begin
select @cu_id=cu_id
from mps_login
where cu_cmpid=@cmpid and (cu_account=@account or cu_mobile=@account) and cu_pass='d41d8cd98f00b204e9800998ecf8427e'

update mps_login set cu_pass=@pass
where cu_id=@cu_id 
select 'ok' result
return
end

if (@cu_id>0 and upper(@pass) = upper('d41d8cd98f00b204e9800998ecf8427e') and (exists (select 1 from ebs_kernel.dbo.pub_company where cmp_id=@cmpid and cmp_allowemptypass=1)))
begin
--declare @url varchar(1000)
--select @url = cmp_logwww from ebs_kernel.dbo.pub_company where cmp_id=@cmpid 
select 'reset' result
return;
end

if @cu_id is null 
begin
select '绑定失败,账号或密码不正确' result
return;
end
set @data=@code+'|'+@userid
--企业号绑定
if(@type='QYH')
begin
update mps_login set cu_qyh=@data
where cu_id=@cu_id and cu_qyh=''
if(@@ROWCOUNT=1)
begin
select '0'  result
return;
end
else 
begin
select '绑定失败，此账号已被其他用户绑定' result
return;
end
end
--公众号绑定
else if(@type='GZH')
begin
--防止一个账号绑定重复的微信公众号和openId
select @count=count(*) from mps_login
where 
cu_id=@cu_id
and (cu_gzh1 like @code+'%' 
or cu_gzh2 like @code+'%' 
or cu_gzh3 like @code+'%' 
or cu_gzh4 like @code+'%' 
or cu_gzh5 like @code+'%')
if(@count>0)
begin
select '绑定失败，该账号已经绑定过相同的微信号，不能重复绑定' result
return;
end
--尝试绑定第一个
update mps_login set cu_gzh1=@data
where cu_id=@cu_id and cu_gzh1='' 
if(@@ROWCOUNT=1)
begin
select '0' result 
return;
end
--尝试绑定第二个
update mps_login set cu_gzh2=@data
where cu_id=@cu_id and cu_gzh2=''
if(@@ROWCOUNT=1)
begin
select '0' result 
return;
end
--尝试绑定第三个
update mps_login set cu_gzh3=@data
where cu_id=@cu_id and cu_gzh3=''
if(@@ROWCOUNT=1)
begin
select '0' result 
return;
end
--尝试绑定第四个
update mps_login set cu_gzh4=@data
where cu_id=@cu_id and cu_gzh4=''
if(@@ROWCOUNT=1)
begin
select '0' result 
return;
end
--尝试绑定第五个
update mps_login set cu_gzh5=@data
where cu_id=@cu_id and cu_gzh5=''
if(@@ROWCOUNT=1)
begin
select '0' result 
return;
end
select '绑定失败，此账号已经达到可绑定微信公众号上限' result
return;
end else if (@type='DING')
begin
update mps_login set cu_ding=@data
where cu_id=@cu_id and cu_ding=''
if(@@ROWCOUNT=1)
begin
select '0'  result
return;
end
else 
begin
select '绑定失败，此账号已被其他钉钉用户绑定' result
return;
end
end else select '错误的账号类型' result
end