package com.goafanti.demand.service.impl;

import com.goafanti.achievement.bo.AchievementDemandListBo;
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.AsyncUtils;
import com.goafanti.common.utils.DateUtils;
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.*;
import com.goafanti.demand.service.DemandService;
import com.goafanti.portal.bo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


@Service
public class DemandServiceImpl extends BaseMybatisDao<DemandMapper> implements DemandService {
	@Autowired
	private DemandMapper					demandMapper;
	@Autowired
	private UserMapper						userMapper;

	@Autowired
	private UserRoleMapper					userRoleMapper;
	@Autowired
	private DemandKeywordMapper				demandKeywordMapper;
	@Autowired
	private AchievementDemandMapper			achievementDemandMapper;
	@Autowired
	private AchievementKeywordMapper		achievementKeywordMapper;
	@Autowired
	private AchievementDemandCountMapper	achievementDemandCountMapper;
	@Autowired
	private UserIdentityMapper				userIdentityMapper;
	@Autowired
	private OrganizationIdentityMapper		organizationIdentityMapper;
	@Autowired
	private AchievementMapper			 	achievementMapper;
	@Autowired
	private FieldGlossoryMapper 			fieldGlossoryMapper;

	@Autowired
	private DemandInterestMapper			demandInterestMapper;
	@Autowired
	private NewsInterestMapper	newsInterestMapper;
	@Autowired
	private UserInterestMapper	userInterestMapper;
	@Autowired
	ProjectInterestMapper	projectInterestMapper;
	@Autowired
	AsyncUtils	asyncUtils;


	DemandFollowDetailMapper	demandFollowDetailMapper;

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<DemandManageListBo> selectUserDemandManageList(String employerName, Integer auditStatus,
			Integer province, Integer serialNumber, String name, String keyword, Integer infoSources,
			Integer demandType, String validityPeriodStartDate, String validityPeriodEndDate, String username,
			Integer status, Integer releaseStatus, String releaseDateStartDate, String releaseDateEndDate,String createDateStartDate, String createDateEndDate, Integer pNo,
			Integer pSize, Integer boutique, Integer hot) {

		Map<String, Object> params = disposeParams(auditStatus, province, serialNumber, name, keyword, infoSources,
				demandType, validityPeriodStartDate, validityPeriodEndDate, username, status, releaseStatus,
				releaseDateStartDate, releaseDateEndDate, createDateStartDate,  createDateEndDate, boutique, hot);

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

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}

		/*
		 * if (TokenManager.hasRole(AFTConstants.SALESMANAGERADMIN) ||
		 * TokenManager.hasRole(AFTConstants.SALESMANADMIN)) {
		 * params.put("principal", TokenManager.getAdminId()); }
		 *
		 * if (TokenManager.hasRole(AFTConstants.MANAGERADMIN)) {
		 * params.put("mid", TokenManager.getAdminId()); }
		 *
		 * if (TokenManager.hasRole(AFTConstants.TECHBROKER)) {
		 * params.put("techBroker", TokenManager.getAdminId()); }
		 */

		if (!TokenManager.hasRole(AFTConstants.SUPERADMIN) && !TokenManager.hasRole(AFTConstants.AUDITORADMIN)) {
			params.put("adminId", TokenManager.getAdminId());
		}

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

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

		return (Pagination<DemandManageListBo>) findPage("findManageUserDemandListByPage", "findManageUserDemandCount",
				params, pNo, pSize);

	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<DemandManageListBo> selectOrgDemandManageList(Integer dataCategory,String employerName, Integer auditStatus,
			Integer province, Integer serialNumber, String name, String keyword, Integer infoSources,
			Integer demandType, String validityPeriodStartDate, String validityPeriodEndDate, String username,
			Integer status, Integer releaseStatus, String releaseDateStartDate, String releaseDateEndDate,String createDateStartDate, String createDateEndDate, Integer pNo,
			Integer pSize, Integer boutique, Integer hot, String techBrokerId,String recordPerson) {
		Map<String, Object> params = disposeParams(auditStatus, province, serialNumber, name, keyword, infoSources,
				demandType, validityPeriodStartDate, validityPeriodEndDate, username, status, releaseStatus,
				releaseDateStartDate, releaseDateEndDate, createDateStartDate,  createDateEndDate, boutique, hot);
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}
		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		/*if (TokenManager.hasRole(AFTConstants.SALESMANAGERADMIN) || TokenManager.hasRole(AFTConstants.SALESMANADMIN)) {
			params.put("principal", TokenManager.getAdminId());
		}

		if (TokenManager.hasRole(AFTConstants.MANAGERADMIN)) {
			params.put("mid", TokenManager.getAdminId());
		}

		if (TokenManager.hasRole(AFTConstants.TECHBROKER)) {
			params.put("techBroker", TokenManager.getAdminId());
		}*/
		if (null != dataCategory) {
			params.put("dataCategory", dataCategory);
		}
		if (null!=recordPerson) {
			params.put("recordPerson",  recordPerson);
		}
		/*if (!TokenManager.hasRole(AFTConstants.SUPERADMIN) && !TokenManager.hasRole(AFTConstants.AUDITORADMIN)) {
			params.put("adminId", TokenManager.getAdminId());
		}*/
		if (StringUtils.isNotBlank(employerName)) {
			params.put("employerName", employerName);
		}
		if (StringUtils.isNotBlank(username)) {
			params.put("unitName", username);
		}
		return (Pagination<DemandManageListBo>) findPage("findManageOrgDemandListByPage", "findManageOrgDemandCount",
				params, pNo, pSize);
	}

	@Override
	public void saveUserDemand(Demand d, String validityPeriodFormattedDate, String[] keywords) {
		Date validityPeriod = null;
		if (!StringUtils.isBlank(validityPeriodFormattedDate)) {
			try {
				validityPeriod = DateUtils.parseDate(validityPeriodFormattedDate, AFTConstants.YYYYMMDD);
			} catch (ParseException e) {
			}
		}

		d.setValidityPeriod(validityPeriod);
		d.setId(UUID.randomUUID().toString());
		d.setTechBrokerId(TokenManager.getAdminId());

		d.setDeletedSign(DeleteStatus.UNDELETE.getCode());

		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		d.setStatus(DemandStatus.UNRESOLVED.getCode());
		d.setReleaseStatus(DemandReleaseStatus.UNRELEASE.getCode());

		d.setPrincipalId(TokenManager.getAdminId());
		if (DemandAuditStatus.SUBMIT.getCode().equals(d.getAuditStatus())) {
			d.setAuditStatus(DemandAuditStatus.INAUDIT.getCode());
			createAuditorNotice(d);
		} else {
			d.setAuditStatus(DemandAuditStatus.CREATE.getCode());
		}

		d.setCreateTime(now.getTime());
		demandMapper.insert(d);
		disposeDemandKeyword(keywords, d, false);
	}

	@Override
	public int updateUserDemand(Demand d, String validityPeriodFormattedDate, String[] keywords, Integer switchSign) {
		Date validityPeriod = null;
		if (!StringUtils.isBlank(validityPeriodFormattedDate)) {
			try {
				validityPeriod = DateUtils.parseDate(validityPeriodFormattedDate, AFTConstants.YYYYMMDD);
			} catch (ParseException e) {
			}
		}
		d.setValidityPeriod(validityPeriod);

		if (DemandAuditStatus.SUBMIT.getCode().equals(d.getAuditStatus())) {
			d.setAuditStatus(DemandAuditStatus.INAUDIT.getCode());
			createAuditorNotice(d);
		}
		disposeDemandKeyword(keywords, d, true);
		demandMapper.updateByPrimaryKeySelective(d);
		if (null != switchSign && DemandSwitchSign.CLOSE.getCode().equals(switchSign)) {
			demandMapper.updateEmployerId(d.getId());
		}
		return 1;
	}

	@Override
	public DemandManageDetailBo selectUserDemandDetail(String id) {
		return demandMapper.selectUserDemandDetail(id);
	}

	@Override
	public int deleteByPrimaryKey(List<String> id) {
		demandKeywordMapper.batchDeleteByDemandIds(id);
		achievementDemandMapper.batchDeleteByDemandIds(id);
		for (String s : id) {
			Demand d = demandMapper.selectByPrimaryKey(s);
			if (null != d && DemandAuditStatus.AUDITED.getCode().equals(d.getAuditStatus())
					&& StringUtils.isNotBlank(d.getEmployerId())) {
				AchievementDemandCount adc = achievementDemandCountMapper.selectByUid(d.getEmployerId());
				if (null != adc) {
					adc.setDemandCount(adc.getDemandCount() - 1);
					if (adc.getDemandCount() < 0) {
						adc.setDemandCount(0);
					}
					achievementDemandCountMapper.updateByPrimaryKeySelective(adc);
				}
			}
		}
		return demandMapper.batchDeleteByPrimaryKey(id);
	}

	@Override
	public DemandManageDetailBo selectOrgDemandDetail(String id) {

		return demandMapper.selectOrgDemandDetail(id);
	}

	@Override
	public Demand selectByPrimaryKey(String id) {
		return demandMapper.selectByPrimaryKey(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<DemandListBo> listDemand(Integer auditStatus, Integer serialNumber, String name, String keyword,
			Integer demandType, String validityPeriodStartDate, String validityPeriodEndDate, Integer status,
			Integer releaseStatus, String releaseDateStartDate, String releaseDateEndDate,String createDateStartDate, String createDateEndDate, Integer pNo, Integer pSize) {
		Map<String, Object> params = disposeParams(auditStatus, null, serialNumber, name, keyword, null, demandType,
				validityPeriodStartDate, validityPeriodEndDate, null, status, releaseStatus, releaseDateStartDate,
				releaseDateEndDate, createDateStartDate, createDateEndDate, null, null);

		params.put("employerId", TokenManager.getUserId());

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

		if (pSize == null || pSize < 0) {
			pSize = 10;
		}
		return (Pagination<DemandListBo>) findPage("findDemandListByPage", "findDemandCount", params, pNo, pSize);
	}

	@Override
	public int updateReleaseStatus(Demand d) {
		d.setAuditStatus(DemandAuditStatus.AUDITED.getCode());
		if(d.getReleaseStatus()==1){
			Calendar now = Calendar.getInstance();
			now.set(Calendar.MILLISECOND, 0);
			d.setReleaseDate(now.getTime());
		}
		d.setStatus(DemandStatus.UNRESOLVED.getCode());
		int i=0;
		i=demandMapper.updateByPrimaryKeySelective(d);
		demandKeywordMapper.batchDeleteByDemandId(d.getId());
		achievementDemandMapper.deleteByDemandId(d.getId());
		if (StringUtils.isNotBlank(d.getEmployerId())) {
			AchievementDemandCount adc = achievementDemandCountMapper.selectByUid(d.getEmployerId());
			if (null != adc) {
				adc.setDemandCount(adc.getDemandCount() - 1);
				if (adc.getDemandCount() < 0) {
					adc.setDemandCount(0);
				}
				achievementDemandCountMapper.updateByPrimaryKeySelective(adc);
			}
		}
		return i;

	}

	@Override
	public int updateAuditDemand(Demand d, String techBroderId, Integer auditStatus) {
		d.setAuditStatus(auditStatus);
		if (DemandAuditStatus.AUDITED.getCode().equals(auditStatus)) {
			Calendar now = Calendar.getInstance();
			now.set(Calendar.MILLISECOND, 0);
			d.setReleaseDate(now.getTime());
			d.setReleaseStatus(DemandReleaseStatus.UNRELEASE.getCode());
			d.setTechBrokerId(techBroderId);

			if (StringUtils.isNotBlank(d.getKeyword())) {
				String[] keywords = d.getKeyword().trim().split(",|，");
				disposeDemandKeyword(keywords, d, false);
			}

			String employerId = d.getEmployerId();
			if (StringUtils.isNotBlank(employerId)) {
				if (UserType.PERSONAL.getCode().equals(d.getDataCategory())) {
					UserIdentity ui = userIdentityMapper.selectUserIdentityByUserId(employerId);
					if (null != ui) {
						d.setEmployerName(ui.getUsername());
					}
				} else if (UserType.ORGANIZATION.getCode().equals(d.getDataCategory())) {
					OrganizationIdentity oi = organizationIdentityMapper.selectOrgIdentityByUserId(employerId);
					if (null != oi) {
						d.setEmployerName(oi.getUnitName());
					}
				}
				AchievementDemandCount adc = achievementDemandCountMapper.selectByUid(employerId);
				if (null == adc) {
					AchievementDemandCount achievementDemandCount = new AchievementDemandCount();
					achievementDemandCount.setId(UUID.randomUUID().toString());
					achievementDemandCount.setUid(employerId);
					achievementDemandCount.setDemandCount(AFTConstants.ACHIEVEMENT_DEMAND_FIRST_COUNT);
					achievementDemandCount.setAchievementCount(AFTConstants.ACHIEVEMENT_DEMAND_INIT_COUNT);
					achievementDemandCountMapper.insert(achievementDemandCount);
				} else {
					adc.setDemandCount(adc.getDemandCount() + 1);
					achievementDemandCountMapper.updateByPrimaryKeySelective(adc);
				}
			}
		} else {
			d.setReleaseStatus(DemandReleaseStatus.UNRELEASE.getCode());
		}
		createTechBorkerNotice(d);
		return demandMapper.updateByPrimaryKeySelective(d);
	}

	@Override
	public void saveDemand(Demand d, String validityPeriodFormattedDate, String[] keywords) {
		Date validityPeriod = null;
		if (!StringUtils.isBlank(validityPeriodFormattedDate)) {
			try {
				validityPeriod = DateUtils.parseDate(validityPeriodFormattedDate, AFTConstants.YYYYMMDD);
			} catch (ParseException e) {
			}
		}

		d.setValidityPeriod(validityPeriod);
		d.setId(UUID.randomUUID().toString());

		d.setDeletedSign(DeleteStatus.UNDELETE.getCode());

		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		d.setStatus(DemandStatus.UNRESOLVED.getCode());
		d.setReleaseStatus(DemandReleaseStatus.UNRELEASE.getCode());

		if (DemandAuditStatus.SUBMIT.getCode().equals(d.getAuditStatus())) {
			d.setAuditStatus(DemandAuditStatus.INAUDIT.getCode());
			createAuditorNotice(d);
		} else {
			d.setAuditStatus(DemandAuditStatus.CREATE.getCode());
		}

		d.setCreateTime(now.getTime());
		demandMapper.insert(d);
		disposeDemandKeyword(keywords, d, false);
	}

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

	@Override
	public void insertImport(List<DemandImportBo> data) {
		if (null == data || data.isEmpty()) {
			return;
		}
		Demand d = null;
		DemandKeyword dk = null;
		List<Demand> demandList = new ArrayList<>();
		List<DemandKeyword> demandKeywordList = new ArrayList<>();
		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		String techBrokerId = TokenManager.getAdminId();
		for (DemandImportBo bo : data) {
			d = new Demand();
			BeanUtils.copyProperties(bo, d);
			d.setId(UUID.randomUUID().toString());
			d.setReleaseStatus(DemandReleaseStatus.UNRELEASE.getCode());
			d.setCreateTime(now.getTime());
			d.setDeletedSign(DeleteStatus.UNDELETE.getCode());
			d.setAuditStatus(DemandAuditStatus.INAUDIT.getCode());
			d.setStatus(DemandStatus.UNRESOLVED.getCode());
			d.setInfoSources(DemandInfoSourceStatus.IMPORT.getCode());
			d.setTechBrokerId(techBrokerId);
			List<String> keywordsList = bo.getKeywords();
			if (null != keywordsList && keywordsList.size() > 0) {
				for (String s : keywordsList) {
					if (!StringUtils.isBlank(s)) {
						dk = new DemandKeyword();
						dk.setDemandId(d.getId());
						dk.setKeyword(s.trim());
						dk.setId(UUID.randomUUID().toString());
						demandKeywordList.add(dk);
					}
				}
			}
			demandList.add(d);
		}
		demandMapper.insertBatch(demandList);
		demandKeywordMapper.insertBatch(demandKeywordList);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<DemandSearchListBo> listDemandSearchList(String url,Integer sign, String keyword, Integer industryCategoryA,
			Integer industryCategoryB, Integer demandType, BigDecimal budgetCostLower, BigDecimal budgetCostUpper,
			Integer pNo, Integer pSize, Integer dateSort) {
		Map<String, Object> params = new HashMap<>();
		if (!StringUtils.isBlank(url)) {
			params.put("url", url);
		}
		if (!StringUtils.isBlank(keyword)) {
			params.put("keyword", keyword);
		}

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

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

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

		if (null != budgetCostLower && DemandPortalSearchSignType.ALL.getCode().equals(sign)) {
			params.put("budgetCostLower", budgetCostLower);
		}

		if (null != budgetCostUpper && DemandPortalSearchSignType.ALL.getCode().equals(sign)) {
			params.put("budgetCostUpper", budgetCostUpper);
		}

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

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

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

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 12;
		}

		return (Pagination<DemandSearchListBo>) findPage("findSearchDemandListByPage", "findSearchDemandCount", params,
				pNo, pSize);
	}

	@Override
	public DemandSearchDetailBo selectDemandSearchDetail(String uid, String id) {
		return demandMapper.selectDemandSearchDetail(uid, id);
	}

	private Map<String, Object> disposeParams(Integer auditStatus, Integer province, Integer serialNumber, String name,
			String keyword, Integer infoSources, Integer demandType, String validityPeriodStartDate,
			String validityPeriodEndDate, String username, Integer status, Integer releaseStatus,
			String releaseDateStartDate, String releaseDateEndDate,String createDateStartDate, String createDateEndDate, Integer boutique, Integer hot) {
		Map<String, Object> params = new HashMap<>();
		Date vStart = null;
		Date vEnd = null;
		Date rStart = null;
		Date rEnd = null;
		Date cStart = null;
		Date cEnd = null;

		if (!StringUtils.isBlank(validityPeriodStartDate)) {
			try {
				vStart = DateUtils.parseDate(validityPeriodStartDate, AFTConstants.YYYYMMDD);
			} catch (ParseException e) {
			}
		}

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

		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 (null != vStart) {
			params.put("vStart", vStart);
		}

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

		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 (null != province) {
			params.put("province", province);
		}

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

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

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

		/*
		 * if (!StringUtils.isBlank(username)) { params.put("username",
		 * username); }
		 */

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

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

		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);
		}
		return params;
	}

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

	// 给指派技术经纪人发送审核结果通知
	private void createTechBorkerNotice(Demand a) {
	}

	private Notice disposeNotice(Demand d, 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(d.getId());
		User u = userMapper.queryById(d.getEmployerId());
		if (null != u) {
			n.setPid(u.getAid());
		}
		if (StringUtils.isBlank(aid)) {
			n.setAid(d.getTechBrokerId());
			if (UserType.PERSONAL.getCode().equals(d.getDataCategory())) {
				n.setContent("编号" + d.getSerialNumber() + NoticeStatus.PERSONALDEMAND.getDesc() + " "
						+ (DemandAuditStatus.AUDITED.getCode().equals(d.getAuditStatus())
								? DemandAuditStatus.AUDITED.getDesc() : DemandAuditStatus.UNAUDITED.getDesc()));
				n.setNoticeType(NoticeStatus.PERSONALDEMAND.getCode());
			} else if (UserType.ORGANIZATION.getCode().equals(d.getDataCategory())) {
				n.setContent("编号" + d.getSerialNumber() + NoticeStatus.ORGANIZATIONDEMAND.getDesc() + " "
						+ (DemandAuditStatus.AUDITED.getCode().equals(d.getAuditStatus())
								? DemandAuditStatus.AUDITED.getDesc() : DemandAuditStatus.UNAUDITED.getDesc()));
				n.setNoticeType(NoticeStatus.ORGANIZATIONDEMAND.getCode());
			}
		} else {
			n.setAid(aid);
			if (UserType.PERSONAL.getCode().equals(d.getDataCategory())) {
				n.setContent(NoticeStatus.PERSONALDEMAND.getDesc() + " " + DemandAuditStatus.SUBMIT.getDesc());
				n.setNoticeType(NoticeStatus.PERSONALDEMAND.getCode());
			} else if (UserType.ORGANIZATION.getCode().equals(d.getDataCategory())) {
				n.setContent(NoticeStatus.ORGANIZATIONDEMAND.getDesc() + " " + DemandAuditStatus.SUBMIT.getDesc());
				n.setNoticeType(NoticeStatus.ORGANIZATIONDEMAND.getCode());
			}
		}
		return n;
	}

	private void disposeDemandKeyword(String[] keywords, Demand d, boolean delete) {
		if (null != keywords && keywords.length > 0) {
			if (delete) {
				demandKeywordMapper.batchDeleteByDemandId(d.getId());
			}
			List<DemandKeyword> list = new ArrayList<>();
			DemandKeyword dk = null;
			for (int i = 0; i < keywords.length; i++) {
				dk = new DemandKeyword();
				dk.setId(UUID.randomUUID().toString());
				dk.setDemandId(d.getId());
				dk.setKeyword(keywords[i].trim());
				list.add(dk);
			}
			demandKeywordMapper.insertBatch(list);
		}
	}

	@Override
	public int updateMatchAchievement(Demand d) {
		achievementDemandMapper.deleteByDemandId(d.getId());
		List<DemandKeyword> demand = demandKeywordMapper.selectKeywordsByDemandId(d.getId());
		if (null != demand && demand.size() > 0) {
			List<String> keyword = new ArrayList<>();
			for (DemandKeyword k : demand) {
				if (!StringUtils.isBlank(k.getKeyword())) {
					keyword.add(k.getKeyword());
				}
			}
			List<AchievementDemand> list = achievementKeywordMapper.selectAchievementDemand(keyword);
			if (null != list && list.size() > 0) {
				for (AchievementDemand ad : list) {
					ad.setDemandId(d.getId());
				}
				return achievementDemandMapper.insertBatch(list);
			}
		}
		return 0;
	}

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

		params.put("employerId", employerId);

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

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}

		return (Pagination<DemandPartnerListBo>) findPage("findPartnerDemandListByPage", "findPartnerDemandCount",
				params, pNo, pSize);
	}

	@Override
	public DemandPortalDetailBo findUserPortalDemandDetail(String id) {
		return demandMapper.findUserPortalDemandDetail(id, TokenManager.getUserId());
	}

	@Override
	public DemandPortalDetailBo findOrgPortalDemandDetail(String id) {
		return demandMapper.findOrgPortalDemandDetail(id, TokenManager.getUserId());
	}

	@Override
	public List<DemandPortalSimilarListBo> findByIndustryCategoryA(Integer industryCategoryA, String id) {
		return demandMapper.findByIndustryCategoryA(industryCategoryA, id);
	}

	@Override
	public int updateByPrimaryKeySelective(Demand d) {
		return demandMapper.updateByPrimaryKeySelective(d);
	}

	@Override
	public DemandListBo selectDemandDetail(String id ) {
		DemandListBo d=demandMapper.selectAppByPrimaryKey(id);

		if (null!=d.getIndustryCategoryA()) {
			d.setIndustryCategory1(fieldGlossoryMapper.selectByPrimaryKey(d.getIndustryCategoryA()).getName());
		}
		if (null!=d.getIndustryCategoryB()) {
			d.setIndustryCategory2(String.valueOf(fieldGlossoryMapper.selectByPrimaryKey(d.getIndustryCategoryB()).getName()));
		}
		if (null!=d.getIndustryCategoryC()) {
			d.setIndustryCategory3(String.valueOf(fieldGlossoryMapper.selectByPrimaryKey(d.getIndustryCategoryC()).getName()));
		}
		int i=demandMapper.countInterest(d.getId());
		d.setCountInterest(String.valueOf(i));
		String uid=TokenManager.getUserId();
		if(TokenManager.isLogin()&&demandInterestMapper.checkUidAndDid(uid,id)>0){
			d.setInterest("1");//已关注
		}else {
			d.setInterest("0");//未关注
		}
		return d;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<BoutiqueListBo> boutiqueSearchList(Integer industryCategoryA, Integer pNo, Integer pSize) {
		Map<String, Object> params = new HashMap<>();
		if (null != industryCategoryA)
			params.put("industryCategoryA", industryCategoryA);
		return (Pagination<BoutiqueListBo>) findPage("findBoutiqueListByPage", "findBoutiqueCount", params, pNo, pSize);
	}

	@Override
	public ArrayList<DemandListBo> selectDemandList(Integer boutique) {
		return demandMapper.selectDemandList(boutique);
	}

	@Override
	public List<DemandListBo> selectCsutomerLike() {
		return demandMapper.selectCsutomerLike(TokenManager.getUserId());
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<DemandSearchListBo> listAppDemand(Integer auditStatus, Integer serialNumber, String name,
			String keyword, Integer demandType,Integer industryCategoryA, String validityPeriodStartDate, String validityPeriodEndDate,
			Integer status, Integer releaseStatus, String releaseDateStartDate, String releaseDateEndDate,String employerId, Integer pNo,
			Integer pSize) {
		Map<String, Object> params = disposeParams(auditStatus, null, serialNumber, name, keyword, null, demandType,
				validityPeriodStartDate, validityPeriodEndDate, null, status, releaseStatus, releaseDateStartDate,
				releaseDateEndDate,null,null, null, null);
		if (null!=industryCategoryA) {
			params.put("industryCategoryA",  industryCategoryA);
		}
		if (null!=employerId) {
			params.put("employerId", employerId);
		}
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}

		if (pSize == null || pSize < 0) {
			pSize = 10;

		}
		Pagination<DemandSearchListBo> p=(Pagination<DemandSearchListBo>) findPage("findAppDemandListByPage", "findAppDemandCount", params, pNo, pSize);
		return p;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<ObjectInterestListBo> selectinterest(Integer type,Integer pNo, Integer pSize) {
		if (pNo == null || pNo < 0) {
			pNo = 1;
		}
		if (pSize == null || pSize < 0) {
			pSize = 10;
		}
		Map<String, Object> params=new HashMap<>();
		params.put("type", type);
		if (StringUtils.isNotBlank(TokenManager.getUserId())) {
			params.put("uid", TokenManager.getUserId());
		}
		//params.put("uid", "6d71349c-7bb8-4e8a-8c03-0c3f36fc66ae");
		if (type==InterestType.POLICY.getCode()) {
			Pagination<ObjectInterestListBo> p=(Pagination<ObjectInterestListBo>) findPage("findAppNewsInterestByPage", "findAppNewsInterestCount", params, pNo, pSize);
			List<ObjectInterestListBo> l=(List<ObjectInterestListBo>) p.getList();
			for (ObjectInterestListBo o : l) {
				int i=newsInterestMapper.countInterest(o.getId());
				o.setCountInterest(String.valueOf(i));
				o.setType(type);
			}
			return p;
		}
		if (type==InterestType.EXPERTS.getCode()) {
			Pagination<ObjectInterestListBo> p=(Pagination<ObjectInterestListBo>) findPage("findAppUserInterestByPage", "findAppUserInterestCount", params, pNo, pSize);
			List<ObjectInterestListBo> l=(List<ObjectInterestListBo>) p.getList();
			for (ObjectInterestListBo o : l) {
				int i=userInterestMapper.countInterest(o.getId());
				o.setCountInterest(String.valueOf(i));
				o.setType(type);
			}
			return p;
		}
		if (type==InterestType.DEMAND.getCode()) {
			Pagination<ObjectInterestListBo> p=(Pagination<ObjectInterestListBo>) findPage("findAppDemandInterestByPage", "findAppDemandInterestCount", params, pNo, pSize);
			List<ObjectInterestListBo> l=(List<ObjectInterestListBo>) p.getList();
			for (ObjectInterestListBo o : l) {
				int i=demandInterestMapper.checkCount(o.getId());
				o.setCountInterest(String.valueOf(i));
				o.setType(type);
			}
			return p;
		}
		if (null==type||type==InterestType.ACHIEVEMENT.getCode()) {
			Pagination<ObjectInterestListBo> p=(Pagination<ObjectInterestListBo>) findPage("findAppAchievementInterestByPage", "findAppAchievementInterestCount", params, pNo, pSize);
			List<ObjectInterestListBo> l=(List<ObjectInterestListBo>) p.getList();
			for (ObjectInterestListBo o : l) {
				int i=achievementMapper.countInterest(o.getId());
				o.setCountInterest(String.valueOf(i));
				o.setType(type);
			}
			return p;
		}
		if (null==type||type==InterestType.PROJECT.getCode()) {
			Pagination<ObjectInterestListBo> p=(Pagination<ObjectInterestListBo>) findPage("findAppProjectInterestByPage", "findAppProjectInterestCount", params, pNo, pSize);
			List<ObjectInterestListBo> l=(List<ObjectInterestListBo>) p.getList();
			for (ObjectInterestListBo o : l) {
				int i=projectInterestMapper.countInterest(o.getId());
				o.setCountInterest(String.valueOf(i));
				o.setType(type);
			}
			return p;
		}
		if (type==InterestType.COUNSELOR.getCode()) {
			Pagination<ObjectInterestListBo> p=(Pagination<ObjectInterestListBo>) findPage("findAppCounselorInterestByPage", "findAppCounselorInterestCount", params, pNo, pSize);
			List<ObjectInterestListBo> l=(List<ObjectInterestListBo>) p.getList();
			for (ObjectInterestListBo o : l) {
				int i=userInterestMapper.countInterest(o.getId());
				o.setCountInterest(String.valueOf(i));
				o.setType(type);
			}
			return p;
		}
		return null;
	}

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


	public int saveAppUserDemand(Demand d, String validityPeriodFormattedDate, String[] keywords) {
		Date validityPeriod = null;
		if (!StringUtils.isBlank(validityPeriodFormattedDate)) {
			try {
				validityPeriod = DateUtils.parseDate(validityPeriodFormattedDate, AFTConstants.YYYYMMDD);
			} catch (ParseException e) {
			}
		}
		d.setInfoSources(1);
		if (null!=TokenManager.getUserId()) {
			d.setEmployerId(TokenManager.getUserId());
			User u=userMapper.queryById(TokenManager.getUserId());
			if (null!=u.getType()) {
				d.setDataCategory(u.getType());
			}
			if (StringUtils.isNotBlank(u.getId())) {
				d.setEmployerId(u.getId());
			}

			if (StringUtils.isNotBlank(u.getMobile())) {
				d.setEmployerContactsMobile(u.getMobile());
			}
		}
		d.setValidityPeriod(validityPeriod);

		d.setId(UUID.randomUUID().toString());
		d.setTechBrokerId(TokenManager.getAdminId());

		d.setDeletedSign(DeleteStatus.UNDELETE.getCode());

		Calendar now = Calendar.getInstance();
		now.set(Calendar.MILLISECOND, 0);
		d.setStatus(DemandStatus.UNRESOLVED.getCode());
		d.setReleaseStatus(DemandReleaseStatus.UNRELEASE.getCode());
		d.setPrincipalId(TokenManager.getAdminId());
		d.setAuditStatus(DemandAuditStatus.INAUDIT.getCode());
		createAuditorNotice(d);
		if (null==d.getKeyword()) {
			d.setKeyword("");
		}
		d.setCreateTime(now.getTime());
		//disposeDemandKeyword(keywords, d, false);
		return demandMapper.insert(d);
	}


	@SuppressWarnings("unchecked")
	@Override
	public Pagination<DemandManageListBo> selectMyDemandManageList(Integer dataCategory,String employerName, Integer auditStatus,
			Integer province, Integer serialNumber, String name, String keyword, Integer infoSources,
			Integer demandType, String validityPeriodStartDate, String validityPeriodEndDate, String username,
			Integer status, Integer releaseStatus, String releaseDateStartDate, String releaseDateEndDate,String createDateStartDate, String createDateEndDate, Integer pNo,
			Integer pSize, Integer boutique, Integer hot, String techBrokerId) {
		Map<String, Object> params = disposeParams(auditStatus, province, serialNumber, name, keyword, infoSources,
				demandType, validityPeriodStartDate, validityPeriodEndDate, username, status, releaseStatus,
				releaseDateStartDate, releaseDateEndDate, createDateStartDate,  createDateEndDate, boutique, hot);

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

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		if (null != dataCategory) {
			params.put("dataCategory", dataCategory);
		}

		if (!TokenManager.hasRole(AFTConstants.SUPERADMIN) && !TokenManager.hasRole(AFTConstants.AUDITORADMIN)) {
			params.put("adminId", TokenManager.getAdminId());
		}

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

		if (StringUtils.isNotBlank(username)) {
			params.put("unitName", username);
		}
		if (null != techBrokerId) {
			params.put("techBrokerId", techBrokerId);
		}

		return (Pagination<DemandManageListBo>) findPage("findMyDemandListByPage", "findMyDemandCount",
				params, pNo, pSize);
	}


	@SuppressWarnings("unchecked")
	@Override
	public Pagination<DemandManageListBo> selectManageDemandManageList(Integer dataCategory,String employerName, Integer auditStatus,
			Integer province, Integer serialNumber, String name, String keyword, Integer infoSources,
			Integer demandType, String validityPeriodStartDate, String validityPeriodEndDate, String username,
			Integer status, Integer releaseStatus, String releaseDateStartDate, String releaseDateEndDate,String createDateStartDate, String createDateEndDate, Integer pNo,
			Integer pSize, Integer boutique, Integer hot, String techBrokerId,String recordPerson) {
		Map<String, Object> params = disposeParams(auditStatus, province, serialNumber, name, keyword, infoSources,
				demandType, validityPeriodStartDate, validityPeriodEndDate, username, status, releaseStatus,
				releaseDateStartDate, releaseDateEndDate, createDateStartDate,  createDateEndDate, boutique, hot);

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

		if (pSize == null || pSize < 0 || pSize > 10) {
			pSize = 10;
		}
		if (null != dataCategory) {
			params.put("dataCategory", dataCategory);
		}
		if (null != recordPerson) {
			params.put("recordPerson", recordPerson);
		}
		if (!TokenManager.hasRole(AFTConstants.SUPERADMIN) && !TokenManager.hasRole(AFTConstants.AUDITORADMIN)) {
			params.put("adminId", TokenManager.getAdminId());
		}

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

		if (StringUtils.isNotBlank(username)) {
			params.put("unitName", username);
		}
		if (null != techBrokerId) {
			params.put("techBrokerId", techBrokerId);
		}

		return (Pagination<DemandManageListBo>) findPage("findManageDemandListByPage", "findManagegDemandCount",
				params, pNo, pSize);
	}

	@Override
	public Demand DemandFollowDetails(String id) {
		return demandMapper.selectDemandFollow(id);
	}


}
