package cn.com.countrygarden.bi.main.service.performance.impl.common;

import cn.com.countrygarden.bi.main.dao.hmWygl.TbHSPRRegionAvatarInfoMapper;
import cn.com.countrygarden.bi.main.dao.performance.*;
import cn.com.countrygarden.bi.main.dao.sys.UserRolesMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbHsprCommunityMapper;
import cn.com.countrygarden.bi.main.model.hmWygl.TbHSPRRegionAvatarInfo;
import cn.com.countrygarden.bi.main.model.performance.PerformanceArea;
import cn.com.countrygarden.bi.main.model.performance.PerformanceElement;
import cn.com.countrygarden.bi.main.model.performance.PerformanceMonthly;
import cn.com.countrygarden.bi.main.model.performance.dto.PerformanceAreaDto;
import cn.com.countrygarden.bi.main.model.performance.monthly.*;
import cn.com.countrygarden.bi.main.model.sys.UserRoles;
import cn.com.countrygarden.bi.main.model.twerp.ErpCommunity;
import cn.com.countrygarden.bi.main.service.performance.AssessmentMonthlyTargetService;
import cn.com.countrygarden.bi.main.service.performance.common.PerformanceAreaService;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Condition;

import java.util.ArrayList;
import java.util.List;

@Service
public class PerformanceAreaServiceImpl implements PerformanceAreaService {

	@Autowired
	private PerformanceTargetMapper performanceTargetMapper;

	@Autowired
	private PerformanceScoreMapper performanceScoreMapper;

	@Autowired
	private PerformanceStatisticsMapper performanceStatisticsMapper;

	@Autowired
	private PerformanceAreaMapper performanceAreaMapper;

	@Autowired
	private TbHsprCommunityMapper tbHsprCommunityMapper;

	@Autowired
	private PerformanceElementMapper performanceElementMapper;

	@Autowired
	private PerformanceMonthlyStatisticsMapper performanceMonthlyStatisticsMapper;

	@Autowired
	private UserRolesMapper userRolesMapper;

	@Autowired
	private AssessmentMonthlyTargetService assessmentMonthlyTargetService;

	@Autowired
	private PerformanceMonthlyMapper performanceMonthlyMapper;

	@Autowired
	private TbHSPRRegionAvatarInfoMapper tbHSPRRegionAvatarInfoMapper;

	@Override
	public List<PerformanceArea> getAllAreasByType(String typeNo) {

		if (StringUtil.isBlankOrEmpty(typeNo))
			throw new IllegalArgumentException("类型不能为空!");

		List<PerformanceArea> areaList = performanceAreaMapper.selectAllByTypeNo(typeNo);
		if (areaList.size() == 0)
			throw new IllegalArgumentException("没有该类型的地区!");

		return areaList;
	}

	@Override
	public int getTotalByType(String typeNo) {

		if (StringUtil.isBlankOrEmpty(typeNo))
			throw new IllegalArgumentException("类型不能为空!");

		int total = performanceAreaMapper.selectCountByTypeNo(typeNo);
		return total;
	}

	@Override
	public List<String> getFilterList(List<String> areaList, String typeNo) {
		return performanceAreaMapper.areaFilter(areaList, typeNo);
	}

	@Override
	public String getSubTypeByHierachyId(String hierachyId) {

		String type = performanceAreaMapper.getSubType(hierachyId);
		if (StringUtil.isBlankOrEmpty(type))
			throw new RuntimeException("该地区id没有下级分类");

		return type;
	}

	@Override
	public void addPerformanceArea(PerformanceArea area) {

		performanceAreaMapper.insertSelective(area);
	}

	@Override
	public void updatePerformanceArea(PerformanceArea area) {

		performanceAreaMapper.updateByPrimaryKeySelective(area);
	}

	@Override
	public Object selectMonthlyEnvScoreInfo(String[] hierarchyIdList, int year, String userCode) {
		// 从ERP库取得该userCode能够查询到的包含 (区域id+城市id)
		List<ErpCommunity> allIdList = tbHsprCommunityMapper.findOrganBaseByUserCode(userCode, null);
		// 类型转换
		List<String> filterIds = new ArrayList<>();
		for (int i = 0; i < allIdList.size(); i++) {
			filterIds.add(allIdList.get(i).getOrganCode());
		}
		// 过滤剩只有区域的id
		List<String> organList = performanceAreaMapper.areaFilter(filterIds, "1");

		// 该账号可访问的 区域id
		List<String> selectHIdList = new ArrayList<>();
		// 判断传入的id集合是否为空
		if (hierarchyIdList == null || hierarchyIdList.length == 0) {// 为空，将Erp库查询到的组装到selectHIdList中
			for (String organ : organList) {
				selectHIdList.add(organ);
			}
		} else {// 不为空，判断传入的id在erp库中是否存在，存在则加入selectHIdList中
			for (String id : hierarchyIdList) {
				for (String organ : organList) {
					if (organ.equals(id)) {
						selectHIdList.add(id);
					}
				}
			}
		}
		if (selectHIdList.isEmpty()) {
			return "该账号无可访问区域数据！";
		}

		// 查询所有三级以上的指标，切不包含总指标
		Condition condition = new Condition(PerformanceElement.class);
		condition.createCriteria().andNotEqualTo("level", 4).andNotEqualTo("elementId", 0).andNotEqualTo("type", "城市公司")
				.andNotEqualTo("type", "加/减分项");
		List<PerformanceElement> performanceElementList = performanceElementMapper.selectByCondition(condition);

		// 查询本年度可以统计数据的月份数
		// 保持数据一致性，月份从月度统计表中取
		long elementid = performanceElementList.get(0).getElementId();// 取任意一个指标
		Integer month = performanceMonthlyStatisticsMapper.selectMaxMonth(elementid, year);
		if (month == null) {
			month = 0;
		}

		// int month =
		// performanceMonthlyMapper.selectCountMonthByYear(year);//从月度表取

		// 查询账号是否是区域总的，如果是还需要判断最新一个月是否发布，若无发布则只返回之前月份的数据
		Condition conditionField = new Condition(UserRoles.class);
		conditionField.createCriteria().andEqualTo("userCode", userCode).andEqualTo("roleCode", "performanceArea");
		List<UserRoles> userRolesList = userRolesMapper.selectByCondition(conditionField);
		if (userRolesList.size() > 0) {// 表示为区域总的账号
			// 查询最新季度是否发布了
			List<AssessmentMonthlyTarget> lastPublic = assessmentMonthlyTargetService.getOgranLastMonthPublic(year,
					month);
			if (lastPublic.size() > 0) {
				month--;
			}
		}

		List<OrganMonthScoreDetailDto> returnList = new ArrayList<>();// 最后返回的集合
		for (String hierarchyId : selectHIdList) {// 遍历该账号有的所有区域id

			OrganMonthScoreDetailDto scoreDetailDto = new OrganMonthScoreDetailDto();

			List<PerformanceMonthAveDto> monthAveDtoList = new ArrayList<>();
			for (int i = month; i >= 1; i--) {

				PerformanceMonthAveDto monthAveDto = new PerformanceMonthAveDto();
				monthAveDto.setMonth(i);// 设置月份信息

				List<PerformanceMonthDto> monthDtos = new ArrayList<>();// 每个月所有的DTO
				for (int j = 0; j < performanceElementList.size(); j++) {
					long elementId = performanceElementList.get(j).getElementId();// 获取id
					String elementName = performanceElementList.get(j).getName();// 获取指标名称
					// 通过年、月、指标id、地区id获得唯一一个实体
					PerformanceMonthly performanceMonthly = new PerformanceMonthDto(year, month, elementId,
							hierarchyId);// 父类引用指向子类实例
					PerformanceMonthly pm = performanceMonthlyMapper.getSelect(performanceMonthly);
					if (pm != null) {
						performanceMonthly = new PerformanceMonthDto(pm);
					}
					PerformanceMonthDto monthDto = (PerformanceMonthDto) performanceMonthly;
					// 设置指标名称i
					monthDto.setElementName(elementName);
					// 加到集合中
					monthDtos.add(monthDto);
				}
				// 组装monthAveDto
				monthAveDto.setMonthDtoList(monthDtos);// 设置每个月所有的Dto
				// 获取区域月度平均值 0 代表区域
				PerformanceMonthly pm = new PerformanceMonthly(year, i, 0, hierarchyId);
				pm = performanceMonthlyMapper.getSelect(pm);
				if (pm != null) {
					// 设置平均分
					String averageScore = pm.getCompleteRate();
					if (!StringUtil.isBlankOrEmpty(averageScore)) {
						monthAveDto.setElementsAverage(averageScore);
					}
					// 设置排名
					int ranges = pm.getRanges();
					monthAveDto.setRanges(ranges);
				}
				monthAveDtoList.add(monthAveDto);
				// 组装scoreDetailDto
				scoreDetailDto.setMonthAveDtoList(monthAveDtoList);
			}
			returnList.add(scoreDetailDto);

		}

		List<PerformanceAreaDto> envDtoList = this.performanceAreaMapper.selectByIds(selectHIdList);// 所有区域的集合
		// 获取图片
		List<TbHSPRRegionAvatarInfo> imageList = this.tbHSPRRegionAvatarInfoMapper.selectOrganList(selectHIdList);
		List<TbHSPRRegionAvatarInfo> commImageList = this.tbHSPRRegionAvatarInfoMapper.selectCommList(selectHIdList);
		for (PerformanceAreaDto envDto : envDtoList) {
			// 获取区域图片
			for (TbHSPRRegionAvatarInfo image : imageList) {
				if (image.getOrganCode().equals(envDto.getHierachyId())) {
					envDto.setImageUrl(image.getImageOnePath());
					envDto.setNames(image.getNames());
				}
			}
			// 获取区域下项目信息
			List<TbHSPRRegionAvatarInfo> commList = new ArrayList<>();
			for (TbHSPRRegionAvatarInfo comm : commImageList) {
				if (envDto.getHierachyId().equals(comm.getOrganCode())) {
					commList.add(comm);
				}
			}
			envDto.setCommInfo(commList);

			for (OrganMonthScoreDetailDto scoreDetailDto : returnList) {
				List<PerformanceMonthAveDto> dtoList = scoreDetailDto.getMonthAveDtoList();
				if (dtoList != null && dtoList.size() > 0) {
					if (envDto.getHierachyId().equals(dtoList.get(0).getMonthDtoList().get(0).getHierarchyId())) {
						scoreDetailDto.setOrgan(envDto);
					}
				}
			}
		}
		return returnList;
	}

	@Override
	public Object selectMonthlyCompanyScoreInfo(String[] hierarchyIdList, Integer year, String userCode) {
		// 从ERP库取得该userCode能够查询到的包含 (区域id+城市id)
		List<ErpCommunity> allIdList = tbHsprCommunityMapper.findOrganBaseByUserCode(userCode, null);
		// 类型转换
		List<String> filterIds = new ArrayList<>();
		for (int i = 0; i < allIdList.size(); i++) {
			filterIds.add(allIdList.get(i).getOrganCode());
		}
		// 过滤剩只有城市公司的id
		List<String> comList = performanceAreaMapper.areaFilter(filterIds, "2");

		// 该账号可访问的城市公司id
		List<String> selectHIdList = new ArrayList<>();
		// 判断传入的id集合是否为空
		if (hierarchyIdList == null || hierarchyIdList.length == 0) {// 为空，将Erp库查询到的组装到selectHIdList中
			for (String company : comList) {
				selectHIdList.add(company);
			}
		} else {// 不为空，判断传入的id在erp库中是否存在，存在则加入selectHIdList中
			for (String id : hierarchyIdList) {
				for (String company : comList) {
					if (company.equals(id)) {
						selectHIdList.add(id);
					}
				}
			}
		}
		if (selectHIdList.isEmpty()) {
			return "该账号无可访问城市公司数据！";
		}

		// 查询所有三级以上的指标，切不包含总指标
		Condition condition = new Condition(PerformanceElement.class);
		condition.createCriteria().andNotEqualTo("level", 4).andNotEqualTo("elementId", 1).andEqualTo("type", "城市公司");
		List<PerformanceElement> performanceElementList = performanceElementMapper.selectByCondition(condition);

		// 查询本年度可以统计数据的月份数
		// 保持数据一致性，月份从月度统计表中取
		long elementid = performanceElementList.get(0).getElementId();// 取任意一个指标
		int month = performanceMonthlyStatisticsMapper.selectMaxMonth(elementid, year);
		// int month = performanceMonthlyMapper.selectCountMonthByYear(year);

		// 查询账号是否是城市公司总的，如果是还需要判断最新一个月是否发布，若无发布则只返回之前月份的数据
		Condition conditionField = new Condition(UserRoles.class);
		conditionField.createCriteria().andEqualTo("userCode", userCode).andEqualTo("roleCode", "performanceCompany");
		List<UserRoles> userRolesList = userRolesMapper.selectByCondition(conditionField);
		if (userRolesList.size() > 0) {// 表示为区域总的账号
			// 查询最新季度是否发布了
			List<AssessmentMonthlyTarget> lastPublic = assessmentMonthlyTargetService.getCompanyLastMonthPublic(year,
					month);
			if (lastPublic.size() > 0) {
				month--;
			}
		}

		List<ComMonthScoreDetailDto> returnList = new ArrayList<>();// 最后返回的集合
		for (String hierarchyId : selectHIdList) {// 遍历该账号有的所有区域id

			ComMonthScoreDetailDto scoreDetailDto = new ComMonthScoreDetailDto();

			List<PerformanceMonthAveDto> monthAveDtoList = new ArrayList<>();
			for (int i = month; i >= 1; i--) {

				PerformanceMonthAveDto monthAveDto = new PerformanceMonthAveDto();
				monthAveDto.setMonth(i);// 设置当前月份

				List<PerformanceMonthDto> monthDtos = new ArrayList<>();// 每个月所有的DTO
				for (int j = 0; j < performanceElementList.size(); j++) {
					long elementId = performanceElementList.get(j).getElementId();// 获取id
					String elementName = performanceElementList.get(j).getName();// 获取指标名称
					// 通过年、月、指标id、地区id获得唯一一个实体
					PerformanceMonthly performanceMonthly = new PerformanceMonthDto(year, i, elementId, hierarchyId);
					PerformanceMonthly pm = performanceMonthlyMapper.getSelect(performanceMonthly);
					if (pm != null) {
						performanceMonthly = new PerformanceMonthDto(pm);
					}
					PerformanceMonthDto monthDto = (PerformanceMonthDto) performanceMonthly;
					// 设置指标名称
					monthDto.setElementName(elementName);
					// 加到集合中
					monthDtos.add(monthDto);
				}
				// 组装monthAveDtoList
				monthAveDto.setMonthDtoList(monthDtos);
				// 获取城市公司月度平均值 1 代表城市公司
				PerformanceMonthly pm = new PerformanceMonthly(year, i, 1, hierarchyId);
				pm = performanceMonthlyMapper.getSelect(pm);
				if (pm != null) {
					// 设置平均分
					String averageScore = pm.getCompleteRate();
					if (!StringUtil.isBlankOrEmpty(averageScore)) {
						monthAveDto.setElementsAverage(averageScore);
					}
					// 设置排名
					int ranges = pm.getRanges();
					monthAveDto.setRanges(ranges);
				}
				monthAveDtoList.add(monthAveDto);
				// 组装scoreDetailDto
				scoreDetailDto.setMonthAveDtoList(monthAveDtoList);
			}

			returnList.add(scoreDetailDto);
		}

		List<PerformanceAreaDto> comDtoList = this.performanceAreaMapper.selectByIds(selectHIdList);// 所有区域的集合
		// 获取图片
		List<TbHSPRRegionAvatarInfo> imageList = this.tbHSPRRegionAvatarInfoMapper.selectOrganList(selectHIdList);
		List<TbHSPRRegionAvatarInfo> commImageList = this.tbHSPRRegionAvatarInfoMapper.selectCommList(selectHIdList);
		for (PerformanceAreaDto comDto : comDtoList) {
			// 获取区域图片
			for (TbHSPRRegionAvatarInfo image : imageList) {
				if (image.getOrganCode().equals(comDto.getHierachyId())) {
					comDto.setImageUrl(image.getImageOnePath());
					comDto.setNames(image.getNames());
				}
			}
			// 获取城市公司下项目信息
			List<TbHSPRRegionAvatarInfo> commList = new ArrayList<>();
			for (TbHSPRRegionAvatarInfo comm : commImageList) {
				if (comDto.getHierachyId().equals(comm.getOrganCode())) {
					commList.add(comm);
				}
			}
			comDto.setCommInfo(commList);

			for (ComMonthScoreDetailDto scoreDetailDto : returnList) {
				List<PerformanceMonthAveDto> dtoList = scoreDetailDto.getMonthAveDtoList();
				if (dtoList.size() != 0) {
					if (comDto.getHierachyId().equals(dtoList.get(0).getMonthDtoList().get(0).getHierarchyId())) {
						scoreDetailDto.setOrgan(comDto);
					}
				}
			}
		}
		return returnList;
	}

}
