package com.goafanti.achievement.service.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

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.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import com.goafanti.achievement.bo.AchievementEntity;
import com.goafanti.achievement.bo.AchievementImportBo;
import com.goafanti.achievement.bo.AchievementListBo;
import com.goafanti.achievement.bo.AchievementOrgOwnerDetailBo;
import com.goafanti.achievement.bo.AchievementPartnerListBo;
import com.goafanti.achievement.bo.AchievementUserOwnerDetailBo;
import com.goafanti.achievement.service.AchievementService;
import com.goafanti.common.bo.MyCollection;
import com.goafanti.common.bo.PolicyEntity;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.constant.PageConstants;
import com.goafanti.common.dao.AchievementDemandCountMapper;
import com.goafanti.common.dao.AchievementDemandMapper;
import com.goafanti.common.dao.AchievementInterestMapper;
import com.goafanti.common.dao.AchievementKeywordMapper;
import com.goafanti.common.dao.AchievementMapper;
import com.goafanti.common.dao.AchievementPublishMapper;
import com.goafanti.common.dao.BranchInformationMapper;
import com.goafanti.common.dao.DemandKeywordMapper;
import com.goafanti.common.dao.JtCollectSearchMapper;
import com.goafanti.common.dao.NoticeMapper;
import com.goafanti.common.dao.OrganizationIdentityMapper;
import com.goafanti.common.dao.UserIdentityMapper;
import com.goafanti.common.dao.UserMapper;
import com.goafanti.common.dao.UserRoleMapper;
import com.goafanti.common.enums.AchievementAuditStatus;
import com.goafanti.common.enums.AchievementReleaseStatus;
import com.goafanti.common.enums.AchievementSwitchSign;
import com.goafanti.common.enums.DeleteStatus;
import com.goafanti.common.enums.DemandReleaseStatus;
import com.goafanti.common.enums.NoticeReadStatus;
import com.goafanti.common.enums.NoticeStatus;
import com.goafanti.common.enums.UserType;
import com.goafanti.common.enums.collectType;
import com.goafanti.common.model.Achievement;
import com.goafanti.common.model.AchievementDemand;
import com.goafanti.common.model.AchievementDemandCount;
import com.goafanti.common.model.AchievementKeyword;
import com.goafanti.common.model.AchievementPublish;
import com.goafanti.common.model.Admin;
import com.goafanti.common.model.JtCollectSearch;
import com.goafanti.common.model.Notice;
import com.goafanti.common.model.OrganizationIdentity;
import com.goafanti.common.model.User;
import com.goafanti.common.model.UserIdentity;
import com.goafanti.common.utils.DateUtils;
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.demand.bo.DemandAchievementListBo;
import com.goafanti.portal.bo.AchievementDetailBo;
import com.goafanti.portal.bo.AchievementObject;
import com.goafanti.portal.bo.AchievementPortalDetailBo;
import com.goafanti.portal.bo.AchievementResultObject;

@Service
public class AchievementServiceImpl extends BaseMybatisDao<AchievementMapper> implements AchievementService {

	@Autowired
	private AchievementMapper				achievementMapper;
	@Autowired
	private UserRoleMapper					userRoleMapper;
	@Autowired
	private NoticeMapper					noticeMapper;
	@Autowired
	private AchievementKeywordMapper		achievementKeywordMapper;
	@Autowired
	private AchievementDemandMapper			achievementDemandMapper;
	@Autowired
	private DemandKeywordMapper				demandKeywordMapper;
	@Autowired
	private AchievementDemandCountMapper	achievementDemandCountMapper;
	@Autowired
	private UserIdentityMapper				userIdentityMapper;
	@Autowired
	private OrganizationIdentityMapper		organizationIdentityMapper;
	@Autowired
	private UserMapper					userMapper;
	@Autowired
	BranchInformationMapper		branchInformationMapper;
	@Autowired
	AchievementPublishMapper	achievementPublishMapper;
	@Autowired
	JtCollectSearchMapper	jtCollectSearchMapper;
	@Value(value="${collect_flag}")
	private Boolean collectFlag ;
	private static final Logger				logger	= LoggerFactory.getLogger(AchievementServiceImpl.class);


	@Override
	public void saveAchievement(Achievement a, String[] keywords,List<String >webPages,List<String>appPages) {
		a.setId(UUID.randomUUID().toString());
		a.setDeletedSign(DeleteStatus.UNDELETE.getCode());
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		if (TokenManager.getToken() instanceof Admin) {
			a.setTechBrokerId(TokenManager.getAdminId());
		}
		a.setReleaseStatus(AchievementReleaseStatus.UNRELEASE.getCode());
	
		if (AchievementAuditStatus.SUBMIT.getCode()==a.getAuditStatus()) {
			
			createAuditorNotice(a);
		} else {
			a.setAuditStatus(AchievementAuditStatus.CREATE.getCode());
		}
		String ownerId = "";
		if (TokenManager.getToken() instanceof User) {
			a.setOwnerId(TokenManager.getUserId());
			User u=userMapper.selectByPrimaryKey(TokenManager.getUserId());
			if (null != u) {
				ownerId = u.getId();
			}
		} 
		a.setCreateTime(now.getTime());
		a.setOrgId(ownerId);	
		a.setInfoSources(1);
		achievementMapper.insert(a);
		disposeAchievementKeyword(keywords, a, false);
		disposeAchievementPublish(a,webPages,appPages,false);
		
	}

	private void disposeAchievementPublish(Achievement a,List<String> webPages,List<String> appPages,boolean delete){
		if(delete){
			if(null != webPages && webPages.size()>0){
				achievementPublishMapper.deleteByAchievementId(a.getId());
			}
		}
		AchievementPublish ap = null;
		String defaultPlatformId = branchInformationMapper.selectByDomain(PageConstants.DEFAULT_DOMAIN).getId();
		if(webPages != null && webPages.size()>0){
			for(String page: webPages){
				ap = new AchievementPublish();
				ap.setId(UUID.randomUUID().toString());
				ap.setAchievementId((a.getId()));
				ap.setPublisher(TokenManager.getUserId());
				ap.setPublisher("1");
				ap.setPublishTime(a.getReleaseDate()==null?new Date():a.getReleaseDate());
				ap.setPublishClient(PageConstants.WEB_PLATFORM);
				ap.setPublishPage(page);
				ap.setPublishPlatform(defaultPlatformId);
				ap.setIfTop(AFTConstants.NO);
				ap.setTopNumber(PageConstants.DEFAULT_TOP_NUMBER);
				ap.setShowNumber(PageConstants.DEFAULT_SHOW_NUMBER);
				achievementPublishMapper.insert(ap);
			}
		}
		if(appPages != null && appPages.size()>0){
			for(String page: appPages){
				ap = new AchievementPublish();
				ap.setId(UUID.randomUUID().toString());
				ap.setAchievementId(a.getId());
				ap.setPublisher(TokenManager.getUserId());
				ap.setPublishTime(a.getReleaseDate()==null?new Date():a.getReleaseDate());
				ap.setPublishClient(PageConstants.APP_PLATFORM);
				ap.setPublishPage(page);
				ap.setPublishPlatform(defaultPlatformId);
				ap.setIfTop(AFTConstants.NO);
				ap.setTopNumber(PageConstants.DEFAULT_TOP_NUMBER);
				ap.setShowNumber(PageConstants.DEFAULT_SHOW_NUMBER);
				achievementPublishMapper.insert(ap);
			}
		}
	}
	@Override
	public int updateAchievement(Achievement a, String[] keywords, Integer switchSign,List<String>webPages,List<String>appPages) {
		if (AchievementAuditStatus.SUBMIT.getCode().equals(a.getAuditStatus())) {
			createAuditorNotice(a);
		}
		disposeAchievementKeyword(keywords, a, true);
		disposeAchievementPublish(a,webPages,appPages,true);
		
		if (null != switchSign && AchievementSwitchSign.CLOSE.getCode().equals(switchSign)) {
			a.setOwnerId("");
		}
		achievementMapper.updateByPrimaryKeySelective(a);
		return 1;
	}

	@Override
	public Achievement selectByPrimaryKey(String id) {
		return achievementMapper.selectByPrimaryKey(id);  
	}

	@Override
	public int deleteByPrimaryKey(List<String> id) {
		achievementKeywordMapper.batchDeleteByAchievementIds(id);
		achievementDemandMapper.batchDeleteByAchievementIds(id);
		achievementPublishMapper.batchDeleteByAchievementIds(id);
		for (String s : id) {
			Achievement a = achievementMapper.selectByPrimaryKey(s);
			if(collectFlag)jtCollectSearchMapper.deleteByrowId(s);
			if (null != a && AchievementAuditStatus.AUDITED.getCode().equals(a.getAuditStatus())
					&& StringUtils.isNotBlank(a.getOwnerId())) {
				AchievementDemandCount adc = achievementDemandCountMapper.selectByUid(a.getOwnerId());
				if (null != adc) {
					adc.setAchievementCount(adc.getAchievementCount() - 1);
					if (adc.getAchievementCount() < 0) {
						adc.setAchievementCount(0);
					}
					achievementDemandCountMapper.updateByPrimaryKeySelective(adc);
				}
			}
		}
		return achievementMapper.batchDeleteByPrimaryKey(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AchievementObject> listMyAchievement(Integer auditStatus, String name,Integer dataCategory, 
			String startDate,String endDate, Integer pNo, Integer pSize) {
		System.out.println("as:"+auditStatus+" dc:"+ dataCategory);
		Map<String,Object> params = new HashMap<>();
		params.put("ownerId", TokenManager.getUserId());
		if (null != startDate) params.put("startDate", startDate);
		if (null != endDate) params.put("endDate", endDate);
		if (null != auditStatus) params.put("auditStatus", auditStatus);
		if(null != dataCategory) params.put("dataCategory", dataCategory);
		if (!StringUtils.isBlank(name)) params.put("name", name);
		return (Pagination<AchievementObject>) findPage("listMyAchievementByPage", "listMyAchievementCount",params,
				pNo, pSize);
	}
	
	private Map<String, Object> disposeParams(Integer ownerType,String username, String ownerName, String ownerId, Integer auditStatus,
			Integer serialNumber, String name, String keyword, Integer category, Integer status,
			String releaseDateStartDate, String releaseDateEndDate,String createDateStartDate, String createDateEndDate, Integer releaseStatus, Integer type,
			Integer boutique,String internationalFlag, Integer hot,String recordPerson) {
		Map<String, Object> params = new HashMap<>();

		Date rStart = null;
		Date rEnd = null;
		Date cStart = null;
		Date cEnd = null;
		if (null != ownerType) {
			params.put("ownerType", ownerType);
		}
		if (null != recordPerson) {
			params.put("recordPerson", recordPerson);
		}
		
		if (!StringUtils.isBlank(releaseDateStartDate)) {
			try {
				rStart = DateUtils.parseDate(releaseDateStartDate, AFTConstants.YYYYMMDD);
			} catch (ParseException e) {
			}
		}

		if (!StringUtils.isBlank(releaseDateEndDate)) {
			try {
				rEnd = DateUtils.addDays(DateUtils.parseDate(releaseDateEndDate, AFTConstants.YYYYMMDD), 1);
			} catch (ParseException e) {
			}
		}
		if (!StringUtils.isBlank(createDateStartDate)) {
			try {
				cStart = DateUtils.parseDate(createDateStartDate, AFTConstants.YYYYMMDD);
			} catch (ParseException e) {
			}
		}

		if (!StringUtils.isBlank(createDateEndDate)) {
			try {
				cEnd = DateUtils.addDays(DateUtils.parseDate(createDateEndDate, AFTConstants.YYYYMMDD), 1);
			} catch (ParseException e) {
			}
		}

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

		if (null != type && StringUtils.isNotBlank(username)) {
			if (UserType.PERSONAL.getCode().equals(type)) {
				params.put("username", username);
			} else {
				params.put("unitName", username);
			}
		}

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

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

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

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

		if (!StringUtils.isBlank(ownerId)) {
			params.put("ownerId", ownerId);
		}

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

		if (!StringUtils.isBlank(name)) {
			params.put("name", name);
		}

		if (!StringUtils.isBlank(keyword)) {
			params.put("keyword", keyword);
		}

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

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

		if (null != releaseStatus) {
			params.put("releaseStatus", releaseStatus);
		}
		if (null != boutique) {
			params.put("boutique", boutique);
		}
		if (null != hot) {
			params.put("hot", hot);
		}
		if (null != internationalFlag) {
			params.put("internationalFlag", internationalFlag);
		}
		return params;
	}

	@Override
	public int updateAuditAchievement(Achievement a, String techBroderId, Integer auditStatus) {
		a.setAuditStatus(auditStatus);
		if (AchievementAuditStatus.AUDITED.getCode().equals(auditStatus)) {
			Calendar now = Calendar.getInstance();
			now.set(Calendar.MILLISECOND, 0);
			a.setReleaseDate(now.getTime());
			a.setReleaseStatus(DemandReleaseStatus.UNRELEASE.getCode());
			a.setTechBrokerId(techBroderId);
			if (StringUtils.isNotBlank(a.getKeyword())) {
				String[] keywords = a.getKeyword().trim().split(",|，");
				disposeAchievementKeyword(keywords, a, false);
			}
			String ownerId = a.getOwnerId();
			if (StringUtils.isNotBlank(ownerId)) {
				if (UserType.PERSONAL.getCode().equals(a.getOwnerType())) {
					UserIdentity ui = userIdentityMapper.selectUserIdentityByUserId(ownerId);
					if (null != ui) {
						a.setOwnerName(ui.getUsername());
					}
				} else if (UserType.ORGANIZATION.getCode().equals(a.getOwnerType())) {
					OrganizationIdentity oi = organizationIdentityMapper.selectOrgIdentityByUserId(ownerId);
					if (null != oi) {
						a.setOwnerName(oi.getUnitName());
					}
				}
				AchievementDemandCount adc = achievementDemandCountMapper.selectByUid(ownerId);
				if (null == adc) {
					AchievementDemandCount achievementDemandCount = new AchievementDemandCount();
					achievementDemandCount.setId(UUID.randomUUID().toString());
					achievementDemandCount.setUid(ownerId);
					achievementDemandCount.setAchievementCount(AFTConstants.ACHIEVEMENT_DEMAND_FIRST_COUNT);
					achievementDemandCount.setDemandCount(AFTConstants.ACHIEVEMENT_DEMAND_INIT_COUNT);
					achievementDemandCountMapper.insert(achievementDemandCount);
				} else {
					adc.setAchievementCount(adc.getAchievementCount() + 1);
					achievementDemandCountMapper.updateByPrimaryKeySelective(adc);
				}
			}
		} else {
			a.setReleaseStatus(DemandReleaseStatus.UNRELEASE.getCode());
		}
		createTechBorkerNotice(a);
		return achievementMapper.updateByPrimaryKeySelective(a);
	}

	@Override
	public int updateReleaseStatus(Achievement a) {
		a.setAuditStatus(AchievementAuditStatus.REVOKE.getCode());
//		if(a.getReleaseStatus()==1){
//			Calendar now = Calendar.getInstance();
//			now.set(Calendar.MILLISECOND, 0);
//			a.setReleaseDate(now.getTime());
//		}
		achievementDemandMapper.deleteByAchievementId(a.getId());
//		achievementKeywordMapper.batchDeleteByAchievementId(a.getId());
		achievementPublishMapper.deleteByAchievementId(a.getId());
		int i=0;
		i=achievementMapper.updateByPrimaryKeySelective(a);
		if(collectFlag)
		jtCollectSearchMapper.deleteByrowId(a.getId());
		if (StringUtils.isNotBlank(a.getOwnerId())) {
			AchievementDemandCount adc = achievementDemandCountMapper.selectByUid(a.getOwnerId());
			if (null != adc) {
				adc.setAchievementCount(adc.getAchievementCount() - 1);
				if (adc.getAchievementCount() < 0) {
					adc.setAchievementCount(0);
				}
				achievementDemandCountMapper.updateByPrimaryKeySelective(adc);
				
			}
		}
		return i;
	}

	@Override
	public AchievementEntity selectAppUserOwnerDetail(String id) {
		String uid=TokenManager.getUserId();
		return achievementMapper.selectAppAchuevementDetail(id,uid);
	}

	@Override
	public AchievementOrgOwnerDetailBo selectOrgOwnerDetail(String id) {
		return achievementMapper.selectOrgOwnerDetail(id);
	}
	
	@Override
	public AchievementUserOwnerDetailBo selectUserOwnerDetail(String id) {
		return achievementMapper.selectUserOwnerDetail(id);
	}

	@Override
	public List<DemandAchievementListBo> selectAchievementDemandListByAchievementId(String id) {
		return achievementDemandMapper.selectAchievementDemandListByAchievementId(id);
	}

	@Override
	public void insertImport(List<AchievementImportBo> data) {
		if (null == data || data.isEmpty()) {
			return;
		}
		Achievement a = null;
		AchievementKeyword ak = null;
		List<Achievement> achievementList = new ArrayList<>();
		List<AchievementKeyword> AchievementKeywordList = new ArrayList<>();
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		String techBrokerId = TokenManager.hasRole(AFTConstants.TECHBROKER) ? TokenManager.getAdminId() : null;
		for (AchievementImportBo bo : data) {
			a = new Achievement();
			BeanUtils.copyProperties(bo, a);
			a.setId(UUID.randomUUID().toString());
			a.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			a.setCreateTime(now.getTime());
			a.setAuditStatus(AchievementAuditStatus.SUBMIT.getCode());
			a.setReleaseStatus(AchievementReleaseStatus.UNRELEASE.getCode());
			a.setTechBrokerId(techBrokerId);
			List<String> keywordsList = bo.getKeywords();
			if (null != keywordsList && keywordsList.size() > 0) {
				for (String s : keywordsList) {
					if (!StringUtils.isBlank(s)) {
						ak = new AchievementKeyword();
						ak.setAchievementId(a.getId());
						ak.setKeyword(s.trim());
						ak.setId(UUID.randomUUID().toString());
						AchievementKeywordList.add(ak);
					}
				}
			}
			achievementList.add(a);
		}

		achievementMapper.insertBatch(achievementList);
		achievementKeywordMapper.insertBatch(AchievementKeywordList);
	}

	@Override
	public AchievementDetailBo selectAchievementDetail(String uid, String id) {
		return achievementMapper.selectAchievementDetail(uid, id);
	}

	private void createTechBorkerNotice(Achievement a) {
		// noticeMapper.insert(disposeNotice(a, null));
	}

	// 给所有审核员发送审核通知
	private void createAuditorNotice(Achievement a) {
		List<String> ids = userRoleMapper.listAuditor();
		List<Notice> list = new ArrayList<>();
		if (null != ids && ids.size() > 0) {
			for (String s : ids) {
				list.add(disposeNotice(a, s));
			}
			noticeMapper.insertBatch(list);
		}
	}

	private Notice disposeNotice(Achievement a, String aid) {
		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());
		n.setRid(a.getId());
		if (StringUtils.isBlank(aid)) {
			n.setAid(a.getTechBrokerId());
			if (UserType.PERSONAL.getCode().equals(a.getOwnerType())) {
				n.setContent("编号" + a.getSerialNumber() + NoticeStatus.PERSONALACHIEVEMENTT.getDesc() + " "
						+ (AchievementAuditStatus.AUDITED.getCode().equals(a.getAuditStatus())
								? AchievementAuditStatus.AUDITED.getDesc()
								: AchievementAuditStatus.UNAUDITED.getDesc()));
				n.setNoticeType(NoticeStatus.PERSONALACHIEVEMENTT.getCode());
			} else if (UserType.ORGANIZATION.getCode().equals(a.getOwnerType())) {
				n.setContent("编号" + a.getSerialNumber() + NoticeStatus.ORGANIZATIONACHIEVEMENT.getDesc() + " "
						+ (AchievementAuditStatus.AUDITED.getCode().equals(a.getAuditStatus())
								? AchievementAuditStatus.AUDITED.getDesc()
								: AchievementAuditStatus.UNAUDITED.getDesc()));
				n.setNoticeType(NoticeStatus.ORGANIZATIONACHIEVEMENT.getCode());
			}
		} else {
			n.setAid(aid);
			if (UserType.PERSONAL.getCode().equals(a.getOwnerType())) {
				n.setContent(
						NoticeStatus.PERSONALACHIEVEMENTT.getDesc() + " " + AchievementAuditStatus.SUBMIT.getDesc());
				n.setNoticeType(NoticeStatus.PERSONALACHIEVEMENTT.getCode());
			} else if (UserType.ORGANIZATION.getCode().equals(a.getOwnerType())) {
				n.setContent(
						NoticeStatus.ORGANIZATIONACHIEVEMENT.getDesc() + " " + AchievementAuditStatus.SUBMIT.getDesc());
				n.setNoticeType(NoticeStatus.ORGANIZATIONACHIEVEMENT.getCode());
			}
		}
		return n;
	}

	private void disposeAchievementKeyword(String[] keywords, Achievement a, boolean delete) {
		if (null != keywords && keywords.length > 0) {
			if (delete) {
				achievementKeywordMapper.batchDeleteByAchievementId(a.getId());
			}
			List<AchievementKeyword> list = new ArrayList<>();
			AchievementKeyword ak = null;
			for (int i = 0; i < keywords.length; i++) {
				ak = new AchievementKeyword();
				ak.setId(UUID.randomUUID().toString());
				ak.setAchievementId(a.getId());
				ak.setKeyword(keywords[i].trim());
				list.add(ak);
			}
			achievementKeywordMapper.insertBatch(list);
		}
	}

	@Override
	public int updateMatchDemand(Achievement a) {
		achievementDemandMapper.deleteByAchievementId(a.getId());// 删除之前匹配单
		List<AchievementKeyword> achievement = achievementKeywordMapper.selectKeywordsByAchievementId(a.getId());
		if (null != achievement && achievement.size() > 0) {
			List<String> keyword = new ArrayList<>();
			for (AchievementKeyword k : achievement) {
				if (!StringUtils.isBlank(k.getKeyword())) {
					keyword.add(k.getKeyword());
				}
			}
			List<AchievementDemand> list = demandKeywordMapper.selectAchievementDemand(keyword);
			if (null != list && list.size() > 0) {
				for (AchievementDemand ad : list) {
					ad.setAchievementId(a.getId());
				}
				return achievementDemandMapper.insertBatch(list);
			}
		}
		return 0;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AchievementPartnerListBo> listPartnerAchievement(String ownerId, Integer pNo, Integer pSize) {
		Map<String, Object> params = new HashMap<>();

		params.put("ownerId", ownerId);

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

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		return (Pagination<AchievementPartnerListBo>) findPage("findPartnerAchievementListByPage",
				"findPartnerAchievementCount", params, pNo, pSize);
	}

	@Override
	public AchievementPortalDetailBo findUserPortalAchievementDetail(String id) {
		return achievementMapper.findUserPortalAchievementDetail(id, TokenManager.getUserId());
	}

	@Override
	public AchievementPortalDetailBo findOrgPortalAchievementDetail(String id) {
		return achievementMapper.findOrgPortalAchievementDetail(id, TokenManager.getUserId());
	}

	@Override
	public int updateByPrimaryKeySelective(Achievement a) {
		return achievementMapper.updateByPrimaryKeySelective(a);
	}

	@CacheEvict(value = "internationalAchievementList", allEntries = true)
	public void cleanInternationalAchievement() {
		LoggerUtils.debug(logger, "清除国际化技术列表");
	}

	@Override
	public Achievement selectAchievementDetail(String id) {
		return achievementMapper.selectByPrimaryKey(id);
	}


	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AchievementPartnerListBo> listAppUserAchievement(Integer auditStatus, Integer serialNumber,
			String name, String keyword,Integer dataCategory, Integer category, Integer ownerType, Integer status,
			String releaseDateStartDate, String releaseDateEndDate, Integer releaseStatus,String ownerId,Integer fieldA, Integer pNo, Integer pSize) {
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		Map<String, Object> params=disposeParams(ownerType,null, null, ownerId, auditStatus, serialNumber, name, keyword, category,
				status, releaseDateStartDate, releaseDateEndDate,null, null,  releaseStatus, null, null,null, null,null);
		if (null!=fieldA) {
			params.put("fieldA", fieldA);
		}
		if (null != dataCategory) {
			params.put("dataCategory", 	String.valueOf(dataCategory));
		}											
		if (null != TokenManager.getUserId()) params.put("uid", TokenManager.getUserId());
		
		Pagination<AchievementPartnerListBo> p=(Pagination<AchievementPartnerListBo>) findPage("findAppAchievementListByPage", "findAppAchievementCount",
				params,pNo, pSize);
		
		return p;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AchievementPartnerListBo> listAppMyAchievement(Integer pNo, Integer pSize) {
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}
		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		Map<String, Object> params = new HashMap<>();
		if (StringUtils.isNotBlank(TokenManager.getUserId())) {
			params.put("ownerId", TokenManager.getUserId());
		}
		//params.put("ownerId", "46433140-0a90-471e-a32f-6bc89c562e3d");
		return (Pagination<AchievementPartnerListBo>) findPage("findMyAchievementListByPage", "findMyAchievementCount",
				params,pNo, pSize);
	}

	@Override
	public int saveAppAchievement(Achievement a, String[] keywords) {
		a.setId(UUID.randomUUID().toString());
		a.setDeletedSign(DeleteStatus.UNDELETE.getCode());
		a.setInfoSources(1);
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		a.setReleaseStatus(AchievementReleaseStatus.UNRELEASE.getCode());
		if (AchievementAuditStatus.SUBMIT.getCode().equals(a.getAuditStatus())) {
			createAuditorNotice(a);
		} else {
			a.setAuditStatus(AchievementAuditStatus.SUBMIT.getCode());
		}
		if (null!=TokenManager.getUserId()) {
			a.setOwnerId(TokenManager.getUserId());
			User u=userMapper.selectByPrimaryKey(TokenManager.getUserId());
			if (null!=u.getType()) {
				a.setOwnerType(u.getType());
			}if (StringUtils.isNotBlank(u.getMobile())) {
				a.setOwnerMobile(u.getMobile());
			}if (StringUtils.isNotBlank(u.getNickname())) {
				a.setOwnerName(u.getNickname());
			}
		}
		a.setCreateTime(now.getTime());
		disposeAchievementKeyword(keywords, a, false);
		return achievementMapper.insert(a);
	}

	@Override
	public List<AchievementObject> recentAchievements(int size, String url, String showLocation) {
		// TODO Auto-generated method stub
		return achievementMapper.getRecentAchievements(size,url,showLocation);
	}

	@Override
	public List<AchievementObject> getHotAchievements(int size, String url, String showLocation) {
		// TODO Auto-generated method stub
		return achievementMapper.getHotAchievements( size,  url,  showLocation);
	}

	@Override
	public List<AchievementObject> getPatentList(int size, String url, String showLocation) {
		// TODO Auto-generated method stub
		return achievementMapper.getPatentList(size,url,showLocation);
	}

	@Override
	public List<AchievementObject> getPracticalTechnologys(int size, String url, String showLocation) {
		// TODO Auto-generated method stub
		return achievementMapper.getPracticalTechnologys(size,url,showLocation);
	}

	@Override
	public List<PolicyEntity> getIntellectualProperty(int size) {
		// TODO Auto-generated method stub
		return achievementMapper.getIntellectualProperty(size);
	}

	@Override
	public AchievementObject getAchievementDetail(String id, Integer type) {
		// TODO Auto-generated method stub
		return achievementMapper.getAchievementDetail(id,type);
	}

	@Override
	public List<AchievementObject> getBoutiquePatent(int size,int deletedSign) {
		// TODO Auto-generated method stub
		return achievementMapper.getBoutiquePatent( size,deletedSign);
	}

	@Override
	public List<AchievementObject> guessYouLike(int size) {
		// TODO Auto-generated method stub
		return achievementMapper.guessYouLike(size);
	}

	@Override
	public AchievementResultObject getAchievementDetailById(String id) {
		// TODO Auto-generated method stub
		return achievementMapper.getAchievementDetailById(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AchievementObject> listAchievement(String name, String ownerName, Integer category,
			Integer dataCategory, Integer auditStatus, String startDate, String endDate, Integer pageNo,
			Integer pageSize) {
		Map<String,Object> params = new HashMap<>();
		if (null != startDate) params.put("startDate", startDate);
		if (null != endDate) params.put("endDate", endDate);
		if (null != auditStatus) params.put("auditStatus", auditStatus);
		if (null != category) params.put("category", category);
		if (null != dataCategory) params.put("dataCategory", dataCategory);
		if (StringUtils.isNotBlank(name)) params.put("name", name);
		if (StringUtils.isNotBlank(ownerName)) params.put("ownerName", ownerName);
		return (Pagination<AchievementObject>) findPage("listMyAchievementByPage", "listMyAchievementCount",params,
				pageNo, pageSize);
	}

	@Override
	public int updateAuditAchievement(String id, Integer auditResult,String auditInfo) {
		// TODO Auto-generated method stub
		int auditStatus=AchievementAuditStatus.AUDITED.getCode().intValue();
		if(auditResult.intValue() == 0) {
			auditStatus=AchievementAuditStatus.UNAUDITED.getCode().intValue();
			if(collectFlag)jtCollectSearchMapper.deleteByrowId(id);
		}
		else {
			auditStatus=AchievementAuditStatus.AUDITED.getCode().intValue();
			if(collectFlag){
			Achievement a=achievementMapper.selectByPrimaryKey(id);
			JtCollectSearch r=new JtCollectSearch();
			r.setFromTable(collectType.ACHIEVEMENT.getDesc());
			r.setKeyword(a.getKeyword());
			r.setTitle(a.getName());
			r.setRowId(a.getId());
			String sum = a.getIntroduction();
			if(null != sum && sum.length() > 40){
				sum = sum.substring(0,40) + "...";
			}
			r.setSummary(sum);
			jtCollectSearchMapper.insertSelective(r);
		}
		}
		
		Achievement achievement=new Achievement();
		achievement.setId(id);
		achievement.setAuditStatus(auditStatus);
		achievement.setAuditInfo(auditInfo);
		achievement.setReleaseDate(new Date());
		achievementMapper.updateByPrimaryKeySelective(achievement);
		
		return auditStatus;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AchievementObject> getAchievementObjects(AchievementObject achievementObject,Integer pageNo,Integer pageSize) {
	if(pageNo==null ||pageNo<1)pageNo=1;
	if(pageSize== null ||pageSize<1)pageSize=10;
		// TODO Auto-generated method stub
		return (Pagination<AchievementObject>)findPage("findAchievementListWithPid","findAchievementCountWithPid",disposeAchievementParams(achievementObject), pageNo, pageSize); 
	}
	 private Map<String, Object> disposeAchievementParams(AchievementObject achievementObject) {
		 Map<String, Object> params=new HashMap<String,Object>();
		 if(null !=achievementObject.getName()) {
			 params.put("name", achievementObject.getName());
		 }
		 
		 if(null != achievementObject.getFieldA())
		 {
			 params.put("fieldA", achievementObject.getFieldA());
		 }
		 if(null != achievementObject.getFieldB()) {
			 params.put("fieldB", achievementObject.getFieldB());
		 }
		 if(null != achievementObject.getDeletedSign()) {
			 params.put("deletedSign", achievementObject.getDeletedSign());
		 }else{
			 params.put("deletedSign", 0);//未删除的数据
		 }
		 return params;
		
	}
	
	 @Override
		public List<AchievementPartnerListBo> findPartnerAchievementList(String uid) {
			return achievementMapper.findPartnerAchievementListByPage(uid);
		}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AchievementObject> listInterestedAchievement(Integer pageNo, Integer pageSize) {
		if(pageNo==null ||pageNo<1)pageNo=1;
		if(pageSize== null ||pageSize<1)pageSize=10;
		 Map<String, Object> params=new HashMap<String,Object>();
		 params.put("uid", TokenManager.getUserId());
		 //params.put("uid", "1180fa62-7c42-44be-bc41-5583814d69f4");
		return (Pagination<AchievementObject>) findPage("listInterestedAchievement", "listInterestedAchievementCount", params, pageNo, pageSize);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<MyCollection> myCollectionAchievement(Integer pageNo, Integer pageSize) {
		if(pageNo==null ||pageNo<1)pageNo=1;
		if(pageSize== null ||pageSize<1)pageSize=10;
		 Map<String, Object> params=new HashMap<String,Object>();
		 params.put("uid", TokenManager.getUserId());
//		 params.put("uid", "1180fa62-7c42-44be-bc41-5583814d69f4");
		return (Pagination<MyCollection>) findPage("myCollectionAchievementList", "myCollectionAchievementCount", params, pageNo, pageSize);
	}
	 
	 
	 

}
