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.exception.PerformanceException;
import cn.com.countrygarden.bi.main.model.hmWygl.TbHSPRRegionAvatarInfo;
import cn.com.countrygarden.bi.main.model.performance.*;
import cn.com.countrygarden.bi.main.model.performance.dto.*;
import cn.com.countrygarden.bi.main.model.sys.UserRoles;
import cn.com.countrygarden.bi.main.model.twerp.ErpCommunity;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysOrgan;
import cn.com.countrygarden.bi.main.service.performance.AssessmentTargetService;
import cn.com.countrygarden.bi.main.service.performance.common.PerformanceService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysOrganService;
import cn.com.countrygarden.bi.main.util.SyncErpToPerformanceUtil;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import tk.mybatis.mapper.entity.Condition;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@Service
public class PerformanceServiceImpl implements PerformanceService {

	@Autowired
	private TbHsprCommunityMapper tbHsprCommunityMapper;

	@Autowired
	private PerformanceElementMapper performanceElementMapper;

	@Autowired
	private PerformanceAreaMapper performanceAreaMapper;

	@Autowired
	private PerformanceRecordMapper performanceRecordMapper;

	@Autowired
	private PerformanceTargetMapper performanceTargetMapper;

	@Autowired
	private PerformanceScoreMapper performanceScoreMapper;

	@Autowired
	private PerformanceStatisticsMapper performanceStatisticsMapper;

	@Autowired
	private UserRolesMapper userRolesMapper;

	@Autowired
	private AssessmentTargetMapper assessmentTargetMapper;

	@Autowired
	private TbHSPRRegionAvatarInfoMapper tbHSPRRegionAvatarInfoMapper;

	@Autowired
	private AssessmentTargetService assessmentTargetService;

	@Override
	public List<ElementDto> getAllElements(String typeNo) {

		if (StringUtil.isBlankOrEmpty(typeNo))
			throw new PerformanceException("分类编码不能为空!");

		List<ElementDto> eleList = new ArrayList<>();
		List<PerformanceElement> list = performanceElementMapper.selectElementByType(typeNo);
		if (list.size() != 0) {
			for (PerformanceElement e : list) {
				ElementDto dto = new ElementDto();
				dto.setElementId(e.getElementId());
				dto.setElementName(e.getName());
				dto.setType(e.getType());
				eleList.add(dto);
			}
		} else {
			throw new PerformanceException("该分类下没有指标!");
		}

		return eleList;
	}

	@Override
	public List<String> getAllType() {
		return null;
	}

	@Override
	public Object releaseFun(String typeNo) {

		PerformanceRecord record = performanceRecordMapper.getNewYearQuarterByType(typeNo);
		if (record == null) {
			throw new PerformanceException("该类型地区无最新的年和季度!");
		}
		int year = record.getYear();
		int quarter = record.getQuarter();
		String quarterly = Integer.toString(quarter);

		// 查询区域是否全部锁定
		List<AssessmentTarget> unLockList = new ArrayList<>();

		if ("1".equals(typeNo))
			unLockList = assessmentTargetService.selectUnLockOrgan(year, quarterly);
		else if ("2".equals(typeNo))
			unLockList = assessmentTargetService.selectUnLockCompany(year, quarterly);

		Map<String, Object> result = new HashMap<>();// 返回前台的数据
		List<String> unLockUserNameList = new ArrayList<>();
		if (unLockList.size() > 0) {// 未完全锁定
			result.put("total", unLockList.size());// 条数
			for (AssessmentTarget unLockUserName : unLockList) {
				unLockUserNameList.add(unLockUserName.getElementname());
			}
			result.put("rows", unLockUserNameList);// 未锁定的指标名
		} else {// 如果完全锁定

			if ("1".equals(typeNo))
				assessmentTargetService.updatePublicStatusOrgan(year, quarterly);
			else if ("2".equals(typeNo))
				assessmentTargetService.updatePublicStatusCompany(year, quarterly);

			// 返回给前台数据
			result.put("total", -1);// 表示修改完成
			result.put("rows", unLockUserNameList);// 为了所有判断返回数据都对应一致
		}

		return result;
	}

	@Override
	public Object publicStatus(String typeNo) {
		Map<String, Integer> result = new HashMap<>();
		PerformanceRecord record = performanceRecordMapper.getNewYearQuarterByType(typeNo);
		if (record == null) {
			result.put("status", 0);// 该类型地区无最新的年和季度!
			return result;
		}
		int year = record.getYear();
		int quarter = record.getQuarter();
		String quarterly = Integer.toString(quarter);

		// 查询最新季度是否发布了
		List<AssessmentTarget> lastPublic = new ArrayList<>();
		if ("1".equals(typeNo))
			lastPublic = assessmentTargetService.selectLastPublicOrgan(year, quarterly);
		else if ("2".equals(typeNo))
			lastPublic = assessmentTargetService.selectLastPublicCompany(year, quarterly);

		if (lastPublic.size() > 0) {
			result.put("status", 0);// 表示还没发布
		} else {
			result.put("status", 1);// 表示发布了
		}

		return result;
	}

	@Override
	public Object myPerformance(String[] selectAreaList, int year, int quarter, String userCode, String typeNo) {
		year = 2018;// 暂时设置为2018，后续修改为2019
		// 条件查询所有三级以上"区域或城市公司"指标
		Condition condition = new Condition(PerformanceElement.class);
		condition.createCriteria().andNotEqualTo("level", 4).andEqualTo("typeNo", typeNo);
		List<PerformanceElement> elements = performanceElementMapper.selectByCondition(condition);
		// 查询今年目前可以统计数据的季度数
		int quarterCount = performanceRecordMapper.selectCountQuarterByYear(year);

		// 查询账号是否是区域总的，如果是得看最新的一个季度是否是发布，如果没发布，则只返回新季度之前的数据
		String roleCode = "";
		if ("1".equals(typeNo))
			roleCode = "performanceArea";
		else if ("2".equals(typeNo))
			roleCode = "performanceCompany";
		Condition conditionField = new Condition(UserRoles.class);
		conditionField.createCriteria().andEqualTo("userCode", userCode).andEqualTo("roleCode", roleCode);
		List<UserRoles> userRolesList = userRolesMapper.selectByCondition(conditionField);
		if (userRolesList.size() > 0) {// 表示为区域总的账号
			// 查询最新季度是否发布了
			List<AssessmentTarget> lastPublic = assessmentTargetMapper.selectLastPublicOrgan(year,
					String.valueOf(quarterCount));
			if (lastPublic.size() > 0) {
				quarterCount--;
			}
		}
		// 验证季度的正确性
		quarter = quarter <= quarterCount ? quarter : quarterCount;
		// 默认返回最新季度的数据
		if (quarter == 0)
			quarter = quarterCount;

		List<MyPerformanceDto> returnList = null;
		try {
			returnList = new ArrayList<>();
			for (String hierachyId : selectAreaList) {
				MyPerformanceDto mpDto = new MyPerformanceDto();
				mpDto.setMaxQuarter(quarterCount);

				List<MyPerformanceDetailDto> mpDetailDtos = new ArrayList<>();
				for (PerformanceElement e : elements) {
					// 设置指标
					MyPerformanceDetailDto detailDto = new MyPerformanceDetailDto();
					detailDto.setElementInfo(e);

					// 得分和目标
					List<PerformanceRecordDto> recordDtos = new ArrayList<>();
					// 季度是确定的
					PerformanceRecord record = new PerformanceRecordDto(hierachyId, e.getElementId(), year, quarter);
					PerformanceRecordDto recordDto = performanceRecordMapper.selectBySelective(record);
					PerformanceTarget target;
					PerformanceScore score;
					if (recordDto != null) {
						long recordId = recordDto.getRecordId();
						target = performanceTargetMapper.selectByRecordId(recordId);
						score = performanceScoreMapper.selectByRecordId(recordId);
					} else {
						recordDto = new PerformanceRecordDto(hierachyId, e.getElementId(), year, quarter);
						target = new PerformanceTarget();
						score = new PerformanceScore();
					}
					recordDto.setTargetInfo(target == null ? new PerformanceTarget() : target);
					recordDto.setScoreInfo(score == null ? new PerformanceScore() : score);
					recordDtos.add(recordDto);

					detailDto.setScoreDetailInfo(recordDtos);
					mpDetailDtos.add(detailDto);
				}
				mpDto.setDetailInfo(mpDetailDtos);
				returnList.add(mpDto);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return returnList;
	}

	@Override
	public Object getAreaInfo(String[] hierarchyIdList, String userCode, String typeNo) {

		// 过滤出账号所有的有效区域
		List<String> selectAreaList = this.selectAreaList(userCode, hierarchyIdList, typeNo);
		if (selectAreaList.isEmpty()) {
			throw new PerformanceException("该账号无可访问地区数据！");
		}
		List<PerformanceAreaDto> dtoList = performanceAreaMapper.selectByIds(selectAreaList);
		// 获取图片
		this.setAreaImageInfo(selectAreaList, dtoList);

		return dtoList;
	}

	@Override
	public Object getAreaSum(String[] hierarchyIdList, int year, String userCode, String typeNo) {
		year=2018;//暂时设置为2018，后续修改为2019
		// 查询今年目前可以统计数据的季度数
		int quarterCount = performanceRecordMapper.selectCountQuarterByYear(year);
		//之前5表示半年度，6表示年度，现在这两个取消了，但数据库有相应的值，所以这里做了该判断
		if(quarterCount!=0&&quarterCount>=5){
			quarterCount=4;
		}

		// 查询账号是否是区域总的，如果是得看最新的一个季度是否是发布，如果没发布，则只返回新季度之前的数据
		String roleCode = "";
		if ("1".equals(typeNo))
			roleCode = "performanceArea";
		else if ("2".equals(typeNo))
			roleCode = "performanceCompany";
		Condition conditionField = new Condition(UserRoles.class);
		conditionField.createCriteria().andEqualTo("userCode", userCode).andEqualTo("roleCode", roleCode);
		List<UserRoles> userRolesList = userRolesMapper.selectByCondition(conditionField);
		if (userRolesList.size() > 0) {// 表示为区域总的账号
			// 查询最新季度是否发布了
			List<AssessmentTarget> lastPublic = assessmentTargetMapper.selectLastPublicOrgan(year,
					String.valueOf(quarterCount));
			if (lastPublic.size() > 0) {
				quarterCount--;
			}
		}

		long elementId = 0;// 默认是区域的
		if ("2".equals(typeNo)) {
			elementId = 1;
		}

		Integer reocrdId = 0;
		PerformanceScore score;
		// 返回所有季度总成绩
		List<PerformanceScore> scoreList = new ArrayList<>();
		for (String hierachyId : hierarchyIdList) {

			for (int i = quarterCount; i >= 1; i--) {
				PerformanceRecord record = new PerformanceRecord(hierachyId, elementId, year, i);
				reocrdId = performanceRecordMapper.selectBySelective3(record);
				if (reocrdId == null) {

					reocrdId = 111111;

				}
				
					score = performanceScoreMapper.selectByRecordId(reocrdId);
					if (score != null) {
					score.setYear(year);
					score.setQuarterly(String.valueOf(i));
					scoreList.add(score);
				}
			}
		}
		if(scoreList.size()<=0){
			 
		      PerformanceScore performanceScore =new PerformanceScore ();
		 
		      scoreList.add(performanceScore);
		 
		    }
		return scoreList;
	}

	@Override
	public Object getElementAveScore(long elementId) {

		/**
		 * 返回的list必须是有4个季度的数据，如果数据库查询不足4个季度，需要补全。 1.判断list的长度是否为0 是 直接生成4个季度的数据
		 * 2.不是 判断list的长度是否为4 3.不是 找出缺少的季度填充(暂不做填充) 4. 用TreeSet为了排序
		 */

		TreeSet<PerformanceStatistics> set;
		// 获取当前年份(这个是接口本来就写死这样的，后面可能还是要改为2019)
		int year = 2018;
		set = performanceStatisticsMapper.selectAllQuarterAve(year, elementId);
		if (set.size() == 0) {
			set = new TreeSet<>();
			for (int i = 1; i < 5; i++) {
				PerformanceStatistics statistics = new PerformanceStatistics();
				statistics.setQuarter(String.valueOf(i));
				set.add(statistics);
			}
		}
		return set;
	}

	@Override
	public Object performanceAnalysis(long elementId, String typeNo, String userCode, int quarter) {

		// 过滤出账号所有的有效area
		List<String> selectAreaList = this.selectAreaList(userCode, null, typeNo);
		if (selectAreaList.isEmpty()) {
			throw new PerformanceException("该账号无可访问地区数据！");
		}

		// 季度的验证
		if (quarter <= 0 || quarter > 4) {
			throw new PerformanceException("季度只能是1到4!");
		}

		// 查询所有area的信息
		List<PerformanceAreaDto> dtoList = performanceAreaMapper.selectByIds(selectAreaList);
		// 获取当前年份(暂时设置为2018年，后续在做修改)
		int year = 2018;
		// int quarterCount =
		// performanceRecordMapper.selectCountQuarterByYear(year);

		// 提前一次性加载所有利润规模的数据
		List<Map<String, String>> scopeList = performanceRecordMapper.selectScope(999L, year, quarter);
		Map<String, String> scopeMap = null;
		if (scopeList.size() != 0) {
			scopeMap = new HashMap<>();
			for (Map<String, String> map : scopeList) {
				scopeMap.put(map.get("hierachy_id"), map.get("scope"));
			}
		}

		// 返回数据
		List<PerformanceAnalysisDto> analysisDtos = new ArrayList<>();

		for (String hierachyId : selectAreaList) {
			PerformanceAnalysisDto analysisDto = new PerformanceAnalysisDto();

			List<PerformanceAnalysisRecordDto> analysisRecordDtos = new ArrayList<>();

			PerformanceRecord record = new PerformanceAnalysisRecordDto(hierachyId, elementId, year, quarter);
			PerformanceStatistics statistics;
			// 查出hierachyId、year、quarter、elementId下的target和score值
			PerformanceAnalysisRecordDto recordDto = performanceRecordMapper.selectBySelective2(record);
			if (recordDto == null) {
				recordDto = new PerformanceAnalysisRecordDto(hierachyId, elementId, year, quarter);
			}
			statistics = performanceStatisticsMapper.selectBySelective(elementId, year, quarter);
			// stastics
			if (statistics != null) {
				recordDto.setAverageScore(statistics.getAverageScore());
				recordDto.setActualAverageScore(statistics.getActualAverageScore());
			}
			// 填充利润规模值
			if (scopeMap != null) {
				recordDto.setScope(scopeMap.get(hierachyId));
			}

			analysisRecordDtos.add(recordDto);

			analysisDto.setAnalysisRecordDtos(analysisRecordDtos);
			analysisDtos.add(analysisDto);
		}

		this.setAreaImageInfo(selectAreaList, dtoList);

		for (PerformanceAnalysisDto analysisDto : analysisDtos) {
			for (PerformanceAreaDto areaDto : dtoList) {
				if (areaDto.getHierachyId().equals(analysisDto.getAnalysisRecordDtos().get(0).getHierachyId())) {
					analysisDto.setOrganInfo(areaDto);
					break;
				}
			}
		}

		return analysisDtos;
	}

	/**
	 * 根据账号查询地区，并过滤无效地区（分类）
	 *
	 * @param userCode
	 * @param areaList
	 * @param typeNo
	 * @return
	 */
	private List<String> selectAreaList(String userCode, String[] areaList, String typeNo) {
		// 从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());
		}
		// 过滤地区
		List<String> selectList = performanceAreaMapper.areaFilter(filterIds, typeNo);

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

		return selectHIdList;
	}

	/**
	 * 设置area区域Image信息
	 */
	private List<PerformanceAreaDto> setAreaImageInfo(List<String> areaIds, List<PerformanceAreaDto> areaDtos) {
		// 获取图片
		List<TbHSPRRegionAvatarInfo> imageList = this.tbHSPRRegionAvatarInfoMapper.selectOrganList(areaIds);
		List<TbHSPRRegionAvatarInfo> commImageList = this.tbHSPRRegionAvatarInfoMapper.selectCommList(areaIds);
		for (PerformanceAreaDto areaDto : areaDtos) {
			// 获取区域图片
			for (TbHSPRRegionAvatarInfo image : imageList) {
				if (image.getOrganCode().equals(areaDto.getHierachyId())) {
					areaDto.setImageUrl(image.getImageOnePath());
					areaDto.setNames(image.getNames());
				}
			}
			// 获取区域下项目信息
			List<TbHSPRRegionAvatarInfo> commList = new ArrayList<>();
			for (TbHSPRRegionAvatarInfo comm : commImageList) {
				if (areaDto.getHierachyId().equals(comm.getOrganCode())) {
					commList.add(comm);
				}
			}
			areaDto.setCommInfo(commList);
		}
		return areaDtos;
	}

	@Override
	public Object myPerformance2(String[] areaList, int year, String userCode, String typeNo) {

		// 过滤出账号所有的有效区域
		List<String> selectAreaList = this.selectAreaList(userCode, areaList, typeNo);
		if (selectAreaList.isEmpty()) {
			return "该账号无可访问地区数据！";
		}
		List<PerformanceAreaDto> dtoList = performanceAreaMapper.selectByIds(selectAreaList);

		// 条件查询所有三级以上"区域或城市公司"指标
		Condition condition = new Condition(PerformanceElement.class);
		condition.createCriteria().andNotEqualTo("level", 4).andEqualTo("typeNo", typeNo);
		List<PerformanceElement> elements = performanceElementMapper.selectByCondition(condition);
		// 查询今年目前可以统计数据的季度数
		int quarterCount = performanceRecordMapper.selectCountQuarterByYear(year);

		// 查询账号是否是区域总的，如果是得看最新的一个季度是否是发布，如果没发布，则只返回新季度之前的数据
		String roleCode = "";
		if ("1".equals(typeNo))
			roleCode = "performanceArea";
		else if ("2".equals(typeNo))
			roleCode = "performanceCompany";
		Condition conditionField = new Condition(UserRoles.class);
		conditionField.createCriteria().andEqualTo("userCode", userCode).andEqualTo("roleCode", roleCode);
		List<UserRoles> userRolesList = userRolesMapper.selectByCondition(conditionField);
		if (userRolesList.size() > 0) {// 表示为区域总的账号
			// 查询最新季度是否发布了
			List<AssessmentTarget> lastPublic = assessmentTargetMapper.selectLastPublicOrgan(year,
					String.valueOf(quarterCount));
			if (lastPublic.size() > 0) {
				quarterCount--;
			}
		}

		List<MyPerformanceDto> returnList = null;
		try {
			returnList = new ArrayList<>();
			for (String hierachyId : selectAreaList) {
				MyPerformanceDto mpDto = new MyPerformanceDto();

				List<MyPerformanceDetailDto> mpDetailDtos = new ArrayList<>();
				for (PerformanceElement e : elements) {
					// 设置指标
					MyPerformanceDetailDto detailDto = new MyPerformanceDetailDto();
					detailDto.setElementInfo(e);

					// 得分和目标
					List<PerformanceRecordDto> recordDtos = new ArrayList<>();
					for (int i = quarterCount; i >= 1; i--) {
						PerformanceRecord record = new PerformanceRecordDto(hierachyId, e.getElementId(), year, i);
						PerformanceRecordDto recordDto = performanceRecordMapper.selectBySelective(record);
						PerformanceTarget target;
						PerformanceScore score;
						if (recordDto != null) {
							long recordId = recordDto.getRecordId();
							target = performanceTargetMapper.selectByRecordId(recordId);
							score = performanceScoreMapper.selectByRecordId(recordId);
						} else {
							recordDto = new PerformanceRecordDto(hierachyId, e.getElementId(), year, i);
							target = new PerformanceTarget();
							score = new PerformanceScore();
						}
						recordDto.setTargetInfo(target == null ? new PerformanceTarget() : target);
						recordDto.setScoreInfo(score == null ? new PerformanceScore() : score);
						recordDtos.add(recordDto);
					}
					detailDto.setScoreDetailInfo(recordDtos);
					mpDetailDtos.add(detailDto);
				}
				mpDto.setDetailInfo(mpDetailDtos);
				returnList.add(mpDto);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 获取图片
		this.setAreaImageInfo(selectAreaList, dtoList);

		for (MyPerformanceDto mpDto : returnList) {
			for (PerformanceAreaDto areaDto : dtoList) {
				if (areaDto.getHierachyId()
						.equals(mpDto.getDetailInfo().get(0).getScoreDetailInfo().get(0).getHierachyId())) {
					mpDto.setOrganInfo(areaDto);
				}
			}

		}

		return returnList;
	}

}
