package com.goafanti.achievement.service.impl;

import com.goafanti.achievement.bo.*;
import com.goafanti.achievement.service.AchievementService;
import com.goafanti.common.constant.AFTConstants;
import com.goafanti.common.dao.*;
import com.goafanti.common.enums.*;
import com.goafanti.common.model.*;
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.customer.bo.CustomerOrganizationDetailBo;
import com.goafanti.customer.bo.CustomerPersonalDetailBo;
import com.goafanti.demand.bo.DemandAchievementListBo;
import com.goafanti.portal.bo.*;
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.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.*;

@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 AchievementInterestMapper	achievementInterestMapper;
	@Autowired
	private UserMapper					userMapper;
	

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

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AchievementListBo> listUserOwnerAchievement(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 pNo, Integer pSize,
			Integer boutique, Integer hot) {
		Map<String, Object> params = disposeParams(ownerType,username, ownerName, ownerId, auditStatus, serialNumber, name, keyword, category, status,
				releaseDateStartDate, releaseDateEndDate, createDateStartDate,  createDateEndDate, releaseStatus, UserType.ORGANIZATION.getCode(),
				boutique,null, hot,null);
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		if (!TokenManager.hasRole(AFTConstants.SUPERADMIN) && !TokenManager.hasRole(AFTConstants.AUDITORADMIN)) {
			params.put("adminId", TokenManager.getAdminId());
		}
		
		return (Pagination<AchievementListBo>) findPage("findUserOwnerAchievementListByPage",
				"findUserOwnerAchievementCount",params,
				pNo, pSize);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AchievementListBo> listOrgOwnerAchievement(Integer ownerType,String unitName, 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, String internationalFlag,Integer pNo, Integer pSize,
			Integer boutique, Integer hot,String recordPerson) {
		Map<String, Object> params = disposeParams(ownerType,unitName, ownerName, ownerId, auditStatus, serialNumber, name, keyword, category, status,
				releaseDateStartDate, releaseDateEndDate, createDateStartDate,  createDateEndDate, releaseStatus, UserType.ORGANIZATION.getCode(),
				boutique,internationalFlag, hot,recordPerson);
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		
		return (Pagination<AchievementListBo>) findPage("findOrgOwnerAchievementListByPage",
				"findOrgOwnerAchievementCount",params,pNo, pSize);
	}

	@SuppressWarnings("unused")
	@Override
	public void saveAchievement(Achievement a, String[] keywords) {
		a.setId(UUID.randomUUID().toString());
		a.setDeletedSign(DeleteStatus.UNDELETE.getCode());
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		CustomerPersonalDetailBo up= new CustomerPersonalDetailBo();
		CustomerOrganizationDetailBo uo=new CustomerOrganizationDetailBo();
		if (TokenManager.getToken() instanceof Admin) {
			a.setTechBrokerId(TokenManager.getAdminId());
		}
		a.setReleaseStatus(AchievementReleaseStatus.UNRELEASE.getCode());

		if (AchievementAuditStatus.SUBMIT.getCode().equals(a.getAuditStatus())) {
			a.setAuditStatus(DemandAuditStatus.INAUDIT.getCode());
			createAuditorNotice(a);
		} else {
			a.setAuditStatus(AchievementAuditStatus.CREATE.getCode());
		}
		Integer ownerType = a.getOwnerType();
		String ownerMobile = a.getOwnerMobile();
		String ownerName = a.getOwnerName();
		String ownerId = "";
		if (TokenManager.getToken() instanceof User) {
			a.setOwnerId(TokenManager.getUserId());
			User u=userMapper.queryById(TokenManager.getUserId());
			if (null != u) {
				ownerId = u.getId();
				if(ownerType == null) ownerType = u.getType();
				if(StringUtils.isBlank(ownerMobile)) ownerMobile = u.getMobile();
				if(StringUtils.isBlank(ownerName)) ownerName = u.getNickname();
				// 如果是单位客户 -查询单位客户的邮件 和通讯地址、证件号码
				//or 
				//如果是个人 。。。
				if(ownerType==1){
					 uo=userMapper.findOrganizationCustomerDetail(ownerId);
				}else if (ownerType==0){
					up=userMapper.findPersonalCustomerDetail(ownerId);
				}
			}
		} 
		a.setCreateTime(now.getTime());
		a.setOwnerType(ownerType);
		a.setOwnerMobile(ownerMobile);
		a.setOwnerName(ownerName);
		a.setOrgId(ownerId);
		//设置邮件和。。。
		/*if(ownerType==1){
			a.setOrgEmail(uo.getLegalPersonEmail());
			a.setOwnerPostalAddress(uo.getPostalAddress());
			a.setOwnerIdNumber(uo.getLicenceNumber());
		}else if(ownerType==0){
			a.setOrgEmail(up.getEmail());
			a.setOwnerPostalAddress(up.getPostalAddress());
			a.setOwnerIdNumber(up.getIdNumber());
		}*/
		
		achievementMapper.insert(a);
		disposeAchievementKeyword(keywords, a, false);
	}

	@Override
	public int updateAchievement(Achievement a, String[] keywords, Integer switchSign) {
		if (AchievementAuditStatus.SUBMIT.getCode().equals(a.getAuditStatus())) {
			a.setAuditStatus(DemandAuditStatus.INAUDIT.getCode());
			createAuditorNotice(a);
		}
		disposeAchievementKeyword(keywords, a, true);
		achievementMapper.updateByPrimaryKeySelective(a);
		if (null != switchSign && AchievementSwitchSign.CLOSE.getCode().equals(switchSign)) {
			achievementMapper.updateOwnerId(a.getId());
		}
		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);
		for (String s : id) {
			Achievement a = achievementMapper.selectByPrimaryKey(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<AchievementListBo> listUserAchievement(Integer auditStatus, Integer serialNumber, String name,
			String keyword, Integer category, Integer ownerType, Integer status, String releaseDateStartDate,
			String releaseDateEndDate,String createDateStartDate, String createDateEndDate, Integer releaseStatus, Integer pNo, Integer pSize) {
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		return (Pagination<AchievementListBo>) findPage("findAchievementListByPage", "findAchievementCount",
				disposeParams(ownerType,null, null, TokenManager.getUserId(), auditStatus, serialNumber, name, keyword, category,
						status, releaseDateStartDate, releaseDateEndDate,createDateStartDate,createDateEndDate, releaseStatus, null, null,null, null,null),
				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);
		}
		if (!TokenManager.hasRole(AFTConstants.SUPERADMIN) && !TokenManager.hasRole(AFTConstants.AUDITORADMIN)) {
			params.put("techBrokerId", TokenManager.getAdminId());
		}
		
		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.AUDITED.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());
		int i=0;
		i=achievementMapper.updateByPrimaryKeySelective(a);
		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 AchievementUserOwnerDetailBo selectAppUserOwnerDetail(String id) {
		AchievementUserOwnerDetailBo a=achievementMapper.selectUserOwnerDetail(id);
		int i=achievementMapper.countInterest(a.getId());
		a.setCountInterest(String.valueOf(i));
		String uid=TokenManager.getUserId();
		if(TokenManager.isLogin()&&achievementInterestMapper.checkUidAndDid(uid,id)>0){
			a.setInterest("1");
		}else {
			a.setInterest("0");
		}
		return a;
	}

	@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.INAUDIT.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);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AchievementSearchListBo> listAchievementSearchList(String url,String keyword, Integer dataCategory,
			Integer category, Integer fieldA, String transferMode, Integer pNo, Integer pSize, Integer dateSort,
			String upperPrice, String lowerPrice,Integer internationalFlag) {
		Map<String, Object> params = new HashMap<>();
		if (!StringUtils.isBlank(url)) {
			params.put("url", url);
		}
		if (!StringUtils.isBlank(keyword)) {
			params.put("keyword", keyword);
		}

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

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

		if (!StringUtils.isBlank(transferMode)) {
			params.put("transferMode", transferMode);
		}
		if (dateSort != null) {
			params.put("dateSort", dateSort);
		}
		if (upperPrice != null) {
			params.put("upperPrice", upperPrice);
		}
		if (lowerPrice != null) {
			params.put("lowerPrice", lowerPrice);
		}
		if (null !=internationalFlag ) {
			params.put("internationalFlag", internationalFlag);
		}
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 20) {
			pSize = 20;
		}
		Pagination<AchievementSearchListBo> result = (Pagination<AchievementSearchListBo>) findPage(
				"findSearchAchievementListByPage", "findSearchAchievementCount", params, pNo, pSize);
		List<AchievementSearchListBo> AchievementSearchList = (List<AchievementSearchListBo>) result.getList();
		for (int i = 0; i < AchievementSearchList.size(); i++) {
			String introduction = AchievementSearchList.get(i).getIntroduction();
			if (introduction != null)
				introduction = introduction.length() > 20 ? introduction.substring(0, 20) + "... ..." : introduction;

		}
		return result;
	}

	@Override
	public AchievementDetailBo selectAchievementSearchDetail(String uid, String id) {
		return achievementMapper.selectAchievementSearchDetail(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 List<AchievementPortalSimilarListBo> findByFieldA(Integer fieldA, String id, Integer type) {
		if (UserType.PERSONAL.getCode().equals(type)) {
			return achievementMapper.findUserPortalSimilarByFieldA(fieldA, id);
		} else if (UserType.ORGANIZATION.getCode().equals(type)) {
			return achievementMapper.findOrgPortalSimilarByFieldA(fieldA, id);
		}
		return null;
	}

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

	@Override
	@Cacheable(value = "internationalAchievementList", key = "'internationalAchievementList:'+#internationalAchievementCacheKey")
	public List<InternationalListBo> selectInternationalAchievement(Integer internationalAchievementCacheKey) {
		return achievementMapper.selectInternationalAchievement();
	}

	@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<BoutiqueListBo> boutiqueSearchList(Integer dataCategory, Integer category, Integer fieldA,
			Integer pNo, Integer pSize) {
		Map<String, Object> params = new HashMap<>();
		if (null != dataCategory) {
			params.put("dataCategory", dataCategory);
		}
		if (null != category) {
			params.put("category", category);
		}
		if (null != fieldA) {
			params.put("fieldA", fieldA);
		}
		return (Pagination<BoutiqueListBo>) findPage("findBoutiqueListByPage", "findBoutiqueCount", params, pNo, pSize);
	}

	@Override
	public List<AchievementListBo> getAchievement(Integer boutique) {
		return achievementMapper.listAchievement();
	}

	@Override
	public List<AchievementListBo> getPerhapLike() {
		return achievementMapper.selectCsutomerLike(); //查询出猜你喜欢
	}

	@Override
	public List<AchievementPartnerListBo> findPartnerAchievementList(String uid) {
		return achievementMapper.findPartnerAchievementListByPage(uid);
	}

	@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", dataCategory);
		}																					
		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);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AchievementListBo> listMyAchievement(String techBrokerId,Integer ownerType,String unitName, 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, String internationalFlag,Integer pNo, Integer pSize,
			Integer boutique, Integer hot) {
		Map<String, Object> params = disposeParams(ownerType,unitName, ownerName, ownerId, auditStatus, serialNumber, name, keyword, category, status,
				releaseDateStartDate, releaseDateEndDate, createDateStartDate,  createDateEndDate, releaseStatus, UserType.ORGANIZATION.getCode(),
				boutique,internationalFlag, hot,null);
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		
		if (null != techBrokerId) {
			params.put("techBrokerId", techBrokerId);
		}
		
		return (Pagination<AchievementListBo>) findPage("findMyyAchievementListByPage",
				"findMyyAchievementCount",params,pNo, pSize);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AchievementListBo> listManageAchievement(String techBrokerId,Integer ownerType,String unitName, 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, String internationalFlag,Integer pNo, Integer pSize,
			Integer boutique, Integer hot,String recordPerson) {
		Map<String, Object> params = disposeParams(ownerType,unitName, ownerName, ownerId, auditStatus, serialNumber, name, keyword, category, status,
				releaseDateStartDate, releaseDateEndDate, createDateStartDate,  createDateEndDate, releaseStatus, UserType.ORGANIZATION.getCode(),
				boutique,internationalFlag, hot,recordPerson);
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		
		if (null != techBrokerId) {
			params.put("techBrokerId", techBrokerId);
		}
		
		return (Pagination<AchievementListBo>) findPage("findManageAchievementListByPage",
				"findManageAchievementCount",params,pNo, pSize);
	}

	@Override
	public int saveAppAchievement(Achievement a, String[] keywords) {
		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().equals(a.getAuditStatus())) {
			a.setAuditStatus(DemandAuditStatus.INAUDIT.getCode());
			createAuditorNotice(a);
		} else {
			a.setAuditStatus(AchievementAuditStatus.INAUDIT.getCode());
		}
		if (null!=TokenManager.getUserId()) {
			a.setOwnerId(TokenManager.getUserId());
			User u=userMapper.queryById(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.setDataCategory(0);
		a.setCreateTime(now.getTime());
		disposeAchievementKeyword(keywords, a, false);
		return achievementMapper.insert(a);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<AchievementListBo> listUserAchievement(String uid, Integer pageNo, Integer pageSize) {
		if (pageNo == null || pageNo < 0) {
			pageNo = 1;
		}

		if (pageSize == null || pageSize < 0 ) {
			pageSize = 10;
		}
		Map<String, Object> params=new HashMap<>();
		params.put("ownerId", uid);
		return (Pagination<AchievementListBo>) findPage("findOrgOwnerAchievementListByPage",
				"findOrgOwnerAchievementCount",params,pageNo, pageSize);
	}

}
