package com.goafanti.business.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.goafanti.business.bo.JtBusinessCategoryBo;
import com.goafanti.business.bo.JtBusinessCategoryTree;
import com.goafanti.business.bo.JtBusinessProjectResult;
import com.goafanti.business.bo.makeMoneyCategoryListBo;
import com.goafanti.business.service.JtBusinessService;
import com.goafanti.common.bo.MyCollection;
import com.goafanti.common.dao.JtBusinessCategoryMapper;
import com.goafanti.common.dao.JtBusinessProjectMapper;
import com.goafanti.common.dao.JtCollectSearchMapper;
import com.goafanti.common.dao.JtCommodityCommentMapper;
import com.goafanti.common.dao.JtTagMapper;
import com.goafanti.common.enums.BusinessCategoryModule;
import com.goafanti.common.enums.ProjectAuditStatus;
import com.goafanti.common.enums.collectType;
import com.goafanti.common.model.JtBusinessCategory;
import com.goafanti.common.model.JtBusinessProject;
import com.goafanti.common.model.JtCollectSearch;
import com.goafanti.common.utils.StringUtils;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.core.shiro.token.TokenManager;

@Service
public class JtBusinessServiceImpl  extends BaseMybatisDao<JtBusinessProjectMapper> implements JtBusinessService{
	@Autowired
	JtBusinessCategoryMapper jtBusinessCategoryMapper;
	@Autowired
	JtBusinessProjectMapper jtBusinessProjectMapper;
	@Autowired
	private JtTagMapper	jtTagMapper;
	@Autowired
	private JtCommodityCommentMapper	jtCommodityCommentMapper;
	@Value(value="${collect_flag}")
	private Boolean collectFlag ;
	@Autowired
	private JtCollectSearchMapper	jtCollectSearchMapper;
	@Override
	public JtBusinessCategory getBusinessCategoryByLayerAndName(Integer layer, String name) {
		return jtBusinessCategoryMapper.getBusinessCategoryByLayerAndName(layer, name);
	}

	@Override
	public List<JtBusinessCategory> getBusinessCategoryBySuperId(String id,Integer size) {
		return jtBusinessCategoryMapper.getBusinessCategoryBySuperId(id,size);
	}

	@Override
	public List<JtBusinessProject> getBusinessProjectByCategoryId(String id,Integer size,Integer isHot) {
		return jtBusinessProjectMapper.getBusinessProjectByCategoryId(id,size,isHot);
	}

	@Override
	public JtBusinessProjectResult getBusinessProjectDetail(String id) {
		String uid=TokenManager.getUserId();
		JtBusinessProjectResult j=jtBusinessProjectMapper.selectByPrimaryKeyWithModule(id,uid);
		j.setCommentDetailResult(jtCommodityCommentMapper.selectByProjectId(id));
		j.setTags(jtTagMapper.selectProjectTag(id));
		if (StringUtils.isBlank(j.getAdvertisement()))j.setAdvertisement("暂无描述");
		return j;
	}


	@Override
	public JtBusinessCategoryTree getCategoryTree(String id) {
		return jtBusinessCategoryMapper.getCategoryTree(id);
	}
	
	public List<JtBusinessCategoryBo>getCategoryBoList(Integer module){
		return jtBusinessCategoryMapper.getCategoryBoList(module);
	}

	/*
	 * 登录用户0     项目列表页1  privateProject
	 * ownerId优先级高于privateProject
	 * 
	 * ordetType---0 发布时间  1价格  2成交量
	 * orderSort ----0大->小   1小->大
	 * 
	 * 
	 * */
	@SuppressWarnings("unchecked")
	@Override
	public Pagination<JtBusinessProjectResult> getProjects(String tag,String topId, String secondId, String name, Integer pageSize,
			Integer pageNo,Integer privateProject,Integer auditStatus,Integer module,Integer isHot,Integer orderType,Integer orderSort,String ownerId) {
		if(orderType==null)orderType=0;
		if(orderSort==null)orderSort=0;
		if (pageNo == null || pageNo < 0) {
			pageNo = 1;
		}
		if (pageSize == null || pageSize < 0 ) {
			pageSize = 10;
		} 
		Map<String, Object> params=disposeParams(topId, secondId, name);
		if(auditStatus!=null ) {
			params.put("auditStatus", auditStatus);
		}
		if(privateProject!=null && privateProject ==0)
		params.put("ownerId", TokenManager.getUserId());
		if(StringUtils.isNotBlank(ownerId)) {
			params.put("ownerId", ownerId);
		}
		if(module!=null)params.put("module", module);
		if(isHot!=null)params.put("isHot", isHot);
		if(orderType!=null)params.put("orderType", orderType);
		if(orderSort!=null)params.put("orderSort", orderSort);
		if(StringUtils.isNotBlank(tag))params.put("tag", tag);
		Pagination<JtBusinessProjectResult> pagination=(Pagination<JtBusinessProjectResult>)findPage("findJtBusinessProjectByPage","findJtBusinessCountByPage",params,pageNo,pageSize);
		List<JtBusinessProjectResult> list =(List<JtBusinessProjectResult>) pagination.getList();
		for (JtBusinessProjectResult j : list) {
			if (StringUtils.isBlank(j.getAdvertisement()))j.setAdvertisement("暂无描述");
		}
		return pagination;
	}
	
	private Map<String, Object> disposeParams(String topId, String secondId,  String name) {
		Map<String, Object> params = new HashMap<>();

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

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

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

		
		return params;
	}

	@Override
	public int insertCategory(JtBusinessCategory jtBusinessCategory) {
//		jtBusinessCategoryMapper.autoIncreaseSort(jtBusinessCategory.getLayer(),jtBusinessCategory.getSort()); 
		if(jtBusinessCategory.getSuperId()!=null && jtBusinessCategory.getLayer().intValue()==1 && jtBusinessCategory.getSuperId().length()>0)return -2;
		//查看是否重名
		int n = jtBusinessCategoryMapper.getCountBySome(jtBusinessCategory);
		if(n>0)return -3;
		//String number="BC";
		String number=BusinessCategoryModule.getStatus(jtBusinessCategory.getModule()).toString();
		if(jtBusinessCategory.getLayer().intValue()==2) {
			//2层，先加第一层
			//找到当前品类父级品类
			JtBusinessCategory sp=jtBusinessCategoryMapper.selectByPrimaryKey(jtBusinessCategory.getSuperId());
			if(sp==null || sp.getLayer()!=1) {
				//找到的父级品类层数不是1 或者未找到
				return -2;
			}
			//加前层
			//父级品类层数为1的情况下 第一层编号为父级sort序号
			int size1=sp.getSort();
			if(size1>99)return -1;
			if(size1<10)number+="0";
			number+=size1;
		}
		
		
		//加层
		int size2;
		//通过父级id获取当前层列表
		List<JtBusinessCategory>businessCategories =jtBusinessCategoryMapper.getBusinessCategoryBySuperId(jtBusinessCategory.getSuperId(), null);
		//列表为0,当前层编号size2设置为1，大于0 设置为当前最大sort+1
		if(businessCategories.size()>0)
		 size2=businessCategories.get(businessCategories.size()-1).getSort()+1;
		else size2=1;
		//每层最多99个
		if(size2>99)return -1;
		//增加0
		if(size2<10)number+="0";
		//完成编号
		number+=size2;
		jtBusinessCategory.setNumber(number);
		//设置sort序号
		jtBusinessCategory.setSort(size2);
		jtBusinessCategory.setCreateTime(new Date());
		jtBusinessCategory.setId(UUID.randomUUID().toString());
		return jtBusinessCategoryMapper.insertSelective(jtBusinessCategory);
	}

	@Override
	public int deleteCategoryById(String id) {
		//查找品类
		JtBusinessCategory sp=jtBusinessCategoryMapper.selectByPrimaryKey(id);
		//查找子品类 存在子品类不允许删除
		List<JtBusinessCategory> chidren=jtBusinessCategoryMapper.getBusinessCategoryBySuperId(sp.getId(), null);
		if(chidren.size()>0) {
			return -1;
		}
		List<JtBusinessProject> childrenProject=jtBusinessProjectMapper.getBusinessProjectByCategoryId(id, 100,null);
		if(childrenProject!= null && childrenProject.size()>0) {
			return -1;
		}
		return jtBusinessCategoryMapper.deleteByPrimaryKey(id);
	}

	@Override
	public JtBusinessCategory getCategoryById(String id) {
		return jtBusinessCategoryMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateCategory(JtBusinessCategory jtBusinessCategory) {
		// 层级不会变
		//修改不影响结构的数据
		JtBusinessCategory category = new JtBusinessCategory();
		category.setId(jtBusinessCategory.getId());
		category.setImgUrl(jtBusinessCategory.getImgUrl());
		category.setName(jtBusinessCategory.getName());
		category.setSummary(jtBusinessCategory.getSummary());
		category.setPcIndex(jtBusinessCategory.getPcIndex());
		category.setAppIndex(jtBusinessCategory.getAppIndex());
		category.setHomeIndex(jtBusinessCategory.getHomeIndex());
		jtBusinessCategoryMapper.updateByPrimaryKeySelective(category);
		//是否修改了模块类别
		boolean moduleChange = null != jtBusinessCategory.getModule() ? !jtBusinessCategory.getModule().equals(jtBusinessCategory.getNextModule()) : false;
		//是否有上级id,并且改变了上级id
		boolean existSuperId = StringUtils.isNotBlank(jtBusinessCategory.getSuperId()) ? !jtBusinessCategory.getSuperId().equals(jtBusinessCategory.getOldSuperId()) : false;
		//获得更改前的自己的number
		String oldNumber = jtBusinessCategoryMapper.selectByPrimaryKey(jtBusinessCategory.getId()).getNumber();
		String number = null;
		//一级更换模块
		if(moduleChange && !existSuperId){
			jtBusinessCategory.setLayer(1);
			//根据模块获得字母前缀
			String prefix = BusinessCategoryModule.getStatus(jtBusinessCategory.getNextModule()).toString();
			jtBusinessCategory.setNumber(prefix + "__");
			number = prefix;
			category.setModule(jtBusinessCategory.getNextModule());
			jtBusinessCategory.setModule(jtBusinessCategory.getNextModule());
		}
		//存在上级说明是二级修改到不同模块的某品类中
		if(existSuperId){
			JtBusinessCategory b = jtBusinessCategoryMapper.selectByPrimaryKey(jtBusinessCategory.getSuperId());
			category.setModule(b.getModule());
			jtBusinessCategory.setLayer(2);
			jtBusinessCategory.setModule(b.getModule());
			
			number = b.getNumber();
			//获得前缀
			String prefix = BusinessCategoryModule.getStatus(b.getModule()).toString();
			number = prefix + number.substring(prefix.length()) ;
			jtBusinessCategory.setNumber(number + "__");
			category.setSuperId(jtBusinessCategory.getSuperId());//上级id也要修改
		}
		if((!moduleChange && !existSuperId) && !existSuperId){
			return 1;
		}
		//获得当前更改后模块的最大值
		String newNumber = jtBusinessCategoryMapper.getCurrentMaxNumber(jtBusinessCategory);
		Integer n = null != newNumber ? Integer.valueOf(newNumber.substring(newNumber.length() - 2)) : 0;
		if(n < 99){
			//将最大值加一
			n += 1;
			newNumber = number + (n<10? "0"+ n : n);
		} else {
			newNumber = jtBusinessCategoryMapper.getCurrentMaxNumber(jtBusinessCategory);
			n = Integer.valueOf(newNumber.substring(newNumber.length() - 2));
			if(n == 1 || n == 01){
				return -1;
			}
			//将最小值减一
			n -= 1;
			newNumber = number + (n<10? "0"+ n : n);
		}
		
		//修改自己和自己下级的前缀
		jtBusinessCategory.setLayer(newNumber.length() + 1);//截取前缀的长度位置
		jtBusinessCategory.setNumber(oldNumber + "%");
		jtBusinessCategory.setName(newNumber );
		//将模块前面字母替换
		jtBusinessCategoryMapper.updateNumberPrefix(jtBusinessCategory);
		//得到sort
		category.setSort(n);
		//修改自己的number
		category.setNumber(newNumber);
		//修改自己的模块
		jtBusinessCategoryMapper.updateByPrimaryKeySelective(category);
		return 1;//jtBusinessCategoryMapper.updateByPrimaryKeySelective(jtBusinessCategory);
	}

	
	
	

	@Override
	public int insertProject(JtBusinessProject jtBusinessProject) {
		jtBusinessProject.setCreateTime(new Date());
		jtBusinessProject.setId(UUID.randomUUID().toString());
		jtBusinessProject.setOwnerId(TokenManager.getUserId());
		jtBusinessProject.setAuditStatus(ProjectAuditStatus.CREATE.getCode());
		List<JtBusinessProject>projects=jtBusinessProjectMapper.findProjectOrderByNumber();
		int cSize = 1;
		if(projects!=null && projects.size()>0)
		{
			String number=projects.get(projects.size()-1).getNumber();
			if(number!=null && number.length()==6)
			{
				String nbString=number.substring(2);
				try {
				cSize=Integer.parseInt(nbString)+1;
				cSize=Math.max(cSize, projects.size()+1);
				}catch (Exception e) {
					return -1;
				}
			}
			else cSize=1;
		}
		else cSize=1;

		String nbString="BP";
		String sizeString="000"+cSize;
		sizeString=sizeString.substring(sizeString.length()-4);
		nbString+=sizeString;
		jtBusinessProject.setNumber(nbString);
		jtBusinessProjectMapper.insertSelective(jtBusinessProject);
		return 1;
	}

	@Override
	public int deleteProjectById(String id) {
		if(collectFlag)jtCollectSearchMapper.deleteByrowId(id);
		return jtBusinessProjectMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int updateProject(JtBusinessProject jtBusinessProject) {
		jtBusinessProjectMapper.updateByPrimaryKeySelective(jtBusinessProject);
		if(null != jtBusinessProject.getTag()){
			jtTagMapper.deleteByProjectId(jtBusinessProject.getId());
			String str=jtBusinessProject.getTag();
			String[] strs = str.split(",");
			for (String s : strs) {
				jtTagMapper.insertProjectTag(UUID.randomUUID().toString(),s,jtBusinessProject.getId());
			}
		}
		return 1;
	}

	@Override
	public List<JtBusinessProject> getProjectsLimit(Integer size) {
		return jtBusinessProjectMapper.findProjectOrderByNumber();
	}

	@Override
	public int deleteByIdAndUid(String id) {
		if(TokenManager.getUserId()==null)return -1;
		return jtBusinessProjectMapper.deleteByIdAndUid(id,TokenManager.getUserId());
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<JtBusinessProject> listProjectIInterestedIn(Integer pageNo,Integer pageSize) {

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

		if (pageSize == null || pageSize < 0 || pageSize > 10) {
			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<JtBusinessProject>) findPage("findInterestedProjcet", "findInterestedProjcetCount", params, pageNo, pageSize);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<MyCollection> myCollectionProject(Integer pageNo, Integer pageSize) {
		if (pageNo == null || pageNo < 0) pageNo = 1;
		if (pageSize == null || pageSize < 0 || pageSize > 10) 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("myCollectionProjectList", "myCollectionProjectCount", params, pageNo, pageSize);
	}

	@Override
	public List<makeMoneyCategoryListBo> makeMoneyCategoryList() {
		List<makeMoneyCategoryListBo> l=new ArrayList<makeMoneyCategoryListBo>();
		//所属模块 0科技服务  1知识产权服务 2高新技术企业服务 3军民融合 4科技咨询 5科技项目
		l.add(new makeMoneyCategoryListBo(2,"高新技术企业服务"));
		l.add(new makeMoneyCategoryListBo(3,"军民融合"));
		l.add(new makeMoneyCategoryListBo(4,"资质认定"));
		l.add(new makeMoneyCategoryListBo(5,"科技项目"));
		for (makeMoneyCategoryListBo m : l) {
			m.setList(getCategoryBoList(m.getModule()));
		}
		return l;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Pagination<MyCollection> recommendedApplication(Integer type,Integer pageNo, Integer pageSize) {
		Map<String,Object> params=new HashMap<String,Object>();
		if (null!=type)params.put("type", type); 
		return (Pagination<MyCollection>) findPage("recommendedApplicationList", "recommendedApplicationCount", params, pageNo, pageSize);
	}

	@Override
	public List<JtBusinessCategory> getCategoryByModule(Integer module,Integer layer,Integer size) {
		return jtBusinessCategoryMapper.getCategoryByModule(module, layer, size);
	}
	
	@Override
	public List<JtBusinessProject> getKJListByIds(Integer module,
			Integer isHost, Integer size) {
		return jtBusinessProjectMapper.getKJListByIds( module,  isHost,  size);
	}

	@Override
	public List<JtBusinessProject> getModuleByName(String name, Integer isHost,
			Integer size) {
		return jtBusinessProjectMapper.getModuleByName(name, isHost, size);
	}

	@Override
	public int updateProjectMoveUp(String id) {
		JtBusinessCategory j1=jtBusinessCategoryMapper.selectByPrimaryKey(id);
		JtBusinessCategory j2=jtBusinessCategoryMapper.selectFirstLevel(id,j1.getModule(),j1.getSuperId(),0);
		if(null==j2){
			return -1;
		}
		Integer i=j1.getSort();
		JtBusinessCategory jtBusinessCategory=new JtBusinessCategory();
		jtBusinessCategory.setId(j1.getId());
		jtBusinessCategory.setSort(j2.getSort());
		jtBusinessCategoryMapper.updateByPrimaryKeySelective(jtBusinessCategory);
		jtBusinessCategory.setId(j2.getId());
		jtBusinessCategory.setSort(i);
		jtBusinessCategoryMapper.updateByPrimaryKeySelective(jtBusinessCategory);
		
		return 1;
	}

	@Override
	public int updateProjectSetTop(String id) {
		JtBusinessCategory j1=jtBusinessCategoryMapper.selectByPrimaryKey(id);
		JtBusinessCategory j2=jtBusinessCategoryMapper.selectFirstLevel(id,j1.getModule(),j1.getSuperId(),1);
		if(null==j2){
			return -1;
		}
		Integer i=j1.getSort();
		JtBusinessCategory jtBusinessCategory=new JtBusinessCategory();
		jtBusinessCategory.setId(j1.getId());
		jtBusinessCategory.setSort(j2.getSort());
		jtBusinessCategoryMapper.updateByPrimaryKeySelective(jtBusinessCategory);
		jtBusinessCategory.setId(j2.getId());
		jtBusinessCategory.setSort(i);
		jtBusinessCategoryMapper.updateByPrimaryKeySelective(jtBusinessCategory);
		return 1;
	}

	@Override
	public void addJtCollectSearch(JtBusinessProject jtBusinessProject) {
	  if(collectFlag){
		JtCollectSearch r=new JtCollectSearch();
		r.setFromTable(collectType.PROJECT.getDesc());
		r.setKeyword(jtBusinessProject.getKeyword());
		r.setTitle(jtBusinessProject.getName());
		r.setRowId(jtBusinessProject.getId());
		String sum = jtBusinessProject.getAdvertisement();
		if(null != sum && sum.length() > 40){
			sum = sum.substring(0,40) + "...";
		}
		r.setSummary(sum);
		jtCollectSearchMapper.insertSelective(r);
	}
		
	}

	@Override
	public void updateJtCollectSearch(String id) {
		if(collectFlag)jtCollectSearchMapper.deleteByrowId(id);
		
	}

	@Override
	public List<JtBusinessCategoryBo> getHomeIndex(Integer module, Integer isHome) {
		
		return jtBusinessCategoryMapper.getHomeIndex(module,isHome);
	}

	@Override
	public List<JtBusinessProject> getProjectByTag(String name, Integer size) {
		return jtBusinessProjectMapper.getProjectByTag(name, size);
	}

	@Override
	public int updateByPrimaryKeySelective(JtBusinessProject jtBusinessProject) {
		return jtBusinessProjectMapper.updateByPrimaryKeySelective(jtBusinessProject);
	}

	
	

}
