package com.goafanti.user.service.impl;

import com.goafanti.app.bo.consultantListBo;
import com.goafanti.common.bo.Result;
import com.goafanti.common.bo.fieldGlossoryBo;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.*;
import com.goafanti.common.model.Notice;
import com.goafanti.common.model.User;
import com.goafanti.common.model.UserIdentity;
import com.goafanti.common.utils.AsyncUtils;
import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;
import com.goafanti.portal.bo.UserSubscriberListBo;
import com.goafanti.user.bo.Advertisings;
import com.goafanti.user.bo.AuditorUserIdentityDetailBo;
import com.goafanti.user.bo.UserIdentityBo;
import com.goafanti.user.bo.UserIdentityDetailAdminBo;
import com.goafanti.user.service.UserIdentityService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserIdentityServiceImpl extends BaseMybatisDao<UserIdentityMapper> implements UserIdentityService {
	@Autowired
	private UserIdentityMapper	userIdentityMapper;
	@Autowired
	private UserMapper			userMapper;
	@Autowired
	private UserRoleMapper		userRoleMapper;
	@Autowired
	private AsyncUtils		asyncUtils;
	@Autowired
	DistrictGlossoryMapper districtGlossoryMapper;
	@Autowired
	IndustryCategoryMapper industryCategoryMapper;
	@Autowired
	UserInterestMapper	userInterestMapper;

	private static final Logger	logger	= LoggerFactory.getLogger(UserIdentityServiceImpl.class);

	@Override
	public UserIdentity selectUserIdentityByUserId(String uid) {
		return userIdentityMapper.selectUserIdentityByUserId(uid);
	}

	@Override
	public UserIdentity insert(UserIdentity userIdentity) {
		userIdentityMapper.insert(userIdentity);
		return userIdentity;
	}

	@Override
	public int updateByPrimaryKeySelective(UserIdentity userIdentity) {
		return userIdentityMapper.updateByPrimaryKeySelective(userIdentity);
	}

	@Override
	public UserIdentityBo selectUserIdentityBoByUserId(String uid) {
		return userIdentityMapper.selectUserIdentityBoByUserId(uid);
	}

	@Override
	public int updateByPrimaryKey(UserIdentity u) {
		return userIdentityMapper.updateByPrimaryKey(u);
	}

	@Override
	public int saveUserIdentityProcess(Result res, UserIdentity userIdentity, String uid) {
		UserIdentity identity = userIdentityMapper.selectUserIdentityByUserId(uid);
		if (null == identity) {
			userIdentity.setId(UUID.randomUUID().toString());
			userIdentity.setUid(uid);
			userIdentity.setWrongCount(0);
			userIdentity.setAuditStatus(0);
			return userIdentityMapper.insert(userIdentity);
		} else {
			userIdentity.setId(identity.getId());
			if (null != userIdentity.getAuditStatus() && 5 == userIdentity.getAuditStatus()) {
				User u = new User();
				u.setId(userIdentity.getUid());
				u.setLvl(1);
				userMapper.update(u);
			}
			return userIdentityMapper.updateByPrimaryKeySelective(userIdentity);
		}
	}

	@Override
	public int updateUserDetail(UserIdentity u, String saveSign, Integer level) {
		User user = userMapper.queryById(u.getUid());
		if (!UserLevel.GENERAL.getCode().equals(user.getLvl())
				&& !CertifySubmitType.SUBMIT.getCode().equals(saveSign)) {
			user.setLvl(level);
			userMapper.update(user);
		}
		if (CertifySubmitType.SUBMIT.getCode().equals(saveSign)) {
			createAuditorNotice(user);
		}

		return userIdentityMapper.updateByPrimaryKeySelective(u);

	}

	@Override
	public int updateUserDetailByAuditAdmin(UserIdentity ui, String aid, String mid, Integer level) {
		// 审核员UPDATE_USER_DETAIL
		User user = userMapper.queryById(ui.getUid());
		if (!IdentityAuditStatus.PASSED.getCode().equals(ui.getAuditStatus())) {
			user.setLvl(UserLevel.GENERAL.getCode());
			userMapper.update(user);
			createNotice(user, ui.getAuditStatus());
		}
		if (IdentityAuditStatus.PASSED.getCode().equals(ui.getAuditStatus())) {
			/*
			 * if (UserLevel.GENERAL.getCode().equals(level)) {
			 * user.setLvl(UserLevel.CERTIFIED.getCode()); }
			 */
			user.setLvl(UserLevel.CERTIFIED.getCode());
			user.setAid(aid);
			user.setMid(mid);
			userMapper.update(user);
			createNotice(user, ui.getAuditStatus());
		}
		return userIdentityMapper.updateByPrimaryKeySelective(ui);
	}

	@Override
	public UserIdentity insertByAdmin(UserIdentity ui, String saveSign) {
		userIdentityMapper.insert(ui);
		User u = userMapper.queryById(ui.getUid());
		if (!TokenManager.hasRole(AFTConstants.AUDITORADMIN) && !TokenManager.hasRole(AFTConstants.SUPERADMIN)
				&& CertifySubmitType.SUBMIT.getCode().equals(saveSign)) {
			u.setAid(TokenManager.getAdminId());
			userMapper.update(u);
			createAuditorNotice(u);
		}
		return ui;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<UserSubscriberListBo> listSubscriber(String url,String name, Integer level, String field, Integer province,
			Integer city, Integer area, Integer international, Integer pNo, Integer pSize) {
		Map<String, Object> params = new HashMap<>();
		if (StringUtils.isNotBlank(url)) {
			params.put("url", url);
		}
		if (StringUtils.isNotBlank(name)) {
			params.put("name", name);
		}

		if (null != level) {
			params.put("level", level);
		}

		if (StringUtils.isNotBlank(field)) {
			params.put("field", field);
		}

		if (null != province) {
			params.put("province", province);
		}

		if (null != city) {
			params.put("city", city);
		}

		if (null != area) {
			params.put("area", area);
		}
		if (null != international) {
			params.put("international", international);
		}

		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 12) {
			pSize = 12;
		}
		return (Pagination<UserSubscriberListBo>) findPage("findSearchSubscriberListByPage",
				"findSearchSubscriberCount", params, pNo, pSize);
	}

	// 给业务员及客户经理发送通知
	private void createNotice(User u, Integer status) {
		if (!StringUtils.isBlank(u.getAid())) {
			Notice n = new Notice();
			n.setPid(u.getAid());
			n.setAid(u.getAid());
			n.setUid(u.getId());
			notice(n, status);
		}

		if (!StringUtils.isBlank(u.getMid())) {
			Notice n = new Notice();
			n.setUid(u.getId());
			n.setAid(u.getMid());
			if (!StringUtils.isBlank(u.getAid())) {
				n.setPid(u.getAid());
			}
			notice(n, status);
		}

	}

	// 给所有审核员发送审核通知
	private void createAuditorNotice(User u) {
		List<String> ids = userRoleMapper.listAuditor();
		List<Notice> list = new ArrayList<>();
		if (null != ids && ids.size() > 0) {
			for (String s : ids) {
				Notice n = new Notice();
				Calendar now = Calendar.getInstance();
				now.set(Calendar.MILLISECOND, 0);
				n.setId(UUID.randomUUID().toString());
				n.setCreateTime(now.getTime());
				n.setReaded(NoticeReadStatus.UNREAD.getCode());

				if (null != u) {
					n.setPid(u.getAid());
				}
				n.setUid(u.getId());
				n.setAid(s);
				n.setContent(NoticeStatus.PERSONALCERTIFY.getDesc() + " " + IdentityAuditStatus.COMMITTED.getDesc());
				n.setNoticeType(NoticeStatus.PERSONALCERTIFY.getCode());
				list.add(n);
			}
			asyncUtils.addNoticeBatch(list);
		}
	}

	@Override
	public AuditorUserIdentityDetailBo selectAuditorUserIdentityByUserId(String uid) {
		return userIdentityMapper.selectAuditorUserIdentityByUserId(uid);
	}

	private void notice(Notice n, Integer status) {
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		n.setId(UUID.randomUUID().toString());
		n.setCreateTime(now.getTime());
		n.setReaded(NoticeReadStatus.UNREAD.getCode());
		String content = NoticeStatus.PERSONALCERTIFY.getDesc();
		if (IdentityAuditStatus.UNCOMMITTED.getCode() == status) {
			content = content + " " + IdentityAuditStatus.UNCOMMITTED.getDesc();
		} else if (IdentityAuditStatus.COMMITTED.getCode() == status) {
			content = content + " " + IdentityAuditStatus.COMMITTED.getDesc();
		} else if (IdentityAuditStatus.UNPAID.getCode() == status) {
			content = content + " " + IdentityAuditStatus.UNPAID.getDesc();
		} else if (IdentityAuditStatus.PAID.getCode() == status) {
			content = content + " " + IdentityAuditStatus.PAID.getDesc();
		} else if (IdentityAuditStatus.PASSED.getCode() == status) {
			content = content + " " + IdentityAuditStatus.PASSED.getDesc();
		} else {
			content = content + " " + IdentityAuditStatus.NOTPASSED.getDesc();
		}
		n.setContent(content);
		n.setNoticeType(NoticeStatus.PERSONALCERTIFY.getCode());
		// noticeMapper.insert(n);
	}

	@Override
	public UserIdentityDetailAdminBo selectUserIdentityByUserIdAdmin(String uid) {
		UserIdentity ui = userIdentityMapper.selectUserIdentityByUserId(uid);
		User u = userMapper.queryById(uid);
		UserIdentityDetailAdminBo bo = new UserIdentityDetailAdminBo();
		if (ui != null) {
			BeanUtils.copyProperties(ui, bo);
		}
		bo.setLevel(u.getLvl().toString());
		return bo;
	}

	@CacheEvict(value = "internationalUserList", allEntries = true)
	public void cleanInternationalUser() {
		LoggerUtils.debug(logger, "清除国际专家列表");
	}

	@Override
	public UserIdentityBo expertsDetail(String uid) {
		
		UserIdentityBo u=userIdentityMapper.selectUserIdentityByUid(uid);
		if (null!=u.getProvince()) {
			u.setProvince0(districtGlossoryMapper.selectByPrimaryKey(u.getProvince()).getName());
		}
		if (null!=u.getCity()) {
			u.setCity0(String.valueOf(districtGlossoryMapper.selectByPrimaryKey(u.getCity()).getName()));
		}
		if (null!=u.getArea()) {
			u.setArea0(String.valueOf(districtGlossoryMapper.selectByPrimaryKey(u.getArea()).getName()));
		}
		if (null!=u.getIndustry()) {
			u.setIndustry0(String.valueOf(industryCategoryMapper.selectByPrimaryKey(u.getIndustry()).getName()));
		}
		if (null!=u.getUid()) {
			u.setCountInterest(String.valueOf(userInterestMapper.countByToUid(u.getUid())));
		}
		String id=TokenManager.getUserId();
		if(TokenManager.isLogin()&&userInterestMapper.checkUidAndDid(uid,id)>0){
			u.setInterest("1");
		}else {
			u.setInterest("0");
		}
		return u;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<UserIdentityBo> expertsList(String name,String industry, Integer pNo, Integer pSize) {
		Map<String, Object> params = new HashMap<>();
		if (StringUtils.isNotBlank(industry)) {
			params.put("industry", industry);
		}
		if (StringUtils.isNotBlank(name)) {
			params.put("name", name);
		}
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 12) {
			pSize = 10;
		}
		
		Pagination<UserIdentityBo> p= (Pagination<UserIdentityBo>) findPage("findUserIdentityListByPage",
				"findUserIdentityCount", params, pNo, pSize);
		List<UserIdentityBo> l=(List<UserIdentityBo>) p.getList();
		for (UserIdentityBo u : l) {
			int i=userInterestMapper.countInterest(u.getUid());
				u.setCountInterest(String.valueOf(i));
		}
		return p;
		}
		
	

	@Override
	public List<fieldGlossoryBo> industryList() {
		List<fieldGlossoryBo> list=industryCategoryMapper.selectindustryList();
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<consultantListBo> consultantList(Integer pNo, Integer pSize) {
		Map<String, Object> params = new HashMap<>();
		
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 12) {
			pSize = 10;
		}
		Pagination<consultantListBo> p=(Pagination<consultantListBo>) findPage("findConsultantListByPage",
				"findConsultantCount", params, pNo, pSize);
		
		return p; 
	}

	@Override
	public consultantListBo consultantDetail(String id) {
		consultantListBo c=userIdentityMapper.selectconsultantByUid(id);
		if (TokenManager.isLogin()&&userInterestMapper.checkUidAndDid(id, TokenManager.getUserId())>0) {
			c.setInterest("1");
		}else {
			c.setInterest("0");
		}
	return  c;
	}

	@Override
	public List<Advertisings> advertising() {
		List<String> a=new ArrayList<>();
		a.add("关于开展2018年度高新技术企业认定专项审计机构申报工作的通知");
		a.add("转发四川省经济和信息化委员会关于开展2017年上市补助申报通知的通知");
		a.add("关于组织企业参加第十三届中国重庆高新技术成果交易会暨第九届中国国际军民两用技术博览会的通知");
		a.add("关于组织参加第十三届中国重庆高新技术交易会暨第九届中国国际军民两用技术博览会的通知");
		List<Advertisings> ads=new ArrayList<>();
		int i=0;
		List<String> l=new ArrayList<>();
		for (String s : a) {
			i++;
			l.add(s);
			if (i%2==0) {
			ads.add(new Advertisings(l));
			l=new ArrayList<>();
			}
		}
		
		return ads;
	}

	

	

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<consultantListBo> portalConsultantList(Integer pNo, Integer pSize) {
		Pagination<consultantListBo> p=(Pagination<consultantListBo>) findPage("findConsultantListByPage",
				"findConsultantCount", new HashMap<>(), pNo, pSize);
		List<consultantListBo> list=(List<consultantListBo>) p.getList();
		for (consultantListBo c : list) {
			if (StringUtils.isNotBlank(TokenManager.getUserId())&&userInterestMapper.checkUidAndDid(c.getId(), TokenManager.getUserId())>0) {
				c.setInterest("1");
			}else {
				c.setInterest("0");
			}
		}
		return p;
	}

	@Override
	public consultantListBo portalconsultantDetail(String id) {
		consultantListBo c=userIdentityMapper.selectconsultantByUid(id);
		if (StringUtils.isNotBlank(TokenManager.getUserId())&&userInterestMapper.checkUidAndDid(id, TokenManager.getUserId())>0) {
			c.setInterest("1");
		}else {
			c.setInterest("0");
		}
		return c;
	}

	@Override
	public List<fieldGlossoryBo> domainList() {
		List<fieldGlossoryBo> list=industryCategoryMapper.selectDomainList();
		return list;
	}

}
