package com.goafanti.customer.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.ibatis.builder.BuilderException;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.goafanti.common.bo.Error;
import com.goafanti.common.bo.userDaysBo;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.ErrorConstants;
import com.goafanti.common.dao.AdminMapper;
import com.goafanti.common.dao.BusinessGlossoryMapper;
import com.goafanti.common.dao.BusinessProjectMapper;
import com.goafanti.common.dao.OrganizationAnnualReportMapper;
import com.goafanti.common.dao.OrganizationApplicationInfoMapper;
import com.goafanti.common.dao.OrganizationContactBookMapper;
import com.goafanti.common.dao.OrganizationIdentityMapper;
import com.goafanti.common.dao.OrganizationYearProjectMapper;
import com.goafanti.common.dao.UserBusinessMapper;
import com.goafanti.common.dao.UserFollowBusinessMapper;
import com.goafanti.common.dao.UserFollowMapper;
import com.goafanti.common.dao.UserIdentityMapper;
import com.goafanti.common.dao.UserLockReleaseMapper;
import com.goafanti.common.dao.UserMapper;
import com.goafanti.common.dao.UserTransferLogMapper;
import com.goafanti.common.enums.CustomerStatusFiled;
import com.goafanti.common.enums.DeleteStatus;
import com.goafanti.common.enums.IdentityProcess;
import com.goafanti.common.enums.UserLevel;
import com.goafanti.common.enums.UserLockReleaseStatus;
import com.goafanti.common.enums.UserType;
import com.goafanti.common.error.BusinessException;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.OrganizationApplicationInfo;
import com.goafanti.common.model.OrganizationContactBook;
import com.goafanti.common.model.OrganizationIdentity;
import com.goafanti.common.model.User;
import com.goafanti.common.model.UserBusiness;
import com.goafanti.common.model.UserFollow;
import com.goafanti.common.model.UserFollowBusiness;
import com.goafanti.common.model.UserIdentity;
import com.goafanti.common.model.UserLockRelease;
import com.goafanti.common.model.UserTransferLog;
import com.goafanti.common.utils.BeanUtilsExt;
import com.goafanti.common.utils.DateUtils;
import com.goafanti.common.utils.ExportExcelUtil;
import com.goafanti.common.utils.PasswordUtil;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.customer.bo.BusinessListBo;
import com.goafanti.customer.bo.BussinessFollowBo;
import com.goafanti.customer.bo.CustomerExcelBo;
import com.goafanti.customer.bo.CustomerListIn;
import com.goafanti.customer.bo.CustomerListOut;
import com.goafanti.customer.bo.CustomerOrganizationDetailBo;
import com.goafanti.customer.bo.CustomerPersonalDetailBo;
import com.goafanti.customer.bo.CustomerSimpleBo;
import com.goafanti.customer.bo.FollowBusinessBo;
import com.goafanti.customer.bo.FollowListBo;
import com.goafanti.customer.bo.LockingReleaseBo;
import com.goafanti.customer.bo.StatisticBo;
import com.goafanti.customer.bo.transferListBo;
import com.goafanti.customer.service.CustomerService;

@Service
public class CustomerServiceImpl extends BaseMybatisDao<UserMapper> implements CustomerService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserIdentityMapper userIdentityMapper;
	@Autowired
	private OrganizationIdentityMapper organizationIdentityMapper;
	@Autowired
	private OrganizationContactBookMapper organizationContactBookMapper;
	@Resource(name = "passwordUtil")
	private PasswordUtil	passwordUtil;
	@Value(value = "${user.receive.max}")
	private Integer USER_RECEIVE_MAX=null;
	@Value(value = "${user_remind_days}")
	private Integer USER_REMIND_DAYS=null;
	@Resource
	private UserFollowMapper userFollowMapper;
	@Resource
	private UserBusinessMapper userBusinessMapper;
	@Resource
	private UserFollowBusinessMapper userFollowBusinessMapper;
	@Resource
	private BusinessGlossoryMapper businessGlossoryMapper;
	@Resource
	private BusinessProjectMapper businessProjectMapper;
	@Resource
	private UserLockReleaseMapper userLockReleaseMapper;
	@Resource
	private AdminMapper	adminMapper;
	@Resource
	private OrganizationApplicationInfoMapper	organizationApplicationInfoMapper;
	@Resource
	private OrganizationAnnualReportMapper	organizationAnnualReportMapper;
	@Resource
	private OrganizationYearProjectMapper	organizationYearProjectMapper;
	@Resource
	private UserTransferLogMapper	userTransferLogMapper;
	@Value(value = "${upload.path}")
	private String 					uploadPath 			= null;
	
	
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CustomerListOut> listPrivatePersonalCustomer(CustomerListIn cli, Integer pageNo,Integer pageSize) {
		cli.setType(AFTConstants.USER_TYPE_PERSONAL);
		cli.setAid(TokenManager.getAdminId());
		Map<String,Object> params = disposeParams(cli);
		Pagination<CustomerListOut> list = (Pagination<CustomerListOut>) findPage("selectPrivatePersonalCustomerList","selectPrivatePersonalCustomerCount",params,pageNo,pageSize);
		List<CustomerListOut> tmpList = (List<CustomerListOut>)list.getList();
		setCustomerList(tmpList,0,null);
		list.setList(tmpList);
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CustomerListOut> listPublicPersonalCustomer(CustomerListIn cli, Integer pageNo,Integer pageSize) {
		cli.setType(AFTConstants.USER_TYPE_PERSONAL);
		Map<String,Object> params = disposeParams(cli);
		Pagination<CustomerListOut> list = (Pagination<CustomerListOut>) findPage("selectPublicPersonalCustomerList","selectPublicPersonalCustomerCount",params,pageNo,pageSize);
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CustomerListOut> listAllPersonalCustomer(CustomerListIn cli, Integer pageNo, Integer pageSize) {
		cli.setType(AFTConstants.USER_TYPE_PERSONAL);
		Map<String,Object> params = disposeParams(cli);
		Pagination<CustomerListOut> list = (Pagination<CustomerListOut>) findPage("selectPersonalCustomerList","selectPersonalCustomerCount",params,pageNo,pageSize);
		return list;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CustomerListOut> listAllManagePersonalCustomer(CustomerListIn cli, Integer pageNo, Integer pageSize) {
		cli.setType(AFTConstants.USER_TYPE_PERSONAL);
		cli.setShareType(String.valueOf(AFTConstants.USER_SHARE_PRIVATE));
		Map<String,Object> params = disposeParams(cli);
		Pagination<CustomerListOut> list = (Pagination<CustomerListOut>) findPage("selectManagePersonalCustomerList","selectManagePersonalCustomerCount",params,pageNo,pageSize);
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CustomerListOut> listPrivateOrganizationCustomer(CustomerListIn cli,Integer sort,Integer sortType, Integer type,
			Integer pageNo,Integer pageSize) {
		cli.setType(AFTConstants.USER_TYPE_ORGANIZATION);
		cli.setAid(TokenManager.getAdminId());
//		cli.setAid("1");
		cli.setShareType(String.valueOf(AFTConstants.USER_SHARE_PRIVATE));
		Map<String,Object> params = disposeParams(cli);
		params.put("sort", sort);
		params.put("sortType",sortType);
		List<String> alist=new ArrayList<>();
		if (type==0||TokenManager.hasRole(AFTConstants.SALESMAN)) {
			params.put("power", 0);
		}else if (TokenManager.hasRole(AFTConstants.SALESMAN_MANAGER)) {
			params.put("power", 1);
			alist=adminMapper.selectBySuperId(cli.getAid());
		}else if (TokenManager.hasRole(AFTConstants.SALESMAN_DIRECTOR)) {
			params.put("power", 2);
			alist=adminMapper.selectBySuperId(cli.getAid());
			List<String >alist2=new ArrayList<>();
			if (!alist.isEmpty()) {
				for (String string : alist) {
					alist2.addAll(adminMapper.selectBySuperId(string));
				}
				alist.addAll(alist2);
			}
		}else if (TokenManager.hasRole(AFTConstants.CED)) {
			params.put("power", 3);
		}
		params.put("alist", alist);
		Pagination<CustomerListOut> list = (Pagination<CustomerListOut>) findPage("selectPrivateOrganizationCustomerList","selectPrivateOrganizationCustomerCount",params,pageNo,pageSize);
		List<CustomerListOut> tmpList = (List<CustomerListOut>)list.getList();
		setCustomerList(tmpList,0,type);
		list.setList(tmpList);
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CustomerListOut> listPublicOrganizationCustomer(CustomerListIn cli, Integer pageNo,Integer pageSize) {
		cli.setType(AFTConstants.USER_TYPE_ORGANIZATION);
		cli.setShareType(String.valueOf(AFTConstants.USER_SHARE_PUBLIC));
		Map<String,Object> params = disposeParams(cli);
		Pagination<CustomerListOut> p = (Pagination<CustomerListOut>) findPage("selectPublicOrganizationCustomerList","selectPublicOrganizationCustomerCount",params,pageNo,pageSize);
		return p;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CustomerListOut> listAllOrganizationCustomer(CustomerListIn cli, Integer pageNo,Integer pageSize) {
		cli.setType(AFTConstants.USER_TYPE_ORGANIZATION);
		Map<String,Object> params = disposeParams(cli);
		if (TokenManager.hasRole(AFTConstants.SUPERADMIN)) {
			params.put("role", 1);
		}else {
			params.put("role", 0);
		}
		
		Pagination<CustomerListOut> p=(Pagination<CustomerListOut>) findPage("selectOrganizationCustomerList","selectOrganizationCustomerCount",params,pageNo,pageSize);
		List<CustomerListOut> l=(List<CustomerListOut>) p.getList();
		for (CustomerListOut c : l) {
			if (null!=c) {
				if(null!=c.getAid())c.setAdminName(adminMapper.selectNameByid(c.getAid()));
				if (null!=c.getShareType()&&c.getShareType().equals("1"))c.setAdminName("暂无");
				if(null!=c.getMid())c.setInformationMaintainer(adminMapper.selectNameByid(c.getMid()));
			}
		}
		return p; 
	}
	
	@Override
	public Pagination<CustomerListOut> listAllManageOrganizationCustomer(CustomerListIn cli, Integer pageNo,Integer pageSize) {
		cli.setType(AFTConstants.USER_TYPE_ORGANIZATION);
		cli.setShareType(String.valueOf(AFTConstants.USER_SHARE_PRIVATE));
		cli.setAid(TokenManager.getAdminId());
		Map<String,Object> params = disposeParams(cli);
		@SuppressWarnings("unchecked")
		Pagination<CustomerListOut> list = (Pagination<CustomerListOut>) findPage("selectManageOrganizationCustomerList","selectManageOrganizationCustomerCount",params,pageNo,pageSize);
		return list;
	}

	private Map<String,Object> disposeParams(CustomerListIn cli){
		Map<String,Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(cli.getType())) params.put("type", Integer.parseInt(cli.getType()));
		if(StringUtils.isNotBlank(cli.getShareType())) params.put("shareType", Integer.parseInt(cli.getShareType()));
		if(StringUtils.isNotBlank(cli.getName())) params.put("name", cli.getName());
		if(StringUtils.isNotBlank(cli.getProvince())) params.put("province", Integer.parseInt(cli.getProvince()));
		if(StringUtils.isNotBlank(cli.getCity())) params.put("city", Integer.parseInt(cli.getCity()));
		if(StringUtils.isNotBlank(cli.getArea())) params.put("area", Integer.parseInt(cli.getArea()));
		if(StringUtils.isNotBlank(cli.getStartDate())) params.put("startDate", cli.getStartDate());
		if(StringUtils.isNotBlank(cli.getEndDate())) params.put("endDate", cli.getEndDate());
		if(StringUtils.isNotBlank(cli.getIndustry())) params.put("industry", Integer.parseInt(cli.getIndustry()));
		if(StringUtils.isNotBlank(cli.getAid())) params.put("aid", cli.getAid());
		if(StringUtils.isNotBlank(cli.getDepartmentId())) params.put("departmentId", cli.getDepartmentId());
		if(StringUtils.isNotBlank(cli.getStatus())) params.put("status", Integer.parseInt(cli.getStatus()));
		if(StringUtils.isNotBlank(cli.getSocietyTag())) params.put("societyTag", cli.getSocietyTag());
		if(StringUtils.isNotBlank(cli.getFollow())) params.put("follow", cli.getFollow());
		if(StringUtils.isNotBlank(cli.getStartDate())) params.put("startDate", cli.getStartDate()+" 00:00:00");
		if(StringUtils.isNotBlank(cli.getEndDate())) params.put("endDate", cli.getEndDate()+" 23:59:59");
		if(null!=cli.getDataGrade()) params.put("dataGrade", cli.getDataGrade());
		if(null!=cli.getLevel())params.put("level", cli.getLevel());
		if(null!=cli.getSort())params.put("sort", cli.getSort());
		return params;
	}

	@Override
	public List<CustomerSimpleBo> findCustomerByName(String name) {		
		return userMapper.findCustomerByName(name);
	}

	@Override
	public int judgeCustomerByName(String name) {
		return userMapper.judgeCustomerByName(name);
	}

	@Override
	@Transactional
	public int addCustomer(String name, String contacts, String contactMobile, Integer type, Integer source,String societyTag, 
			Integer province ,Integer city, Integer area)  throws BusinessException{
		User user = new User();
		Date now = new Date();
		String uid = UUID.randomUUID().toString();
		String identifyId = UUID.randomUUID().toString();
		user.setId(uid);
		user.setIdentifyName(name);
		user.setSource(1);//客户来源为录入
		user.setNickname(name);
		user.setStatus(AFTConstants.USER_STATUS_NORMAL);
		user.setShareType(AFTConstants.NO);
		user.setAid(TokenManager.getAdminId());
//		user.setAid("1");
		user.setType(type);
		user.setLvl(UserLevel.CERTIFIED.getCode());
		user.setSocietyTag(societyTag);
		user.setCreateTime(now);
		user.setTransferTime(now);
		user.setUpdateTime(now);
		user.setMobile(contactMobile);
		user.setPassword(AFTConstants.INITIALPASSWORD);
		user.setInformationMaintainer(TokenManager.getAdminId());
		float f=0;
		user.setIntegrity(f);
//		user.setInformationMaintainer("1");
		passwordUtil.encryptPassword(user);
		if(type == UserType.PERSONAL.getCode()){
			if(userMapper.checkUser("", "", contactMobile, type,null,null).size()>0) throw new BusinessException(new Error(ErrorConstants.CUSTOMER_ALREADY_EXIST, name,""));
			UserIdentity ui = new UserIdentity();
			ui.setId(identifyId);
			ui.setUid(uid);
			ui.setContacts(contacts);
			ui.setContactMobile(contactMobile);
			ui.setUsername(name);
			ui.setProvince(province);
			ui.setCity(city);
			ui.setArea(area);
			ui.setExpert(AFTConstants.NO);
			ui.setCelebrity(AFTConstants.NO);
			ui.setInternational(AFTConstants.NO);
			ui.setAuditStatus(IdentityProcess.SUCCESS.getCode());//认证个人
			userIdentityMapper.insert(ui);
		}else if(type == UserType.ORGANIZATION.getCode()){
			if(userMapper.checkUser("",name,"",type,null,null).size()>0) throw new BusinessException(new Error(ErrorConstants.CUSTOMER_ALREADY_EXIST, name,""));
			// 创建企业认证信息
			OrganizationIdentity oi = new OrganizationIdentity();
			oi.setUnitName(name);
			oi.setId(identifyId);
			oi.setUid(uid);
			oi.setContacts(contacts);
			oi.setContactMobile(contactMobile);
			oi.setLocationProvince(province);
			oi.setLocationCity(city);
			oi.setLocationArea(area);
			oi.setHighTechZone(AFTConstants.NO);
			oi.setInternational(AFTConstants.NO);
			oi.setListed(AFTConstants.NO);
			oi.setAuditStatus(IdentityProcess.SUCCESS.getCode()); //实名企业
			organizationIdentityMapper.insert(oi);
		}
		userMapper.insert(user);	
		//新增企业联系人
		OrganizationContactBook cob = new OrganizationContactBook();
		cob.setAid(TokenManager.getAdminId());
		cob.setAname(adminMapper.selectByPrimaryKey(TokenManager.getAdminId()).getName());
		cob.setId(UUID.randomUUID().toString());
		cob.setUid(uid);
		cob.setName(contacts);
		cob.setMobile(contactMobile);
		cob.setMajor(AFTConstants.YES);
		organizationContactBookMapper.insert(cob);
		//新增锁定数据
		boolean isUs=false;
		if (uid.contains(",")) {
			isUs=true;
		}
		List<String> uList=new ArrayList<>();
		if (isUs) {
			uList=Arrays.asList(uid.split(","));
		}
		addUserLock(uid, TokenManager.getAdminId(), now,uList);
		return 1;
	}

	@Override
	public CustomerPersonalDetailBo findPersonalCustomerDetail(String uid) {
		return userMapper.findPersonalCustomerDetail(uid);
	}

	@Override
	public CustomerOrganizationDetailBo findOrganizationCustomerDetail(String uid) {
		return userMapper.findOrganizationCustomerDetail(uid);
	}

	@Override
	@Transactional
	public int updateOrganizationCustomer(CustomerOrganizationDetailBo bo) {
		OrganizationIdentity oi = new OrganizationIdentity();
		User user = new User();
		Date date =new Date();
		OrganizationApplicationInfo oa=new OrganizationApplicationInfo(); 
		try {
			BeanUtilsExt.copyProperties(oi, bo);
			user.setId(bo.getUid());
			user.setSocietyTag(bo.getSocietyTag());
			user.setCompanyLogoUrl(bo.getCompanyLogoUrl());
			user.setIntroduction(bo.getIntroduction());
			user.setUpdateTime(date);
			user.setInformationMaintainer(bo.getInformationMaintainer());
			user.setCoreTechnology(bo.getCoreTechnology());
			user.setAccomplishSituation(bo.getAccomplishSituation());
			user.setIntellectualProperty(bo.getIntellectualProperty());
			user.setCreditRating(bo.getCreditRating());
			user.setIntegrity(countIntegrity(bo));
			if (StringUtils.isNotBlank(bo.getPojectApplicationUrl())) {
				List<OrganizationApplicationInfo> l=organizationApplicationInfoMapper.selectByUid(bo.getUid());
				if(l.size()>0){
					oa=l.get(0);
					oa.setPojectApplicationUrl(bo.getPojectApplicationUrl());
					organizationApplicationInfoMapper.updateByPrimaryKey(oa);
				}else {
					oa.setId(UUID.randomUUID().toString());
					oa.setCreateTime(date);
					oa.setUid(bo.getUid());
					oa.setPojectApplicationUrl(bo.getPojectApplicationUrl());
					organizationApplicationInfoMapper.insert(oa);
				}
			}
		} catch (IllegalAccessException |InvocationTargetException e) {
			e.printStackTrace();
		} 
		organizationIdentityMapper.updateByPrimaryKey(oi);
		userMapper.updateByPrimaryKeySelective(user);
		return 1;
	}

	public  Float countIntegrity(CustomerOrganizationDetailBo bo) {
		//完整资料总数
		int max=10;
		int number=0;
		if(null!=bo.getIndustry())number+=1;
		if(bo.getLocationProvince()!=null)number+=1;
		if(StringUtils.isNotBlank(bo.getBusinessScope()))number+=1;
		if(bo.getRegisteredCapital()!=null)number+=1;
		if(StringUtils.isNotBlank(bo.getCooperationSituation()))number+=1; 
		if(StringUtils.isNotBlank(bo.getQualification()))number+=1; 
		if (organizationAnnualReportMapper.selectOrgAnnualCount(bo.getUid())>0)number+=1;
		if (organizationAnnualReportMapper.selectOrgYearProjectCount(bo.getUid())>0)number+=1;
		if(StringUtils.isNotBlank(bo.getCoreTechnology()))number+=1;
		if(bo.getCreditRating()!=null)number+=1;
		float f= (float)number/max;
		return f;
	}

	@Override
	public int updatePersonalCustomer(CustomerPersonalDetailBo bo) {
		UserIdentity ui = new UserIdentity();
		User user = new User();
		try {
			try {
				PropertyUtils.copyProperties(ui,bo);
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}
			user.setId(bo.getUid());
			user.setSocietyTag(bo.getSocietyTag());
			user.setHeadPortraitUrl(bo.getHeadPortraitUrl());
			user.setIntroduction(bo.getIntroduction());
			user.setUpdateTime(new Date());
			if(null==bo.getExpertAudit()&&bo.getExpert()==1)ui.setExpertAudit(2);
		} catch (InvocationTargetException | IllegalAccessException e) {
			e.printStackTrace();
		}
		userIdentityMapper.updateByPrimaryKeySelective(ui);
		userMapper.updateByPrimaryKeySelective(user);
		return 1;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<FollowListBo> listFollowHistory(Integer pageNo, Integer pageSize,String uid,String businessProjectId,Integer type) {
		Map<String, Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(uid))params.put("uid", uid);
		if(StringUtils.isNotBlank(businessProjectId)) params.put("businessProjectId", businessProjectId);
		Pagination<FollowListBo> page = (Pagination<FollowListBo>)findPage("selectFollowHistoryList","selectFollowHistoryCount",params, pageNo, pageSize);
		List<FollowListBo> list = (List<FollowListBo>)page.getList();
		for(FollowListBo bo : list){
			if(bo.getAid().equals(TokenManager.getAdminId())){
				
				bo.setReadOnly(AFTConstants.NO);
			}else{
				bo.setContactMobile("***");
				bo.setContacts("***");
				bo.setReadOnly(AFTConstants.YES);
			} 
			
		}
		page.setList(list);
		return page;
	}

	/**
	 * 推动指导已读
	 * @param uid
	 */
	@Override
	public int pushGuidance(String uid) {
		User u=userMapper.findUserAccountDetail(uid);
		if (u!=null &&u.getGuidance()!=0) {
		 return userMapper.pushUserGuidance(uid,2);
		}
		return 0;
	}

	@Override
	public User findUserAccountDetail(String uid) {
		
		return userMapper.findUserAccountDetail(uid);
	}

	@Override
	public int updateUserAccount(User user) {
		return userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public List<OrganizationContactBook> findCustomerContacts(String uid) {
		List<OrganizationContactBook> list=userMapper.findCustomerContacts(uid,TokenManager.getAdminId());
		return list; 
	}

	@Override
	@Transactional
	public int addFollow(FollowBusinessBo fbb) throws BusinessException{
		//更新跟进记录表
		SimpleDateFormat format = new SimpleDateFormat(AFTConstants.YYYYMMDDHHMMSS);
		UserFollow userFollow = new UserFollow();
		String followId = UUID.randomUUID().toString();
		userFollow.setId(followId);
		userFollow.setAid(TokenManager.getAdminId());
		userFollow.setContactType(Integer.parseInt(fbb.getContactType()));
		userFollow.setEffective(DeleteStatus.UNDELETE.getCode());
		try {
			userFollow.setCreateTime(format.parse(fbb.getFollowTime()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		userFollow.setOcbId(fbb.getOcbId());
		userFollow.setResult(fbb.getResult());
		userFollow.setUid(fbb.getUid());
		int followCount = userBusinessMapper.selectFollowCountByUAid(fbb.getUid(), TokenManager.getAdminId()) + 1;
		userFollow.setFollowCount(followCount);
		userFollowMapper.insert(userFollow);
		//判断是跟进还是签单
		int x=0;
		//检查客户锁定情况
		if(fbb.getUserBusinessList().size()>0){
			boolean isUserOwner = false;
			List<LockingReleaseBo> userLockedList = userMapper.selectLockedProject(fbb.getUid(), TokenManager.getAdminId(),null, 0, UserLockReleaseStatus.LOCKED.getCode());
			if(userLockedList.size() > 0){
				isUserOwner = true;
			}
			boolean isBusinessOwner = false;
			List<LockingReleaseBo> businessLockedList = null;
			String businessName= "";
			String ufbId = "";
			UserBusiness userBusiness = null;
			UserFollowBusiness userFollowBusiness = null;
			for(BusinessListBo ub: fbb.getUserBusinessList()){
				userBusiness = new UserBusiness();
				userFollowBusiness = new UserFollowBusiness();
				ufbId = UUID.randomUUID().toString();
				businessName = businessProjectMapper.selectByPrimaryKey(ub.getBusinessProjectId()).getBname();
				UserBusiness us=userBusinessMapper.selectByPrimaryKey(ub.getBusinessId());
				if(StringUtils.isNotBlank(ub.getBusinessId())){
					//更新业务表
					userBusiness.setId(ub.getBusinessId());
					if (us.getFollowSituation()==5) {//如果已签合同，则不允许变更
						if (ub.getCustomerStatus()!=us.getCustomerStatus()&& ub.getFollowSituation()!=5) {
							throw new BusinessException(new Error(ErrorConstants.BUSINESS_ALREADY_LOCKED,""));
						}
					}
					//检查业务锁定情况
					businessLockedList = userMapper.selectLockedProject(fbb.getUid(), null, ub.getBusinessProjectId(), 1, UserLockReleaseStatus.LOCKED.getCode());
					if(businessLockedList.size() > 0){
						for(LockingReleaseBo bo : businessLockedList){
							if(bo.getAid().equals(TokenManager.getAdminId())) isBusinessOwner = true;
						}
						if(!isBusinessOwner) throw new BusinessException(new Error(ErrorConstants.BUSINESS_ALREADY_LOCKED,businessName,""));
					}else{ 
						if(!isUserOwner) throw new BusinessException(new Error(ErrorConstants.CUSTOMER_ALREADY_LOCKED,businessName,""));
					}
//					if (us.getFollowSituation()!=5&&ub.getFollowSituation()==5) {//如果改成已签合同，则锁定业务
//						if (StringUtils.isNotBlank(fbb.getUid())) ub.setUid(fbb.getUid());
//						lockProject(ub);//锁定客户业务
//						x=1;
//					}		
					userBusiness.setBusinessProjectId(ub.getBusinessProjectId());
					userBusiness.setCustomerStatus(ub.getCustomerStatus());
					userBusiness.setFollowSituation(ub.getFollowSituation());
					userBusiness.setRemarks(ub.getRemarks());
					userBusiness.setUid(fbb.getUid());
					try {
						userBusiness.setUpdateTime(format.parse(fbb.getFollowTime()));
					} catch (ParseException e) {
						e.printStackTrace();
					}
					userBusiness.setAid(TokenManager.getAdminId());
					userBusinessMapper.updateByPrimaryKeySelective(userBusiness);
					//更新业务中间表
					userFollowBusiness.setBusinessId(ub.getBusinessProjectId());
					userFollowBusiness.setCustomerStatus(ub.getCustomerStatus());
					userFollowBusiness.setFollowSituation(ub.getFollowSituation());
					userFollowBusiness.setId(ufbId);
					userFollowBusiness.setFollowId(followId);
					userFollowBusiness.setRemarks(ub.getRemarks());
					userFollowBusiness.setBusinessProjectId(ub.getBusinessProjectId());
					userFollowBusinessMapper.insert(userFollowBusiness);
				}else{
					//检查业务锁定情况
					businessLockedList = userMapper.selectLockedProject(fbb.getUid(), null, ub.getBusinessProjectId(), 1, UserLockReleaseStatus.LOCKED.getCode());
					if(businessLockedList.size() > 0){
						for(LockingReleaseBo bo : businessLockedList){
							if(bo.getAid().equals(TokenManager.getAdminId())) isBusinessOwner = true;
						}
						if(!isBusinessOwner) throw new BusinessException(new Error(ErrorConstants.BUSINESS_ALREADY_LOCKED,businessName,""));
					}else{ 
						if(!isUserOwner) throw new BusinessException(new Error(ErrorConstants.CUSTOMER_ALREADY_LOCKED,businessName,""));
					}
					
					if(userBusinessMapper.judgeBusiness(fbb.getUid(), ub.getBusinessProjectId(), "")>0){
						throw new BusinessException(new Error(ErrorConstants.BUSINESS_ALREADY_EXIST,businessName,""));
					}
//					if (ub.getFollowSituation()==5) {//如果改成已签合同，则锁定业务
//						if (StringUtils.isNotBlank(fbb.getUid())) ub.setUid(fbb.getUid());
//						lockProject(ub);//锁定客户业务
//						x=1;
//					}
					String ubId = UUID.randomUUID().toString();
					//更新业务表
					userBusiness.setId(ubId);
					userBusiness.setBusinessProjectId(ub.getBusinessProjectId());
					try {
						userBusiness.setCreateTime(format.parse(fbb.getFollowTime()));
						userBusiness.setUpdateTime(format.parse(fbb.getFollowTime()));
					} catch (ParseException e) {
						e.printStackTrace();
					}
					userBusiness.setCustomerStatus(ub.getCustomerStatus());
					userBusiness.setFollowSituation(ub.getFollowSituation());
					userBusiness.setUid(fbb.getUid());
					userBusiness.setAid(TokenManager.getAdminId());
					userBusiness.setRemarks(ub.getRemarks());
					userBusinessMapper.insert(userBusiness);	
					//更新业务中间表
					userFollowBusiness.setBusinessId(ubId);
					userFollowBusiness.setCustomerStatus(ub.getCustomerStatus());
					userFollowBusiness.setFollowSituation(ub.getFollowSituation());
					userFollowBusiness.setId(ufbId);
					userFollowBusiness.setFollowId(followId);
					userFollowBusiness.setRemarks(ub.getRemarks());
					userFollowBusiness.setBusinessProjectId(ub.getBusinessProjectId());
					userFollowBusinessMapper.insert(userFollowBusiness);
				}
				
			}
		}
		followProject(fbb.getUid(),x);
		return 1;
	}

	/**
	 * 跟进更新用户中间表
	 * @param ub
	 */
	private void followProject(String uid,int x) {
		Date date =new Date();
		String aid=TokenManager.getAdminId();
		if (x==0) {
			if (userLockReleaseMapper.updateUserMid(uid,aid,date,null)<1) {
				userLockReleaseMapper.insertUserMid(uid,aid,date,null);
			}
		}else {
			if (userLockReleaseMapper.updateUserMid(uid,aid,date,date)<1) {
				userLockReleaseMapper.insertUserMid(uid,aid,date,date);
			}
		}
	}
	
	@SuppressWarnings("unused")
	private void releaseProject(List<LockingReleaseBo> businessLockedList) {
		if(businessLockedList != null && businessLockedList.size()>0){
			UserLockRelease ulr = null;
			for(LockingReleaseBo bo : businessLockedList){
				ulr = new UserLockRelease();
				ulr.setId(bo.getId());
				ulr.setStatus(UserLockReleaseStatus.RELEASE.getCode());
				userLockReleaseMapper.updateByPrimaryKeySelective(ulr);
			}
			
		}
	
		
	}

	@Override
	public FollowBusinessBo findFollowById(String followId) {
		
		return userMapper.findFollowById(followId);
	}

	@Override
	public List<BusinessListBo> findBusinessByFollowId(String followId) {
		return userMapper.findBusinessByFollowId(followId);
	}

	@Override
	@Transactional
	public int updateFollow(FollowBusinessBo fbb) throws BusinessException{
		UserFollow userFollow  = new UserFollow();
		SimpleDateFormat format = new SimpleDateFormat(AFTConstants.YYYYMMDDHHMMSS);
		userFollow.setId(fbb.getFollowId());
		if(StringUtils.isNotBlank(fbb.getOcbId())) userFollow.setOcbId(fbb.getOcbId());
		userFollow.setResult(fbb.getResult());
		userFollow.setContactType(Integer.parseInt(fbb.getContactType()));
		userFollowMapper.updateByPrimaryKeySelective(userFollow); //修改拜访记录表
		if(fbb.getUserBusinessList().size()>0){
			//检查客户锁定情况
			boolean isUserOwner = false;
			List<LockingReleaseBo> userLockedList = userMapper.selectLockedProject(fbb.getUid(), TokenManager.getAdminId(),null, 0, UserLockReleaseStatus.LOCKED.getCode());
			if(userLockedList.size() > 0){
				isUserOwner = true;
			}
			boolean isBusinessOwner = false;	
			List<LockingReleaseBo> businessLockedList = null;
			String businessName= "";
			UserFollowBusiness userFollowBusiness = null;
			for(BusinessListBo ub: fbb.getUserBusinessList()){
				userFollowBusiness = new UserFollowBusiness();
				businessName = businessProjectMapper.selectByPrimaryKey(ub.getBusinessProjectId()).getBname();
				if(StringUtils.isNotBlank(ub.getUfbId())){
					userFollowBusiness.setId(ub.getUfbId());
					userFollowBusiness.setFollowSituation(ub.getFollowSituation());
					userFollowBusiness.setCustomerStatus(ub.getCustomerStatus());
					userFollowBusiness.setRemarks(ub.getRemarks());
					userFollowBusinessMapper.updateByPrimaryKeySelective(userFollowBusiness); //修改拜访记录中间表
				}else{
					//检查业务锁定情况
					businessLockedList = userMapper.selectLockedProject(fbb.getUid(), null,ub.getBusinessProjectId(), 1, UserLockReleaseStatus.LOCKED.getCode());
					if(businessLockedList.size() > 0){
						for(LockingReleaseBo bo : businessLockedList){
							if(bo.getAid().equals(TokenManager.getAdminId())) isBusinessOwner = true;
						}
						if(!isBusinessOwner) throw new BusinessException(new Error(ErrorConstants.BUSINESS_ALREADY_LOCKED,businessName,""));
					}else{
						if(!isUserOwner) throw new BusinessException(new Error(ErrorConstants.CUSTOMER_ALREADY_LOCKED,businessName,""));
					}
					if(userBusinessMapper.judgeBusiness(fbb.getUid(), ub.getBusinessProjectId(), "")>0){
						throw new BusinessException(new Error(ErrorConstants.BUSINESS_ALREADY_EXIST,businessName,""));
					}
					String ubId = UUID.randomUUID().toString();		
					UserBusiness userBusiness = new UserBusiness();
					//更新业务表
					userBusiness.setId(ubId);
					userBusiness.setBusinessProjectId(ub.getBusinessProjectId());
					try {
						userBusiness.setCreateTime(format.parse(fbb.getFollowTime()));
						userBusiness.setUpdateTime(format.parse(fbb.getFollowTime()));
					} catch (ParseException e) {
						e.printStackTrace();
					}
					userBusiness.setCustomerStatus(ub.getCustomerStatus());
					userBusiness.setFollowSituation(ub.getFollowSituation());
					userBusiness.setUid(fbb.getUid());
					userBusiness.setAid(TokenManager.getAdminId());
					userBusinessMapper.insert(userBusiness);	
					//更新业务中间表
					String ufbId = UUID.randomUUID().toString();
					userFollowBusiness.setId(ufbId);
					userFollowBusiness.setFollowId(fbb.getFollowId());
					userFollowBusiness.setBusinessId(ubId);
					userFollowBusiness.setCustomerStatus(ub.getCustomerStatus());
					userFollowBusiness.setFollowSituation(ub.getFollowSituation());
					userFollowBusiness.setRemarks(ub.getRemarks());
					userFollowBusiness.setBusinessProjectId(ub.getBusinessProjectId());
					userFollowBusinessMapper.insert(userFollowBusiness);
				}		
			}
		}
		return 1;
	}

	@Override
	public Set<OrganizationContactBook> findAllContacts(String uid) {
		Set<OrganizationContactBook> result = new HashSet<OrganizationContactBook>();
		result.addAll(userMapper.findAllContacts(uid));
		return result;
	}

	@Override
	public int updateCustomerContacts(List<OrganizationContactBook> ocbList,String uid) {
		if(ocbList.size()>0){
			OrganizationContactBook ocb = null;
			for(OrganizationContactBook item: ocbList){
				if(item!=null&&item.getMajor()!=null&&item.getMajor()==1) {
					//改变用户原本的联系人
					OrganizationIdentity oi=new OrganizationIdentity();
					oi.setContacts(item.getName());
					oi.setContactMobile(item.getMobile());
					oi.setUid(uid);
					organizationIdentityMapper.updateServiceByUid(oi);
				}
				ocb = new OrganizationContactBook();
				try {
					BeanUtils.copyProperties(ocb, item);
					if(StringUtils.isBlank(ocb.getId())){
						ocb.setId(UUID.randomUUID().toString());
						ocb.setUid(uid);
						ocb.setAid(TokenManager.getAdminId());
						Admin ad=adminMapper.selectByPrimaryKey(TokenManager.getAdminId());
						ocb.setAname(ad.getName());
						organizationContactBookMapper.insert(ocb);
					}else{
						organizationContactBookMapper.updateByPrimaryKeySelective(ocb);
					}
				} catch (IllegalAccessException | InvocationTargetException e) {
					e.printStackTrace();
				}
			}		
		}
		return 1;
	}

	@Override
	public int deleteFollow(String followId) {
		UserFollow uf = new UserFollow();
		List<BusinessListBo> list= userMapper.findBusinessByFollowId(followId);
		for (BusinessListBo b : list) {
			if(b.getFollowSituation()==5)throw new BusinessException(new Error(ErrorConstants.BUSINESS_ALREADY_LOCKED,""));;
		}
		uf.setId(followId);
		uf.setEffective(DeleteStatus.DELETED.getCode());
		return userFollowMapper.updateByPrimaryKeySelective(uf);
	}

	@Override
	public void checkCustomer(Set<CustomerExcelBo> boSet, Set<Integer> existRows, Set<Integer> filterRows) {
		List<User> list = null;
		CustomerExcelBo[] bos = (CustomerExcelBo[])boSet.toArray(new CustomerExcelBo[] {});
		for (int i=0;i<bos.length;i++) {
			CustomerExcelBo bo = bos[i];
			CustomerExcelBo ceb = null;
			for(int j=0;j<i;j++){
				ceb = bos[j];
				if(bo.getCustomerType().equals(AFTConstants.USER_TYPE_PERSONAL)){ //个人
					if(ceb.getMobile().equals(bo.getMobile()) && ceb.getCustomerType().equals(bo.getCustomerType())){
						bo.setUid(ceb.getUid());
						bo.setNewData(false);
						filterRows.add(bo.getRowNumber());
						break;
					}
				}else if(bo.getCustomerType().equals(AFTConstants.USER_TYPE_ORGANIZATION)){ //单位
					if(ceb.getIdentifyName().equals(bo.getIdentifyName()) && ceb.getCustomerType().equals(bo.getCustomerType())){
						bo.setUid(ceb.getUid());
						bo.setNewData(false);
						filterRows.add(bo.getRowNumber());
						break;
					}
				}
			}
			if(StringUtils.isBlank(bo.getUid())){ //是否已经存在
				if(bo.getCustomerType().equals(AFTConstants.USER_TYPE_PERSONAL)){
					list = userMapper.checkUser("", "", bo.getMobile(), Integer.parseInt(bo.getCustomerType()),null,null);
				}else if(bo.getCustomerType().equals(AFTConstants.USER_TYPE_ORGANIZATION)){
					list = userMapper.checkUser("", bo.getIdentifyName(), "", Integer.parseInt(bo.getCustomerType()),null,null);
				}			
				if (list.size() > 0) {
					bo.setUid(list.get(0).getId());
					bo.setNewData(false);
					List<LockingReleaseBo> businessLockedList = userMapper.selectLockedProject(bo.getUid(), null,bo.getBusinessProjectId(), 1, UserLockReleaseStatus.LOCKED.getCode());
					if(businessLockedList.size() > 0){
						existRows.add(bo.getRowNumber());
					}
				}else{
					bo.setUid(UUID.randomUUID().toString());
					bo.setNewData(true);
				}
			}else{
				List<LockingReleaseBo> businessLockedList = userMapper.selectLockedProject(bo.getUid(), null,bo.getBusinessProjectId(), 1, UserLockReleaseStatus.LOCKED.getCode());
				if(businessLockedList.size() > 0){
					existRows.add(bo.getRowNumber());
				}
			}	
		}
	}

	@Override
	@Transactional
	public int saveUploadData(Set<CustomerExcelBo> boSet) {
		Date now = new Date();
		String uid = "";
		for(CustomerExcelBo bo : boSet){
			uid = bo.getUid();
			if(bo.isNewData()){ //新建客户
				createUser(bo, uid, now);
				createIdentity(bo, bo.getCustomerType(), uid);
				createBusiness(bo, uid, now);
				createContacts(bo, uid);	
			}else{ //新建业务
				createBusiness(bo, uid, now);
				if(organizationContactBookMapper.checkContacts(uid, bo.getMobile(), TokenManager.getAdminId())<=0){
					createContacts(bo, uid);
				}
			}
		}
		return 1;
	}
	
	private void createUser(CustomerExcelBo bo,String uid,Date now){
		User user = new User();
		user.setId(uid);
		user.setIdentifyName(bo.getIdentifyName());
		user.setSource(AFTConstants.USER_SOURCE_CREATE);
		user.setNickname(bo.getIdentifyName());
		user.setStatus(AFTConstants.USER_STATUS_NORMAL);
		user.setShareType(AFTConstants.USER_SHARE_PRIVATE);
		user.setAid(TokenManager.getAdminId());
		user.setType(Integer.parseInt(bo.getCustomerType()));
		user.setLvl(UserLevel.CERTIFIED.getCode());
		user.setCreateTime(now);
		user.setUpdateTime(now);
		user.setMobile(bo.getMobile());
		user.setPassword(AFTConstants.INITIALPASSWORD);
		passwordUtil.encryptPassword(user);
		userMapper.insert(user);	
	}
	
	private void createIdentity(CustomerExcelBo bo,String type,String uid){
		String identifyId = UUID.randomUUID().toString();
		if(type.equals(AFTConstants.USER_TYPE_PERSONAL)){
			//新增个人认证信息
			UserIdentity ui = new UserIdentity();
			ui.setId(identifyId);
			ui.setUid(uid);
			ui.setContacts(bo.getContacts());
			ui.setContactMobile(bo.getMobile());
			ui.setUsername(bo.getIdentifyName());
			ui.setExpert(AFTConstants.NO);
			ui.setCelebrity(AFTConstants.NO);
			ui.setInternational(AFTConstants.NO);
			ui.setAuditStatus(5);
			userIdentityMapper.insert(ui);
		}else if(type.equals(AFTConstants.USER_TYPE_ORGANIZATION)){
			// 创建企业认证信息
			OrganizationIdentity oi = new OrganizationIdentity();
			oi.setId(identifyId);
			oi.setUnitName(bo.getIdentifyName());
			oi.setUid(uid);
			oi.setContacts(bo.getContacts());
			oi.setContactMobile(bo.getMobile());
			oi.setHighTechZone(AFTConstants.NO);
			oi.setInternational(AFTConstants.NO);
			oi.setListed(AFTConstants.NO);
			oi.setAuditStatus(5); //实名企业
			organizationIdentityMapper.insert(oi);
		}
	}
	
	private void createContacts(CustomerExcelBo bo,String uid){
		//新增企业联系人
		OrganizationContactBook cob = new OrganizationContactBook();
		cob.setAid(TokenManager.getAdminId());
		cob.setId(UUID.randomUUID().toString());
		cob.setUid(uid);
		cob.setName(bo.getContacts());
		cob.setMobile(bo.getMobile());
		cob.setMajor(AFTConstants.NO);
		organizationContactBookMapper.insert(cob);
	}
	
	private void createBusiness(CustomerExcelBo bo,String uid,Date now){
		//新增业务
		UserBusiness ub = new UserBusiness();
		ub.setId(UUID.randomUUID().toString());
		ub.setAid(TokenManager.getAdminId());
		ub.setBusinessProjectId(bo.getBusinessProjectId());
		ub.setUid(uid);
		ub.setCreateTime(now);
		ub.setUpdateTime(now);
		ub.setCustomerStatus(Integer.parseInt(bo.getCustomerStatus()));
		ub.setFollowSituation(Integer.parseInt(bo.getFollowSituation()));
		userBusinessMapper.insert(ub);
	}

	@Override
	public int updateByOperatorType(String uid,String oldAid, Integer operatorType,Object... params) {
		User user = new User();
		Date now = new Date();
		//是否多个客户
		boolean isUs=false;
		if (uid.contains(",")) {
			isUs=true;
		}
		List<String> uList=new ArrayList<>();
		if (isUs) {
			uList=Arrays.asList(uid.split(","));
		}
		user.setId(uid);
		int flag = 0;
		if(AFTConstants.USER_RECEIVE.equals(operatorType)){
			if(userMapper.UserReceiveCount(TokenManager.getAdminId())>=USER_RECEIVE_MAX)
				throw new BusinessException(new Error(ErrorConstants.CUSTOM_EREXCESS,""+USER_RECEIVE_MAX,""));
			user.setAid(TokenManager.getAdminId());
			user.setShareType(AFTConstants.USER_SHARE_PRIVATE);
			user.setInformationMaintainer(TokenManager.getAdminId());
			user.setSource(2);//客户来源设置为领取
			user.setTransferTime(now);
			flag = addUserLock(uid,TokenManager.getAdminId(),now,uList); //指定用户锁定客户
			addUserTransferLog(uid,TokenManager.getAdminId(),1,null,now,uList);
			if(flag <= 0) throw new BusinessException(new Error(ErrorConstants.CUSTOMER_ALREADY_RECEIVE,""));
		}else if(AFTConstants.USER_TRANSFER_TO_OTHER.equals(operatorType)
					||AFTConstants.SIGN_USER_TRANSFER_TO_OTHER==operatorType){
			if(!isUs) {
				user.setAid(String.valueOf(params[0]));
				user.setSource(3);//客户来源设置为转交
				if (AFTConstants.USER_TRANSFER_TO_OTHER==operatorType) {
					//查询这个客户是否是登陆人的客户
					if(userMapper.getAidAndUser(uid,TokenManager.getAdminId())<=0)throw new BusinessException(new Error("请勿非法操作！","请勿非法操作！"));
					flag = updateUserLock(uid,oldAid,UserLockReleaseStatus.LOCKED.getCode(),UserLockReleaseStatus.RELEASE.getCode()); //原用户释放客户
					if(flag > 0 ) flag = addUserLock(uid,String.valueOf(params[0]),now,uList); //指定用户锁定客户
					if(flag <= 0) throw new BusinessException(new Error(ErrorConstants.CUSTOMER_TRANSFER_FAIL,""));
				}
				
			}else {
				for (String us : uList) {
					if(userMapper.getAidAndUser(us,TokenManager.getAdminId())<=0)throw new BusinessException(new Error("请勿非法操作！","请勿非法操作！"));
				}
				if (AFTConstants.USER_TRANSFER_TO_OTHER==operatorType) {
				flag = updateUsersLock(uList,oldAid,UserLockReleaseStatus.LOCKED.getCode(),UserLockReleaseStatus.RELEASE.getCode()); //原用户释放客户
				if(flag > 0 ) flag = addUserLock(uid,String.valueOf(params[0]),now,uList); //指定用户锁定客户
				if(flag <= 0) throw new BusinessException(new Error(ErrorConstants.CUSTOMER_TRANSFER_FAIL,""));
				}
			}
			Integer type=2;
			if (AFTConstants.SIGN_USER_TRANSFER_TO_OTHER==operatorType)type=7; 
				
			addUserTransferLog(uid,String.valueOf(params[0]),type,null,now,uList);
		}
		if (isUs) {
			if (AFTConstants.USER_RECEIVE==operatorType) {
				userMapper.updateList(String.valueOf(params[0]),null,3,null,2,uList);
			} else {
				userMapper.updateList(String.valueOf(params[0]),null,3,null,null,uList);
			}
		} else {
			userMapper.updateByPrimaryKeySelective(user);
		}
		return 1; 
	}

	/**
	 * 
	 * @param uid	客户id
	 * @param aid  接受者id
	 * @param lockTime 时间
	 * @param uList 是不是多人客户
	 * @return
	 */
	private int addUserLock(String uid,String aid ,Date lockTime, List<String> uList){
		if (uList.isEmpty()) {
			UserLockRelease ulr = new UserLockRelease();
			ulr.setId(UUID.randomUUID().toString());
			ulr.setType(0);
			ulr.setAid(aid);
			ulr.setLockTime(lockTime);
			ulr.setStatus(UserLockReleaseStatus.LOCKED.getCode());
			ulr.setUid(uid);
			userLockReleaseMapper.insert(ulr);
		}else {
			List<UserLockRelease> ulrList=new ArrayList<>();
			for (String s : uList) {
				UserLockRelease ulr = new UserLockRelease();
				ulr.setId(UUID.randomUUID().toString());
				ulr.setType(0);
				ulr.setAid(aid);
				ulr.setLockTime(lockTime);
				ulr.setStatus(UserLockReleaseStatus.LOCKED.getCode());
				ulr.setUid(s);
				ulrList.add(ulr);
			}
			 userLockReleaseMapper.insertList(ulrList);
		}
		return 1;
	}
	/**
	 * 
	 * @param type  0录入  1领取 2转交客户 3转交业务
	 */
	private void addUserTransferLog(String uid,String aid,Integer type,String pid,Date lockTime, List<String> uList) {
		if(uList.isEmpty()) {
			UserTransferLog utl=new UserTransferLog();
			if(type==0||type==1) utl.setAid(aid);
			else if(type==2||type==3) {
				utl.setAid(TokenManager.getAdminId());
				utl.setTakeAid(aid);
			}
			if(type==3)utl.setPid(pid);
			utl.setType(type);
			utl.setCreateTime(lockTime);
			utl.setUid(uid);
			userTransferLogMapper.insertSelective(utl);
		}else {
			List<String> ulist=Arrays.asList(uid.split(","));
			List<UserTransferLog> utlList=new ArrayList<>();
			for (String string : ulist) {
				UserTransferLog utl=new UserTransferLog();
				if(type==0||type==1) utl.setAid(string);
				else if(type==2||type==3) {
					utl.setAid(TokenManager.getAdminId());
					utl.setTakeAid(string);
				}
				if(type==3)utl.setPid(pid);
				utl.setCreateTime(lockTime);
				utl.setUid(uid);
				utl.setType(type);
				utlList.add(utl);
			}
			userTransferLogMapper.insertList(utlList);
		}
	}

	

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<StatisticBo> customerStatistics(Date sDate, Date eDate, String depNo, String businessGlossoryId, Integer pageNo, Integer pageSize) {
		Map<String,Object> params = new HashMap<String,Object>();
		if(null != sDate) params.put("sDate", sDate);
		if(null != eDate) params.put("eDate", eDate);
		if(StringUtils.isNotBlank(depNo)) params.put("depNo", depNo);
		if(StringUtils.isNotBlank(businessGlossoryId)) params.put("businessGlossoryId", businessGlossoryId);
		Pagination<StatisticBo> page = (Pagination<StatisticBo>)findPage("customerStatisticsList", "customerStatisticsCount", params, pageNo, pageSize);
		return page;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<StatisticBo> businessStatistic(Date sDate, Date eDate,String depNo, String businessGlossoryId,Integer pageNo, Integer pageSize) {
		Map<String,Object> params = new HashMap<String,Object>();
		if(null != sDate) params.put("sDate", sDate);
		if(null != eDate) params.put("eDate", eDate);
		if(StringUtils.isNotBlank(depNo)) params.put("depNo", depNo);
		if(StringUtils.isNotBlank(businessGlossoryId)) params.put("businessGlossoryId", businessGlossoryId);
		Pagination<StatisticBo> page = (Pagination<StatisticBo>)findPage("businessStatisticList", "businessStatisticCount", params, pageNo, pageSize);
		return page;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<StatisticBo> followStatistic(Date sDate, Date eDate, String depNo, Integer pageNo, Integer pageSize) {
		Map<String,Object> params = new HashMap<String,Object>();
		if(null != sDate) params.put("sDate", sDate);
		if(null != eDate) params.put("eDate", eDate);
		if(StringUtils.isNotBlank(depNo)) params.put("depNo", depNo);
		Pagination<StatisticBo> page = (Pagination<StatisticBo>)findPage("followStatisticList", "followStatisticCount", params, pageNo, pageSize);
		return page;
	}
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<BusinessListBo> listBusiness(BusinessListBo blo,Integer pageNo,Integer pageSize) {
		blo.setAid(TokenManager.getAdminId());
		return (Pagination<BusinessListBo>) findPage("selectBusinessList", "selectBusinessCount", disposeParams(blo), pageNo, pageSize);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<BusinessListBo> listAllBusiness(BusinessListBo blo, Integer pageNo, Integer pageSize) {
		return (Pagination<BusinessListBo>) findPage("selectBusinessList", "selectBusinessCount", disposeParams(blo), pageNo, pageSize);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<BusinessListBo> listManageBusiness(BusinessListBo blo,Integer pageNo,Integer pageSize) {
		blo.setAid(TokenManager.getAdminId());
		return (Pagination<BusinessListBo>) findPage("selectBusinessManageList", "selectBusinessManageCount", disposeParams(blo), pageNo, pageSize);
	}
	
	private Map<String,Object> disposeParams(BusinessListBo blo){
		Map<String, Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(blo.getUid())) params.put("uid", blo.getUid());
		if(StringUtils.isNotBlank(blo.getAid())) params.put("aid", blo.getAid());
		if(StringUtils.isNotBlank(blo.getAdminName())) params.put("adminName", blo.getAdminName());
		if(StringUtils.isNotBlank(blo.getStartDate())) params.put("startDate", blo.getStartDate()+" 00:00:00");
		if(StringUtils.isNotBlank(blo.getEndDate())) params.put("endDate", blo.getEndDate()+ " 23:59:59");
		if(StringUtils.isNotBlank(blo.getIdentifyName())) params.put("identifyName", blo.getIdentifyName());
		if(blo.getFollowSituation() != null) params.put("followSituation", blo.getFollowSituation());
		if(blo.getCustomerStatus() != null) params.put("customerStatus", blo.getCustomerStatus());
		return params;
	}

	@Override
	public List<BusinessListBo> findBusinessGlossory() {
		return userBusinessMapper.selectBusinessGlossory();
	}

	@Override
	public int judgeBusiness(String uid, String businessProjectId) {
		return userMapper.selectLockedProject(uid, null,businessProjectId, 1, UserLockReleaseStatus.LOCKED.getCode()).size();
	}

	@Override
	@Transactional
	public void addBusinessAndFollow(BussinessFollowBo bfb) throws ParseException {
		UserBusiness ub = new UserBusiness();
		String ubId = UUID.randomUUID().toString();
		SimpleDateFormat format = new SimpleDateFormat(AFTConstants.YYYYMMDDHHMMSS);
		ub.setCustomerStatus(Integer.parseInt(bfb.getCustomerStatus()));
		ub.setFollowSituation(Integer.parseInt(bfb.getFollowSituation()));
		ub.setId(ubId);
		ub.setUid(bfb.getUid());
		ub.setAid(TokenManager.getAdminId());
		ub.setRemarks(bfb.getRemarks());
		ub.setBusinessProjectId(bfb.getBusinessProjectId());
		ub.setUpdateTime(format.parse(bfb.getCreateTime()));
		ub.setCreateTime(format.parse(bfb.getCreateTime()));
		userBusinessMapper.insert(ub);
		if (StringUtils.isNotBlank(bfb.getOcbId())) { // 跟进联系人不为空则添加跟进记录
			UserFollow uf = new UserFollow();
			String ufId = UUID.randomUUID().toString();
			uf.setId(ufId);
			uf.setUid(bfb.getUid());
			uf.setCreateTime(format.parse(bfb.getFollowTime()));
			uf.setOcbId(bfb.getOcbId());
			uf.setResult(bfb.getResult());
			uf.setContactType(Integer.parseInt(bfb.getContactType()));
			uf.setAid(TokenManager.getAdminId());
			uf.setEffective(0);
			int followCount = userBusinessMapper.selectFollowCountByUAid(bfb.getUid(), TokenManager.getAdminId()) + 1;
			uf.setFollowCount(followCount);
			userFollowMapper.insert(uf);
			UserFollowBusiness ufb = new UserFollowBusiness();
			ufb.setId(UUID.randomUUID().toString());
			ufb.setBusinessId(ubId);
			ufb.setFollowId(ufId);
			ufb.setCustomerStatus(ub.getCustomerStatus());
			ufb.setFollowSituation(ub.getFollowSituation());
			ufb.setBusinessProjectId(bfb.getBusinessProjectId());
			userFollowBusinessMapper.insert(ufb);
		}
	}

	@Override
	public List<BusinessListBo> findBusinessByUAid(String uid, String aid) {
		return userBusinessMapper.selectBusinessByUAid(uid,aid);
	}

	@Override
	public List<BusinessListBo> findLockedBusinessByUAid(String uid, String aid) {
		return userBusinessMapper.selectLockedBusinessByUAid(uid,aid);
	}

	@Override
	public BussinessFollowBo findBusinessDetail(String businessId) {
		
		return userBusinessMapper.findBusinessDetail(businessId);
	}

	@Override
	public int updateBusiness(BussinessFollowBo bfb) {
		UserBusiness userBusiness = new UserBusiness();
		userBusiness.setId(bfb.getBusinessId());
		userBusiness.setCustomerStatus(Integer.parseInt(bfb.getCustomerStatus()));
		userBusiness.setFollowSituation(Integer.parseInt(bfb.getFollowSituation()));
		userBusiness.setRemarks(bfb.getRemarks());
		userBusiness.setUpdateTime(new Date());
		return userBusinessMapper.updateByPrimaryKeySelective(userBusiness);
	}

	@Override
	@Transactional
	public int addFollowOneBusiness(BussinessFollowBo bfb) throws ParseException {
		Date updateTime = new Date();
		SimpleDateFormat format = new  SimpleDateFormat(AFTConstants.YYYYMMDDHHMMSS);
		UserBusiness userBusiness = new UserBusiness();
		userBusiness.setId(bfb.getBusinessId());
		userBusiness.setUpdateTime(updateTime);
		userBusiness.setCustomerStatus(Integer.parseInt(bfb.getCustomerStatus()));
		userBusiness.setFollowSituation(Integer.parseInt(bfb.getFollowSituation()));
		userBusinessMapper.updateByPrimaryKeySelective(userBusiness);
		UserFollow userFollow = new UserFollow();
		String followId = UUID.randomUUID().toString();
		int followCount = userBusinessMapper.selectFollowCountByUAid(bfb.getUid(), TokenManager.getAdminId()) + 1;
		userFollow.setId(followId);
		userFollow.setResult(bfb.getResult());
		userFollow.setCreateTime(format.parse(bfb.getFollowTime()));
		userFollow.setEffective(0);
		userFollow.setOcbId(bfb.getOcbId());
		userFollow.setFollowCount(followCount);
		userFollow.setContactType(Integer.parseInt(bfb.getContactType()));
		userFollow.setAid(TokenManager.getAdminId());
		userFollow.setUid(bfb.getUid());
		userFollowMapper.insert(userFollow);
		UserFollowBusiness userFollowBusiness = new UserFollowBusiness();
		String ufbId = UUID.randomUUID().toString();
		userFollowBusiness.setId(ufbId);
		userFollowBusiness.setFollowId(followId);
		userFollowBusiness.setBusinessProjectId(bfb.getBusinessProjectId());
		userFollowBusiness.setBusinessId(bfb.getBusinessId());
		userFollowBusiness.setCustomerStatus(Integer.parseInt(bfb.getCustomerStatus()));
		userFollowBusiness.setFollowSituation(Integer.parseInt(bfb.getFollowSituation()));
		userFollowBusiness.setRemarks(bfb.getRemarks());
		userFollowBusinessMapper.insert(userFollowBusiness);
		return 1;
	}

	@Override
	public BussinessFollowBo findFollowOneBusiness(String ufbId) {
		return userBusinessMapper.findFollowOneBusiness(ufbId);
	}

	@Override
	public int updateFollowOneBusiness(BussinessFollowBo bfb) {
		//修改业务跟进中间表
		UserFollowBusiness userFollowBusiness = new UserFollowBusiness();
		userFollowBusiness.setId(bfb.getUfbId());
		userFollowBusiness.setRemarks(bfb.getRemarks());
		userFollowBusiness.setCustomerStatus(Integer.parseInt(bfb.getCustomerStatus()));
		userFollowBusiness.setFollowSituation(Integer.parseInt(bfb.getFollowSituation()));
		userFollowBusinessMapper.updateByPrimaryKeySelective(userFollowBusiness);
		//修改跟进记录表
		UserFollow userFollow = new UserFollow();
		userFollow.setId(bfb.getFollowId());
		userFollow.setContactType(Integer.parseInt(bfb.getContactType()));
		userFollow.setResult(bfb.getResult());
		if(StringUtils.isNotBlank(bfb.getOcbId())) userFollow.setOcbId(bfb.getOcbId());
		userFollowMapper.updateByPrimaryKeySelective(userFollow);
		return 1;
	}

	@Override
	public int addOneContact(OrganizationContactBook ocb) {
		ocb.setAid(TokenManager.getAdminId());
		ocb.setId(UUID.randomUUID().toString());
		ocb.setMajor(AFTConstants.NO);
		Admin ad=adminMapper.selectByPrimaryKey(TokenManager.getAdminId());
		ocb.setAname(ad.getName());
		return organizationContactBookMapper.insert(ocb);
	}

	@Override
	public int deleteBusiness(String businessId) {
		return userBusinessMapper.deleteByPrimaryKey(businessId);
	}

	@Override
	public int updateBusinessToStop(String businessId) {
		UserBusiness ub = new UserBusiness();
		ub.setId(businessId);
		ub.setCustomerStatus(CustomerStatusFiled.STATUS_STOP.getCode());
		return userBusinessMapper.updateByPrimaryKeySelective(ub);
	}

	@Override
	public int deleteFollowOneBusiness(String ufbId) {
		UserFollowBusiness ufb=userFollowBusinessMapper.selectByPrimaryKey(ufbId);
		if (ufb.getFollowSituation()==5) {//如果业务是已签合同则不允许删除
			throw new BusinessException(new Error(ErrorConstants.BUSINESS_ALREADY_LOCKED,""));
		}
		return userFollowBusinessMapper.deleteByPrimaryKey(ufbId);
	}

	@Override
	public int deleteOneContact(String ocbId) {
		return organizationContactBookMapper.deleteByPrimaryKey(ocbId);
	}

	@Override
	public List<Admin> findAdminName() {
		String aid=TokenManager.getAdminId();
		return userMapper.findAdminName(aid);
	}
	
	@Override
	public int updatePersonalCustomerz(CustomerPersonalDetailBo bo) {
		UserIdentity ui = new UserIdentity();
		User user = new User();
		try {
			BeanUtilsExt.copyProperties(ui, bo);
			user.setId(bo.getUid());
			user.setSocietyTag(bo.getSocietyTag());
			user.setHeadPortraitUrl(bo.getHeadPortraitUrl());
			user.setIntroduction(bo.getIntroduction());
			user.setUpdateTime(new Date());
			if(!StringUtils.isBlank(bo.getAid())){
				user.setAid(bo.getAid());
				user.setShareType(0);
			}
		} catch (InvocationTargetException | IllegalAccessException e) {
			e.printStackTrace();
		}
		userMapper.updateByPrimaryKeySelective(user);
		return 1;
	}

	@Override
	public Pagination<CustomerListOut> findEnteringAudit(CustomerListOut clo, Integer pageNo, Integer pageSize) {
		Map<String,Object> params = disposeParams(clo);
		if(!StringUtils.isBlank(clo.getAdminName()))params.put("adminName", clo.getAdminName());
		@SuppressWarnings("unchecked")
		Pagination<CustomerListOut> list = (Pagination<CustomerListOut>) findPage("findEnteringAuditList","findEnteringAuditCount",params,pageNo,pageSize);
		return list;
	}
	
	@Override
	public Pagination<CustomerListOut> findEnteringAuditIsNo(CustomerListOut clo, Integer pageNo, Integer pageSize) {
		clo.setAid(TokenManager.getAdminId());
		Map<String,Object> params = disposeParams(clo);
		if(!StringUtils.isBlank(clo.getAdminName()))params.put("adminName", clo.getAdminName());
		@SuppressWarnings("unchecked")
		Pagination<CustomerListOut> list = (Pagination<CustomerListOut>) findPage("findEnteringAuditIsNoList","findEnteringAuditIsNoCount",params,pageNo,pageSize);
		return list;
	}

	@Override
	public int updateEnteringAudit(User bo) {	
		String[] ary=bo.getId().split(",");
		for (String s : ary) {
			String id=s;
			Integer auditStatus=bo.getAuditStatus();
			String auditOpinion=bo.getAuditOpinion();
			userMapper.updateEnteringAudit(id,auditStatus,auditOpinion);	
		}
		return 1;
	}

	@Override
	public int updateMainContact(String ocbId,String uid) {
		organizationContactBookMapper.updateSubContact(uid);
		OrganizationIdentity oi=new OrganizationIdentity();
		OrganizationContactBook ocb= organizationContactBookMapper.selectByPrimaryKey(ocbId);
		oi.setUid(uid);
		oi.setContacts(ocb.getName());
		oi.setContactMobile(ocb.getMobile());
		organizationIdentityMapper.updateServiceByUid(oi);
		organizationContactBookMapper.updateMainContact(ocbId);
		return 1;
	}

	@Override
	public int updateRefusedCustomer(String id,String nickname, String mobile, String societyTag) {
		User u=userMapper.selectByPrimaryKey(id);
		u.setNickname(nickname);
		u.setMobile(mobile);
		u.setSocietyTag(societyTag);
		return userMapper.updateRefusedCustomer(id, nickname, mobile, societyTag);
	}
	
	private void setCustomerList(List<CustomerListOut> tmpList,int i, Integer power){
		Date now = new Date();
		String s1,s2;
		Long l1,l2;
		int diff1=0,diff2=0;
		for(CustomerListOut clo: tmpList){
			try {
				//如果最近跟进为空直接取转换时间
			if (StringUtils.isNotBlank(clo.getLastFollowTime())){
				//如果最近跟进小于转换取转换时间
				if(DateUtils.parseDate(clo.getLastFollowTime(), AFTConstants.YYYYMMDDHHMMSS).getTime()>DateUtils.parseDate(clo.getTransferTime(), AFTConstants.YYYYMMDDHHMMSS).getTime()) {
					s1=clo.getLastFollowTime();
				}else {
					s1=clo.getTransferTime();
				}
			}else {
				s1=clo.getTransferTime();
			}
			//另外一个时间取转换时间
			s2 = clo.getTransferTime();
				l1 = DateUtils.parseDate(s1, AFTConstants.YYYYMMDDHHMMSS).getTime();
				l2 = DateUtils.parseDate(s2, AFTConstants.YYYYMMDDHHMMSS).getTime();
				if(i==0) {
					diff1 = (int)((l1 + AFTConstants.USER_FOLLOW_LIMIT_MS - now.getTime())/(24*3600*1000));
					diff2 = (int)((l2 + AFTConstants.USER_SIGN_LIMIT_MS - now.getTime())/(24*3600*1000));
				}else if (i==1) {
					diff1 = (int)((l1 + AFTConstants.PROJECT_FOLLOW_LIMIT_MS - now.getTime())/(24*3600*1000));
					diff2 = (int)((l2 + AFTConstants.PROJECT_SIGN_LIMIT_MS - now.getTime())/(24*3600*1000));
				}
				clo.setSurplusFollowTime(diff1 + "");
				clo.setSurplusSignTime(diff2 + "");
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if (power==1) {
				if(!clo.getAid().equals(TokenManager.getAdminId())) {
				clo.setContacts("***");
				clo.setContactMobile("***");
				}
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CustomerListOut> listSignOrganizationCustomer(CustomerListIn cli, Integer pageNo,
			Integer pageSize) {
		cli.setAid(TokenManager.getAdminId());
		Map<String,Object> params = disposeParams(cli);
		Pagination<CustomerListOut> list = (Pagination<CustomerListOut>) findPage("selectSignOrganizationCustomerList","selectSignOrganizationCustomerCount",params,pageNo,pageSize);
		return list;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CustomerListOut> listSignPersonalCustomer(CustomerListIn cli, Integer pageNo,
			Integer pageSize) {
		cli.setAid(TokenManager.getAdminId());
		Map<String,Object> params = disposeParams(cli);
		Pagination<CustomerListOut> list = (Pagination<CustomerListOut>) findPage("selectSignPersonalCustomerList","selectSignPersonalCustomerCount",params,pageNo,pageSize);
		List<CustomerListOut> tmpList = (List<CustomerListOut>)list.getList();
		setCustomerList(tmpList,0,null);
		list.setList(tmpList);
		return list;
	}

	@Override
	public List<LockingReleaseBo> selectLockedProject(String uid) {
		List<LockingReleaseBo> list=userMapper.selectLockedProject(uid,null,null,1,0);
		for (LockingReleaseBo lrb : list) {
			if (lrb.getAid().equals(TokenManager.getAdminId())) {
				lrb.setMySign(1);
			}else {
				lrb.setMySign(0);
			}
		}
		return list;
	}

	@Override
	public List<CustomerSimpleBo> getPrivateCustomerByName(String name) {
		return userMapper.selectPrivateCustomerByName(name,TokenManager.getAdminId());
	}

	@Override
	public List<CustomerSimpleBo> getSignedCustomerByName(String name) {
		return userMapper.selectSignedCustomerByName(name,TokenManager.getAdminId());
	}
	
	private int updateUserLock(String uid,String aid,Integer oldStatus,Integer newStatus){
		return userLockReleaseMapper.updateUserLock(uid,aid,oldStatus,newStatus);
	}
	private int updateUsersLock(List<String> uList, String aid, Integer oldStatus, Integer newStatus) {
		return userLockReleaseMapper.updateUsersLock(uList,aid,oldStatus,newStatus);
	}
	
	
	
	
	
	
	
	
	@Override
	public List<LockingReleaseBo> selectWaitReleaseCustomer(String uid,Integer type){
		return userLockReleaseMapper.selectWaitReleaseCustomer(uid,type);
	}
	
	/**
	 * 查询需要释放的业务
	 * @param uid
	 * @return
	 */
	@Override
	public List<LockingReleaseBo> selectWaitReleaseBusiness(String uid){
		return userLockReleaseMapper.selectWaitReleaseBusiness(uid);
	}
	
	/**
	 * 处理需要释放
	 * @param list
	 */
	@Override
	public void updateReleaseLock(Date releaseTime){
		 SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		 String time=formatter.format(releaseTime); 
		userMapper.updateReleaseLock(time);
		userLockReleaseMapper.updateReleaseLock(time);
		
	}
	
	@Override
	public int updateAgainProjectTask(String uid, String projectId,String aid) {
		List<LockingReleaseBo>  businessLockedList = userMapper.selectLockedProject(uid, TokenManager.getAdminId(), projectId, 1, UserLockReleaseStatus.LOCKED.getCode());
//		List<LockingReleaseBo>  businessLockedList = userMapper.selectLockedProject(uid, aid, projectId, 1, UserLockReleaseStatus.LOCKED.getCode());
		UserLockRelease u= new UserLockRelease();
		if (businessLockedList.size()==1) {
			for (LockingReleaseBo l : businessLockedList) {
				u.setId(l.getId());
				u.setLockTime(new Date());
			}
			return userLockReleaseMapper.updateByPrimaryKeySelective(u);
		}
		return 0;
	}

	@Override
	public int updateInformationMaintainerr(String id, String aid) {
		User u=new User();
		u.setId(id);
		u.setInformationMaintainer(aid);
		return userMapper.updateByPrimaryKeySelective(u);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CustomerListIn> listCustomerInformation(CustomerListIn cli, Integer pageNo, Integer pageSize) {
			cli.setType(AFTConstants.USER_TYPE_ORGANIZATION);
			cli.setAid(TokenManager.getAdminId());
//			cli.setAid("1");
			cli.setShareType(String.valueOf(AFTConstants.USER_SHARE_PRIVATE));
			Map<String,Object> params = disposeParams(cli);
			return (Pagination<CustomerListIn>) findPage("selectCustomerInformationList","selectCustomerInformationCount",params,pageNo,pageSize);
			}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<CustomerListIn> listDepCustomerInformation(CustomerListIn cli, Integer pageNo, Integer pageSize) {
		cli.setType(AFTConstants.USER_TYPE_ORGANIZATION);
		cli.setAid(TokenManager.getAdminId());
//		cli.setAid("1");
		cli.setShareType(String.valueOf(AFTConstants.USER_SHARE_PRIVATE));
		Map<String,Object> params = disposeParams(cli);
		return (Pagination<CustomerListIn>) findPage("selectDepCustomerInformationList","selectDepCustomerInformationCount",params,pageNo,pageSize);
		}
	
	public boolean checkCustomerInformation(String uid) {
		int i=userMapper.checkCustomerInformation(uid);
		if (i<1) {
			return true;
		}
		return false;
	}

	@Override
	public void updatePendingReleaseLock(List<LockingReleaseBo> newList) {
		String lockIds = "";
		for(LockingReleaseBo bo:newList){
			lockIds += bo.getId() + ",";
		}
		if(lockIds.length()>0) {
			lockIds = "'" + lockIds.substring(0,lockIds.length()-1).replace(",", "','") + "'";
			userLockReleaseMapper.updatePendingReleaseLock(lockIds);
		}
	
	}

	@Override
	public List<LockingReleaseBo> selectPendinglockUserList() {
		return userLockReleaseMapper.selectPendinglockUserList();
		
	}

	@Override
	public int updateUserLevel(User u) {
		if (!u.getId().contains(",")) {
			userMapper.updateByPrimaryKeySelective(u);
		}else {
			List<String> ulist=Arrays.asList(u.getId().split(","));
			userMapper.updateList(null, u.getLevel(), null,null,null, ulist);
		}
		return 1; 
	}

	@Override
	public XSSFWorkbook privateUnitCustomerOutXls(CustomerListIn cli, Integer sort, Integer sortType, Integer pageNo,
			Integer pageSize) {
		cli.setType(AFTConstants.USER_TYPE_ORGANIZATION);
		cli.setAid(TokenManager.getAdminId());
//		cli.setAid("1");
		cli.setShareType(String.valueOf(AFTConstants.USER_SHARE_PRIVATE));
		Map<String,Object> params = disposeParams(cli);
		params.put("sort", sort);
		params.put("sortType",sortType);
		List<CustomerListOut> list= userMapper.privateUnitCustomerList(params);
		setCustomerList(list,0,0);
		if (list==null || list.size()==0) return null;
		String[] comment = {"客户名称","地区","联系人","联系电话","社会性质","客户初始时间","剩余私有天数","最新跟进时间","客户等级"};
		String filePath = uploadPath + "/privateUnitCustomer";
		XSSFWorkbook wb = ExportExcelUtil.exportSelectPrivateOrganizationCustomer(list, comment, filePath);
		return wb;
	}

	@Override
	public int customerHandOver(String userIds, String receiveId) {
/*		String [] str=userIds.split(",");
		String aid=TokenManager.getAdminId();
		List<String> uids=Arrays.asList(str);
		userLockReleaseMapper.updateBatchReleaseProject(uids,receiveId,aid);
		userLockReleaseMapper.updateBatchlockProject(uids,receiveId,aid);*/
		return 0;
	}


	
	@Override
	public int updatePrivateBusinessTransfer(String inputId, String uid, String pid) {
		List<LockingReleaseBo> list=userLockReleaseMapper.checkUserProject(uid, pid,TokenManager.getAdminId());
		if (list.isEmpty()) {
			throw new BusinessException(new Error("客户归属错误","客户归属错误"));
		}
		LockingReleaseBo l=list.get(0);
		UserLockRelease ul=new UserLockRelease();
		ul.setId(l.getId());
		ul.setAid(inputId);
		userLockReleaseMapper.updateByPrimaryKeySelective(ul);
		addtransferLog(uid,pid,TokenManager.getAdminId(),inputId,3,false);
		List<BusinessListBo> bl=userBusinessMapper.selectBusinessProjectByUAPid(uid, TokenManager.getAdminId(), pid);
		if (bl.size()==1) {
			UserBusiness ub=new UserBusiness();
			ub.setId(bl.get(0).getBusinessId());
			ub.setAid(inputId);
			ub.setRemarks("转交客户业务触发");
			userBusinessMapper.updateByPrimaryKeySelective(ub);
		}
		return 1;
	}

	private void addtransferLog(String uid, String pid, String aid, String takeAid,Integer type, boolean isUs) {
		if (!isUs) {
			UserTransferLog utl=new UserTransferLog();
			utl.setAid(aid);
			utl.setCreateTime(new Date());
			utl.setPid(pid);
			utl.setTakeAid(takeAid);
			utl.setType(type);
			utl.setUid(uid);
			userTransferLogMapper.insertSelective(utl);
		}else {
			List<String> ulist=Arrays.asList(uid.split(","));
			List<UserTransferLog> utfList=new ArrayList<>();
			for (String us : ulist) {
				UserTransferLog utl=new UserTransferLog();
				utl.setAid(aid);
				utl.setCreateTime(new Date());
				utl.setPid(pid);
				utl.setTakeAid(takeAid);
				utl.setType(type);
				utl.setUid(us);
				utfList.add(utl);
			}
			userTransferLogMapper.insertList(utfList);
		}
		
		
	}

	@Override
	public List<transferListBo> transferList(String uid) {
		return userTransferLogMapper.selectByUidGetList(uid);
	}

	@Override
	public int pushReleaseUser(String id) {
		Date date =new Date();
		String aid=TokenManager.getAdminId();
		if (!id.contains(",")) {
			
			User u=userMapper.selectByPrimaryKey(id);
			if (!u.getAid().equals(aid)) {
				throw new BuilderException("客户归属错误！");
			}
			UserTransferLog utl=new UserTransferLog();
			u.setTransferTime(date);
			u.setShareType(1);
			userMapper.updateByPrimaryKeySelective(u);
			utl.setAid(aid);
			utl.setCreateTime(date);
			utl.setType(6);
			utl.setUid(id);
			userTransferLogMapper.insertSelective(utl);
			userLockReleaseMapper.updateUserTypeLock(u.getId(), TokenManager.getAdminId(), 0, 2,date);
		}else {
			List<String> list=Arrays.asList(id.split(","));
			List<UserTransferLog> ulList=new ArrayList<UserTransferLog>();
			for (String str : list) {
				User u=userMapper.selectByPrimaryKey(str);
				if (!u.getAid().equals(TokenManager.getAdminId())) {
					throw new BuilderException("客户归属错误！");
				}
				UserTransferLog utl=new UserTransferLog();
				utl.setAid(aid);
				utl.setCreateTime(date);
				utl.setType(6);
				utl.setUid(str);
				ulList.add(utl);
			}
			userTransferLogMapper.insertList(ulList);
			userMapper.updateList(null, null, null,date,1, list);
			userLockReleaseMapper.updateUserTypeLockList(list, TokenManager.getAdminId(), 0, 2,date);
		}
		return 1;
	}

	@Override
	public List<userDaysBo> selectUserDays(String id) {
		Integer x=30,y=270;
		x=x-USER_REMIND_DAYS;
		y=y-USER_REMIND_DAYS;
		List<userDaysBo> list=userLockReleaseMapper.selectUserDays(id,x,y);
		return list;
	}

	@Override
	public int addGuidance(String followId, String guidance) {
		UserFollow uf=new UserFollow();
		uf.setId(followId);
		uf.setGuidance(guidance);
		uf.setGuidanceTime(new Date());
		userFollowMapper.pushUserGuidance(followId,1);
		return userFollowMapper.updateByPrimaryKeySelective(uf);
	}

	@Override
	public boolean checkMax(String aid) {
		int y =0;
		int i=userMapper.checkUserMax(aid);
		//营销员100 经理200 总监500
		if (TokenManager.hasRole(AFTConstants.SALESMAN_DIRECTOR))y=500;
		else if (TokenManager.hasRole(AFTConstants.SALESMAN_MANAGER))y=200;
		else if (TokenManager.hasRole(AFTConstants.SALESMAN))y=100;
		if (i>=y) {
			return true;
		}
		return false;
	}

	@Override
	public void pushReleaseLog(List<LockingReleaseBo> list,Integer type) throws InterruptedException {
		Date date=new Date();
		List<LockingReleaseBo> newList=new ArrayList<LockingReleaseBo>();
		  if (list!=null&&list.size()>0) {
			  for(int i=0;i<list.size();i++){
				  newList.add(list.get(i));
				  if(50 == newList.size()||i == list.size()-1){
					  if(newList.size()>0) {
						  List<UserTransferLog> list3=new ArrayList<UserTransferLog>();
						  for (LockingReleaseBo lrb : newList) {
							  UserTransferLog utl=new UserTransferLog();
							  utl.setAid(lrb.getAid());
							  utl.setCreateTime(date);
							  if(type==0)utl.setType(4);
							  else if(type==1)utl.setType(5);
							  utl.setUid(lrb.getUid());
							  list3.add(utl);
						}
						  userTransferLogMapper.insertList(list3);
					  }
					  newList.clear();
					  Thread.sleep(2000);
				  }
			  }
		  }
		
	}


}