package cn.com.countrygarden.bi.main.service.manager.map.impl;


import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;

import javax.annotation.Resource;

import cn.com.countrygarden.bi.main.dao.manager.map.*;
import cn.com.countrygarden.bi.main.dto.manager.TreeNode;
import cn.com.countrygarden.bi.main.model.manager.map.*;
import cn.com.countrygarden.bi.main.service.UserRoleService;
import cn.com.countrygarden.bi.main.service.manager.map.ManagerHousekeeperCacheService;
import cn.com.countrygarden.bi.main.service.manager.map.ManagerMapCacheService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.performance.bdpsndocMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.ManagerMapForErpMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbHsprCommunityMapper;
import cn.com.countrygarden.bi.main.dao.wcx.WcxRegionProjectRelMapper;
import cn.com.countrygarden.bi.main.dto.DevelopmentSubjectDTO;
import cn.com.countrygarden.bi.main.dto.HouseKeeperDTO;
import cn.com.countrygarden.bi.main.dto.HouseKeeperDataVo;
import cn.com.countrygarden.bi.main.dto.HouseKeeperNameTreeDTO;
import cn.com.countrygarden.bi.main.dto.HouseKeeperParamVo;
import cn.com.countrygarden.bi.main.dto.HouseKepperDTO;
import cn.com.countrygarden.bi.main.dto.ManagerMapDTO;
import cn.com.countrygarden.bi.main.dto.ManagerMapOrganTreeDTO;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.wcx.WcxRegionProjectRel;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.manager.map.ManagerMapService;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class ManagerMapServiceImpl implements ManagerMapService{
	@Autowired
	private ManagerMapIndexMapper managerMapper;
	@Autowired
	private ManagerMapMapper managerMapMapper;
	@Autowired
	private ManagerMapCacheMapper managerMapCacheMapper;
	@Autowired
	private ManagerHousekeeperCacheMapper managerHousekeeperCacheMapper;
	@Autowired
	private ManagerMapCacheService managerMapCacheService;
	@Autowired
	private ManagerHousekeeperCacheService managerHousekeeperCacheService;
	@Autowired
	private ManagerMapForErpMapper managerMapForErpMapper;
	@Resource
	private TbHsprCommunityMapper tbHsprCommunityMapper;
	@Autowired
	private FenghuangHouseKeeperCommunicationMapper houseKeeperCommunicationMapper;
	@Autowired
    private AccessTokenService accessTokenService;
	@Autowired
	private bdpsndocMapper bdpsndocMapper;
	@Autowired
    private ManagerHousekeeperFollowMapper managerHousekeeperFollowMapper;
	@Autowired
	private WcxRegionProjectRelMapper wcxRegionProjectRelMapper;
	@Resource
	@Qualifier("taskExecutor")
	private ThreadPoolTaskExecutor poolTaskExecutor;
	@Autowired
	private UserRoleService userRoleService;

	@Override
	public List<ManagerMapDTO> findPageList(String organName) throws InterruptedException {
		List<ManagerMapDTO> organBase = tbHsprCommunityMapper.findAllBaseOrgan(organName);
		CountDownLatch latch=new CountDownLatch(organBase.size());
		for (ManagerMapDTO dto : organBase) {
			poolTaskExecutor.execute(new ManagerMapCountTask(managerMapMapper,dto,latch));
		}
		latch.await();
		return organBase;
	}

	@Override
	public List<ManagerMapDTO> findPageList1(String organName) throws InterruptedException {
		List<ManagerMapDTO> organBase = tbHsprCommunityMapper.findAllBaseOrgan(organName);
//		for (ManagerMapDTO dto : organBase) {
//			if(dto.getManageNumCount()!=null&&dto.getCommCount()!=null){
//				dto.setManageNumAvg(dto.getManageNumCount()/dto.getCommCount());
//			}
//		}
		return organBase;
	}

	private List<String> substringComm (List<String> comms){
		List<String> list = new ArrayList<>();
		for(String comm : comms){
			int testIndex = comm.indexOf("(测试)");
			int rcIndex = comm.indexOf("(预生产)");
			int prodIndex = comm.indexOf("(正式)");
			if(testIndex!=-1){
				list.add(comm.substring(0, testIndex));
			}else if(rcIndex!=-1){
				list.add(comm.substring(0, rcIndex));
			}else if(prodIndex!=-1){
				list.add(comm.substring(0, prodIndex));
			}else{
				list.add(comm);
			}
		}
		list = uniqueValue(list);
		return list;
	}

	private List<String>  uniqueValue (List<String> list){
		Map<String,String> map = new LinkedHashMap();
		for(String str : list){
			map.put(str,str);
		}
		List<String> comms = new ArrayList<>(map.values());
		return comms;
	}

	/**
	 * 获取管家数据
	 * @param houseKeeperParamVo
	 * @return
	 */
	@Override
	public List<HouseKeeperDTO> getAllHKData(HouseKeeperParamVo houseKeeperParamVo) {
		List<String> phoneNums=new ArrayList<>();
		String gardenDistricts=houseKeeperParamVo.getGardenDistricts();
		String organCode=houseKeeperParamVo.getOrganCode();
		List<HouseKeeperDTO> houseKeeperList= new ArrayList<>();
		List<String> communityNames =managerMapMapper.selectCommNameTreeByOrganNameStr(organCode);
		if(communityNames != null && communityNames.size()>0){
			houseKeeperList=managerMapMapper.selectHouseKeeperPageDataByOrganCode(communityNames,houseKeeperParamVo.getUserCode(),phoneNums,gardenDistricts,null,null);
			for(int i=0;i<houseKeeperList.size();i++) {
				if(houseKeeperList.get(i).getBIRTHDATE()!=null) {
					houseKeeperList.get(i).setAgeStructure(houseKeeperList.get(i).getBIRTHDATE().substring(2, 3)+"0后");
				}
				if(StringUtils.isNotBlank(houseKeeperList.get(i).getCommName())){
					List<HouseKeeperDTO> commInfo = managerMapForErpMapper.selectCommByErp(houseKeeperList.get(i).getOrganName(),houseKeeperList.get(i).getCommName());
					if(commInfo!=null&&commInfo.size()>0) {
						if((commInfo.get(0).getCommName()!=null&&!commInfo.get(0).getCommName().isEmpty())
								||(commInfo.get(0).getDevelopmentSubject()!=null&&!commInfo.get(0).getDevelopmentSubject().isEmpty())) {
							houseKeeperList.get(i).setDevelopmentSubject(commInfo.get(0).getDevelopmentSubject());
						}
					}
				}
				FenghuangHouseKeeperCommunication houseKeeperInfo=houseKeeperCommunicationMapper.selectHouseKeeperInfoByUserCode(houseKeeperList.get(i).getPK_ORG(),houseKeeperList.get(i).getCODE(),houseKeeperList.get(i).getBID());
				if(houseKeeperInfo!=null) {
					houseKeeperList.get(i).setJurisdictionForMonth(String.valueOf(countMonths(houseKeeperInfo.getJurisdictionMonth())));
				}
//				获取EPR区域编号
				String regionCode = managerMapForErpMapper.selectOrganCodeByOrganName(organCode);
				houseKeeperList.get(i).setRegionCode(regionCode);
//				获取EPR项目编号
				String commCode = managerMapForErpMapper.selectCommCodeByCommName(houseKeeperList.get(i).getCommName(), houseKeeperList.get(i).getRegionCode());
				houseKeeperList.get(i).setCommCode(commCode);
			}
		}
		return houseKeeperList;
	}



	@Override
	public Result getOrganTreeData(String userCode) {
		Integer count = userRoleService.countByUserCodeAndRoleCode(userCode, "manager_map_admin");
		if(count>0){
			return Response.response(managerMapMapper.selectAllOrganTree());
		}else{
			List<ManagerMapOrganTreeDTO> list = new ArrayList<>();
			List<String> organList = managerMapForErpMapper.queryRegionByUserCode(userCode);
			if(CollectionUtils.isNotEmpty(organList)){
				for(String organ : organList){
					if(StringUtils.isNotEmpty(organ)){
						ManagerMapOrganTreeDTO dto = managerMapMapper.selectOrganTreeByErpOrgan(organ);
						if(dto!=null)list.add(dto);
					}
				}
			}
			return Response.response(list);
		}
	}

	@Override
	public Result getCommTreeDataByOrgan(String organName,String userCode) {
		List<ManagerMapOrganTreeDTO> commList = commList = managerMapMapper.selectCommNameTreeByOrganName(organName);
		return Response.response(commList);
	}

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

	/**
	 * 管家列表数据--将缓存临时表的数据和缓存正式表的数据比对
	 * @param data
	 * @return
	 */
	@Override
	public Boolean handleHouserkeeperCache(List<ManagerHousekeeperCache> inserts,List<ManagerHousekeeperCache> updates,List<ManagerHousekeeperCache> caches) {

		if(CollectionUtils.isNotEmpty(inserts)){
			managerHousekeeperCacheMapper.insertList(inserts);
		}
		if(CollectionUtils.isNotEmpty(updates)){
			for(ManagerHousekeeperCache cache : updates){
				Condition condition=new Condition(ManagerHousekeeperCache.class);
				Example.Criteria criteria = condition.createCriteria();
				criteria.andEqualTo("pkPsndoc",cache.getPkPsndoc());
				managerHousekeeperCacheMapper.updateByConditionSelective(cache,condition);
			}
		}
		//判断是否离职及是否还在管家岗位，如果为否则删除
		if(CollectionUtils.isNotEmpty(caches)){
			for(ManagerHousekeeperCache one : caches){
				if( null == one )continue;
				Integer count = managerMapMapper.selectHouserKeeperIsEffective(one.getPkPsndoc());
				if(0 == count){
					managerHousekeeperCacheMapper.deleteByPrimaryKey(one);
				}
			}
		}
		return true;
	}

	/**
	 * 管家地图区域数据 -- 将缓存临时表的数据和缓存正式表的数据比对
	 * @param data
	 * @return
	 */
	@Override
	public boolean handleManagerMapCache(List<ManagerMapCache> inserts,List<ManagerMapCache> updates) {
		if(CollectionUtils.isNotEmpty(inserts)){
			managerMapCacheMapper.insertList(inserts);
		}
		if(CollectionUtils.isNotEmpty(updates)){
			for(ManagerMapCache cache : updates){
				Condition condition=new Condition(ManagerMapCache.class);
				Example.Criteria criteria = condition.createCriteria();
				criteria.andEqualTo("organCode",cache.getOrganCode());
				managerMapCacheMapper.updateByConditionSelective(cache,condition);
			}
		}
		return true;
	}

	@Override
	public Result findById(Integer id) {
		return Response.response(managerMapper.selectByPrimaryKey(id));
	}

	@Override
	public Result findByOrgancode(FengHuangManagerData managerData, int page, int size) {
		Page<FengHuangManagerData> objects = PageHelper.startPage(page,size);
		managerMapper.findByOrgancode(managerData.getOrganCode());
		PageData pd = new PageData(objects);
		pd.setData(objects.getResult());
		return Response.response(pd);
	}

	@Override
	public Result countHouseKeeper() {
		HouseKepperDTO dto = managerMapper.countHouseKeeper();
		dto.setHireCount(managerMapper.countHireHouseKeeper());
		dto.setQuitCount(managerMapper.countQuitHouseKeeper());
		return Response.response(dto);
	}

	@Override
	public Result addOrUpdateHouseKeeperById(FenghuangHouseKeeperCommunication houseKeeperCommunication,HouseKeeperDataVo vo) {
		FenghuangHouseKeeperCommunication houseKeeperInfo = houseKeeperCommunicationMapper.selectHouseKeeperInfoByUserCode(houseKeeperCommunication.getPkOrg(),houseKeeperCommunication.getUserCode(),houseKeeperCommunication.getBid());

//		不注释的话，NC项目和ERP项目是1对1关系
//		wcxRegionProjectRelMapper.updatePropertyProjectNameForNull(vo.getCommName());
		WcxRegionProjectRel rel = wcxRegionProjectRelMapper.selectByPropertyProjectName(vo.getPkOrg());
		WcxRegionProjectRel relData = new WcxRegionProjectRel();
		relData.setRegionName(vo.getOrganName());
		relData.setProjectName(vo.getCommName());
		relData.setPropertyProjectName(vo.getPkOrg());
		if(StringUtils.isNotBlank(vo.getCommName())) {
			if(rel==null) {
				relData.setRegionProjectId(String.valueOf(UUID.randomUUID()));
				wcxRegionProjectRelMapper.insertSelective(relData);
			}else {
				wcxRegionProjectRelMapper.updateProjectNameByPropertyProjectName(relData);
			}
		}

		if(houseKeeperInfo==null) {
			houseKeeperCommunicationMapper.insertSelective(houseKeeperCommunication);
		}else {
			houseKeeperCommunicationMapper.updateHouseKeeperInfoByRegionProjectId(houseKeeperCommunication);
		}

//		修改ERP项目时自动匹配项目类型,已改为页面选择项目时获取
//		managerHousekeeperCacheMapper.updateCommByCommName(vo.getCommName());
//		String developmentsubject = managerMapForErpMapper.selectDevelopmentsubjectByCommCode(vo.getCommCode());
//		managerHousekeeperCacheMapper.updateCommByProjectName(vo.getPkOrg(),vo.getCommName(),vo.getCommCode(),developmentsubject);

		int count = managerHousekeeperCacheMapper.countHousekeeperByOrgan(vo.getOrganName());
		managerMapCacheMapper.updateHousekeeperCountByOrganName(count,vo.getOrganName());

		return Response.response("修改成功");

	}

	@Override
	public Result getHouseKeeperNameTree() {
		List<HouseKeeperNameTreeDTO> dto=bdpsndocMapper.findALLNameData(null,null);
		for(HouseKeeperNameTreeDTO nameTreeDTO : dto) {
			List<String> pdto=bdpsndocMapper.findPhoneNumTreeByUserCode(nameTreeDTO.getCode());
			nameTreeDTO.setPhones(pdto);
		}
		return Response.response(dto);
	}

	@Override
	public Result queryByName(String regionName, String name) {
		List<HouseKeeperNameTreeDTO> dto=bdpsndocMapper.findALLNameData(name,regionName);
//		for(HouseKeeperNameTreeDTO nameTreeDTO : dto) {
//			List<String> pdto=bdpsndocMapper.findPhoneNumTreeByUserCode(nameTreeDTO.getCode());
//			nameTreeDTO.setPhones(pdto);
//		}
		return Response.response(dto);
	}

	@Override
	public Result queryByPhoneNum(String regionName, String phone) {
		return Response.response(managerHousekeeperCacheMapper.findALLPhoneNum(phone,regionName));
	}

	@Override
	public Result getDevelopmentSubjectTree() {
		return Response.response(managerMapForErpMapper.selectDevelopmentsubjectTree());
	}



	@Override
	public Result getGardenDistrictTree() {
		return Response.response(houseKeeperCommunicationMapper.selectGardenDistrictTree());
	}

	@Override
	public Result getAllCommNameTree(String userCode) {
		Integer count = userRoleService.countByUserCodeAndRoleCode(userCode, "manager_map_admin");
		List<TreeNode> list = new ArrayList<>();
		List<String> organList = new ArrayList<>();
		if(count>0){
			organList = managerMapForErpMapper.queryAllRegionName();
			if(CollectionUtils.isNotEmpty(organList)){
				for(String organ : organList){
					if(StringUtils.isNotEmpty(organ)){
						TreeNode tree = new TreeNode();
						List<TreeNode> comms = managerMapForErpMapper.queryCommByOrganName(organ);
						tree.setLabel(organ);
						tree.setChildren(comms);
						list.add(tree);
					}
				}
			}
		}else{
			organList = managerMapForErpMapper.queryRegionByUserCode(userCode);
			if(CollectionUtils.isNotEmpty(organList)){
				for(String organ : organList){
					if(StringUtils.isNotEmpty(organ)){
						TreeNode tree = new TreeNode();
						List<TreeNode> comms = managerMapForErpMapper.queryCommByOrganAndUser(organ,userCode);
						tree.setLabel(organ);
						tree.setChildren(comms);
						list.add(tree);
					}
				}
			}
		}
		return Response.response(list);
	}


	private Integer countMonths(Date JurisdictionMonth) {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		Calendar bef = Calendar.getInstance();
		Calendar aft = Calendar.getInstance();
		bef.setTime(date);
		aft.setTime(JurisdictionMonth);
		int month1 = bef.get(Calendar.MONTH)-aft.get(Calendar.MONTH);
		int month2 = (bef.get(Calendar.YEAR)-aft.get(Calendar.YEAR))*12;
		int month = month1+month2;
		return month;
	}


	@Override
	public Result exportList(HouseKeeperParamVo houseKeeperParamVo) {
		List<String> communityNames=new ArrayList<>();
		List<String> phoneNums=new ArrayList<>();
		String developmentSubjects=houseKeeperParamVo.getDevelopmentSubjects();
		String gardenDistricts=houseKeeperParamVo.getGardenDistricts();
		String commCode=houseKeeperParamVo.getCommCode();
		String organCode=houseKeeperParamVo.getOrganCode();
		if(StringUtils.isNotEmpty(developmentSubjects)) {
			List<DevelopmentSubjectDTO> developmentSubjectDTO = managerMapForErpMapper.selectDevelopmentsubjectData();
			if(StringUtils.isBlank(commCode)&&StringUtils.isBlank(houseKeeperParamVo.getOrganCode())) {
				List<String> commNames = new ArrayList<>();
				for(DevelopmentSubjectDTO dto :  developmentSubjectDTO) {
					if(dto.getdevelopmentSubject()!=null) {
						if(dto.getdevelopmentSubject().equals(developmentSubjects)) {
							commNames.add(dto.getCommName());
						}
					}
				}
				for(String str : commNames) {
					List<String> list = managerMapMapper.selectCommNameByProjectName(str);
					for(String s : list ) {
						communityNames.add(s);
					}
				}
			}else if(StringUtils.isBlank(commCode)&&StringUtils.isNotEmpty(houseKeeperParamVo.getOrganCode())){
				List<String> commNames= managerMapMapper.selectCommNameTreeByOrganNameStr(organCode);
				List<String> commNameForErp = new ArrayList<>();
				for(String str : commNames) {
					if(StringUtils.isNotBlank(str)) {
						commNameForErp.add(managerMapMapper.selectCommNameByPropertyProjectName(str));
					}
				}
				List<DevelopmentSubjectDTO> dto = managerMapForErpMapper.selectCommByDevelopmentsubject(commNameForErp);
				for(DevelopmentSubjectDTO ds : dto) {
					if(ds.getdevelopmentSubject()!=null) {
						if(ds.getdevelopmentSubject().equals(developmentSubjects)&&ds.getOrganName().equals(organCode)) {
							List<String> list = managerMapMapper.selectPropertyProjectNameByCommName(ds.getCommName());
							if(list!=null&&list.size()>0) {
								for(String s : list) {
									communityNames.add(s);
								}
							}
						}
					}
				}
				if(communityNames==null||communityNames.size()==0) {
					communityNames.add("");
				}
			}else if(StringUtils.isNotEmpty(commCode)&&StringUtils.isNotEmpty(organCode)){
				String commName = managerMapMapper.selectCommNameByPropertyProjectName(commCode);
				List<DevelopmentSubjectDTO> dto = managerMapForErpMapper.selectDevelopmentsubjectByComm(commName);
				for(DevelopmentSubjectDTO ds : dto) {
					if(ds.getdevelopmentSubject()!=null) {
						if(ds.getdevelopmentSubject().equals(developmentSubjects)) {
							communityNames.add(commCode);
						}else {
							communityNames.add("");
						}
					}
				}
			}
		}else{
			if(StringUtils.isBlank(commCode)){
				communityNames =managerMapMapper.selectCommNameTreeByOrganNameStr(organCode);
			}else{
				communityNames.add(commCode);
			}
		}
		if(StringUtils.isBlank(houseKeeperParamVo.getPhoneNum())){
			phoneNums=bdpsndocMapper.findPhoneNumByUserCode(houseKeeperParamVo.getUserCode());
		}else{
			phoneNums.add(houseKeeperParamVo.getPhoneNum());
		}
		List<HouseKeeperDTO> houseKeeperList=managerMapMapper.selectHouseKeeperPageDataByOrganCode(communityNames,houseKeeperParamVo.getUserCode(),phoneNums,gardenDistricts, null,null);

		for(int i=0;i<houseKeeperList.size();i++) {
			List<HouseKeeperDTO> houseErpInfo = managerMapForErpMapper.selectHouseCountPageDataByErp(houseKeeperList.get(i).getOrganName(), houseKeeperList.get(i).getCommName() ,houseKeeperList.get(i).getNAME());
			if(houseKeeperList.get(i).getBIRTHDATE()!=null) {
				houseKeeperList.get(i).setAgeStructure(houseKeeperList.get(i).getBIRTHDATE().substring(2, 3)+"0后");
			}
			if(houseErpInfo!=null&&houseErpInfo.size()>0) {
				if(houseErpInfo.get(0).getHouses()!=null || houseErpInfo.get(0).getVillas()!=null || houseErpInfo.get(0).getShops()!=null) {
					houseKeeperList.get(i).setHouses(houseErpInfo.get(0).getHouses());
					houseKeeperList.get(i).setVillas(houseErpInfo.get(0).getVillas());
					houseKeeperList.get(i).setShops(houseErpInfo.get(0).getShops());
				}
			}
			if(StringUtils.isNotBlank(houseKeeperList.get(i).getCommName())){
				List<HouseKeeperDTO> commInfo = managerMapForErpMapper.selectCommByErp(houseKeeperList.get(i).getOrganName(),houseKeeperList.get(i).getCommName());
				if(commInfo!=null&&commInfo.size()>0) {
					if((commInfo.get(0).getCommName()!=null&&!commInfo.get(0).getCommName().isEmpty())
							||(commInfo.get(0).getDevelopmentSubject()!=null&&!commInfo.get(0).getDevelopmentSubject().isEmpty())) {
						houseKeeperList.get(i).setDevelopmentSubject(commInfo.get(0).getDevelopmentSubject());
					}
				}
			}
			FenghuangHouseKeeperCommunication houseKeeperInfo=houseKeeperCommunicationMapper.selectHouseKeeperInfoByUserCode(houseKeeperList.get(i).getPK_ORG(),houseKeeperList.get(i).getCODE(),houseKeeperList.get(i).getBID());
			if(houseKeeperInfo!=null) {
				houseKeeperList.get(i).setJurisdictionForMonth(String.valueOf(countMonths(houseKeeperInfo.getJurisdictionMonth())));
			}
		}
		PageData pd = new PageData();
		pd.setData(houseKeeperList);
		return Response.response(pd);
	}


	@Override
	public Result houseKeeperCount(List<String> projects) {
		return Response.response(managerMapMapper.countHousekeeperByProjects(projects));
	}

}
