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

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.*;
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.service.performance.AssessmentMonthlyTargetService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceEnvService;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;

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


/**
 * 层级参数
 *
 * @author leo 严明斌
 * @version 2018-4-3 16:58:33
 */

@Service
public class PerformanceEnvServiceImpl implements PerformanceEnvService {

    @Autowired
    private PerformanceEnvMapper performanceEnvMapper;
    @Autowired
    private PerformanceScoreMapper performanceScoreMapper;

    @Autowired
    private PerformanceTargetMapper performanceTargetMapper;

    @Autowired
    private TbHsprCommunityMapper tbHsprCommunityMapper;
    @Autowired
    private TbHSPRRegionAvatarInfoMapper tbHSPRRegionAvatarInfoMapper;

    @Autowired
    private PerformanceElementMapper performanceElementMapper;

    @Autowired
    private PerformanceMonthlyMapper performanceMonthlyMapper;

    @Autowired
    private PerformanceMonthlyStatisticsMapper performanceMonthlyStatisticsMapper;

    @Autowired
    private UserRolesMapper userRolesMapper;

    @Autowired
    private AssessmentTargetMapper assessmentTargetMapper;

    @Autowired
    private AssessmentMonthlyTargetService assessmentMonthlyTargetService;

    /**
     * modified:Max   Date:2018/09/12
     * @param element 指标id
     * @param userCode UserCode
     * @return Object
     */
    @Override
    public Object selectScoreList(String element, String userCode) {
        List<ErpCommunity> organList = tbHsprCommunityMapper.findOrganBaseByUserCode(userCode, null);//获取区域id
        if (organList.isEmpty()) {
            return "该账号无可访问区域数据！";
        }
        List<String> hierarchyIdList = new ArrayList<>();
        for (ErpCommunity organ : organList) {
            hierarchyIdList.add(organ.getOrganCode());
        }

        //过滤多余城市公司和无效区域
        hierarchyIdList=performanceEnvMapper.selectOrganFilter(hierarchyIdList);

        Calendar date = Calendar.getInstance();
        Integer year = date.get(Calendar.YEAR);

        //@Author:Geoffrey
        //修改返回结果
        //整体思路：查询每个区域下，给定指标的所有季度成绩和区域信息，然后返回所有区域的信息
        List<OrganPerformanceScoreListDto> scoreListDtoList = new ArrayList<>();

        int quarterCount = performanceScoreMapper.selectCountQuarterByYear(year);
        quarterCount = quarterCount > 4 ? 4 : quarterCount;

        //遍历区域
        for (String hierarchyId : hierarchyIdList) {
            OrganPerformanceScoreListDto performanceScoreListDto = new OrganPerformanceScoreListDto();
            Condition condition = new Condition(PerformanceEnv.class);
            condition.createCriteria().andEqualTo("hierarchyId", hierarchyId);
            List<PerformanceEnv> performanceEnvs = performanceEnvMapper.selectByCondition(condition);
            if (performanceEnvs.size() == 0) {
                continue;
            } else {
                performanceScoreListDto.setOrganInfo(new PerformanceEnvDto(performanceEnvs.get(0)));
            }

            List<OrganPerformanceScoreDto> performanceScores = new ArrayList<>();
            for (int i = quarterCount; i >= 1; i--) {
                PerformanceScoreDto performanceScore = this.performanceEnvMapper.selectScoreList(hierarchyId, element, year, i);
                OrganPerformanceScoreDto opsd = null;
                if (performanceScore != null) {
                    opsd = OrganPerformanceScoreDto.getInstance(performanceScore);
                }else {
                    opsd = new OrganPerformanceScoreDto();
                    opsd.setHierarchyId(hierarchyId);
                    opsd.setYear(year);
                    opsd.setQuarterly(String.valueOf(i));
                }
                //利润规模
                PerformanceScore score=new PerformanceScore();
                score.setYear(year);//年
                score.setQuarterly(String.valueOf(i));//季度
                score.setHierarchyId(hierarchyId);//区域
                score.setElementId(999L);//二级id 事故数量
                PerformanceScore sValue=performanceScoreMapper.getscoreByHierarchyId(score);
                if(sValue!=null){
                    opsd.setScope(sValue.getScore());//设置利润规模
                }
                performanceScores.add(opsd);
            }
            performanceScoreListDto.setScoreInfo(performanceScores);
            scoreListDtoList.add(performanceScoreListDto);
        }

        //获取图片
        List<TbHSPRRegionAvatarInfo> imageList = this.tbHSPRRegionAvatarInfoMapper.selectOrganList(hierarchyIdList);
        List<TbHSPRRegionAvatarInfo> commImageList = this.tbHSPRRegionAvatarInfoMapper.selectCommList(hierarchyIdList);
        for (OrganPerformanceScoreListDto scoreListDto : scoreListDtoList) {
            for (TbHSPRRegionAvatarInfo image : imageList) {
                if (image.getOrganCode().equals(scoreListDto.getOrganInfo().getHierarchyId())) {
                    scoreListDto.getOrganInfo().setImageUrl(image.getImageOnePath());
                    scoreListDto.getOrganInfo().setNames(image.getNames());
                }
            }
            //获取区域下项目信息
            List commList = new ArrayList<TbHSPRRegionAvatarInfo>();
            for (TbHSPRRegionAvatarInfo comm : commImageList) {
                if (scoreListDto.getOrganInfo().getHierarchyId().equals(comm.getOrganCode())) {
                    commList.add(comm);
                }
            }
            scoreListDto.getOrganInfo().setCommInfo(commList);
        }

        return scoreListDtoList;
    }

    @Override
    public List<PerformanceEnv> selectPerformanceOrgan() {
        return this.performanceEnvMapper.selectPerformanceOrgan();
    }

    @Override
    public List<PerformanceEnv> selectPerformanceCompany() {
        return this.performanceEnvMapper.selectPerformanceCompany();
    }

    @Override
    public int insertEnvList(List<PerformanceEnv> envList) {
        return this.performanceEnvMapper.insertEnvList(envList);
    }

    @Override
    @Transactional
    public void updateEnvList(List<PerformanceEnv> envList) {
        for (PerformanceEnv env : envList) {
            this.performanceEnvMapper.updateByPrimaryKeySelective(env);
        }
    }

    @Override
    public void save(PerformanceEnv model) {

    }

    @Override
    public void save(List<PerformanceEnv> models) {

    }

    @Override
    public void deleteById(Integer id) {

    }

    @Override
    public void deleteByIds(String ids) {

    }

    @Override
    public void update(PerformanceEnv model) {

    }

    @Override
    public PerformanceEnv findById(Integer id) {
        return null;
    }

    @Override
    public PerformanceEnv findBy(String fieldName, Object value) throws TooManyResultsException {
        return null;
    }

    @Override
    public List<PerformanceEnv> findByIds(String ids) {
        return null;
    }

    @Override
    public List<PerformanceEnv> findByCondition(Condition condition) {
        return null;
    }

    @Override
    public List<PerformanceEnv> findAll() {
        return null;
    }

    @Override
    public PerformanceEnv getByHierarchyId(PerformanceEnv env) {
        return this.performanceEnvMapper.getByHierarchyId(env);
    }

    @Override
    public List<String> selectNotInName(PerformanceScore performanceScore) {
        return performanceEnvMapper.selectNotInName(performanceScore);
    }

    @Override
    public List<String> selectNotInNameCompany(PerformanceScore performanceScore) {
        return performanceEnvMapper.selectNotInNameCompany(performanceScore);
    }

    @Override
    public int insertSelective(PerformanceEnv record) {
        return performanceEnvMapper.insertSelective(record);
    }

    @Override
    public int updateByPrimaryKeySelective(PerformanceEnv record) {
        return performanceEnvMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public List<PerformanceEnv> selectAll() {
        return performanceEnvMapper.selectAll();
    }

    @Override
    public Object selectEnvScoreInfo(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> organList = performanceEnvMapper.selectOrganFilter(filterIds);

        //该账号可访问的 区域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 "该账号无可访问区域数据！";
        }
        List<PerformanceScoreInfoDto> returnList = new ArrayList<>();
        List<PerformanceEnvDto> envDtoList = this.performanceEnvMapper.selectById(selectHIdList);
//        List<PerformanceDetailInfoDto> detailInfoDtoList = this.performanceElementMapper.selectScoreInfo(selectHIdList, year);


        //@Author:Geoffrey
        //构造新的返回结果
        //[start]

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

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

        for (String hierarchyId : selectHIdList) {
            PerformanceScoreInfoDto scoreInfoDto = new PerformanceScoreInfoDto();

            List<PerformanceDetailInfoDto> detailInfoDtoList = new ArrayList<>();
            for (PerformanceElement performanceElement : performanceElementList) {
                //设置指标
                PerformanceDetailInfoDto performanceDetailInfoDto = new PerformanceDetailInfoDto();
                performanceDetailInfoDto.setElementInfo(performanceElement);
                //得分和目标

                List<PerformanceScoreDetailInfoDto> scoreAndTargetDTOs = new ArrayList<>();
                for (int i = quarterCount; i >= 1; i--) {
                    //score & target DTO
                    PerformanceScoreDetailInfoDto scoreAndTargetDTO = new PerformanceScoreDetailInfoDto();
                    PerformanceTarget t = new PerformanceTarget();
                    t.setHierarchyId(hierarchyId);
                    t.setElementId(performanceElement.getElementId());
                    t.setYear(year);
                    t.setQuarterly(String.valueOf(i));
                    PerformanceTarget tValue = performanceTargetMapper.getByHierarchyId(t);
                    if (tValue != null) {
                        scoreAndTargetDTO.setTargetInfo(tValue);
                    } else {
                        scoreAndTargetDTO.setTargetInfo(t);
                    }

                    PerformanceScore s = new PerformanceScore();
                    s.setHierarchyId(hierarchyId);
                    s.setElementId(performanceElement.getElementId());
                    s.setYear(year);
                    s.setQuarterly(String.valueOf(i));
                    PerformanceScore sValue = performanceScoreMapper.getscoreByHierarchyId(s);
                    if (sValue != null) {
                        scoreAndTargetDTO.setScoreInfo(sValue);
                    } else {
                        scoreAndTargetDTO.setScoreInfo(s);
                    }
                    scoreAndTargetDTOs.add(scoreAndTargetDTO);
                }
                performanceDetailInfoDto.setScoreDetailInfo(scoreAndTargetDTOs);
                detailInfoDtoList.add(performanceDetailInfoDto);
            }
            scoreInfoDto.setDetailInfo(detailInfoDtoList);
            returnList.add(scoreInfoDto);
        }
        //[end]


        //获取图片
//        List<TbHSPRRegionAvatarInfo> imageList = this.tbHSPRRegionAvatarInfoMapper.selectOrganList(selectHIdList);
//        List<TbHSPRRegionAvatarInfo> commImageList = this.tbHSPRRegionAvatarInfoMapper.selectCommList(selectHIdList);
//        for (PerformanceEnvDto envDto : envDtoList) {
//            //获取区域图片
//            for (TbHSPRRegionAvatarInfo image : imageList) {
//                if (image.getOrganCode().equals(envDto.getHierarchyId())) {
//                    envDto.setImageUrl(image.getImageOnePath());
//                    envDto.setNames(image.getNames());
//                }
//            }
//            //获取区域下项目信息
//            List<TbHSPRRegionAvatarInfo> commList = new ArrayList<>();
//            for (TbHSPRRegionAvatarInfo comm : commImageList) {
//                if (envDto.getHierarchyId().equals(comm.getOrganCode())) {
//                    commList.add(comm);
//                }
//            }
//            envDto.setCommInfo(commList);
//
//
//            for (PerformanceScoreInfoDto scoreInfoDto : returnList) {
//                if (envDto.getHierarchyId().equals(scoreInfoDto.getDetailInfo().get(0).getScoreDetailInfo().get(0).getScoreInfo().getHierarchyId())) {
//                    scoreInfoDto.setOrganInfo(envDto);
//                }
//            }
//            PerformanceScoreInfoDto scoreInfoDto = new PerformanceScoreInfoDto();
//            scoreInfoDto.setOrganInfo(envDto);
//            scoreInfoDto.setDetailInfo(new ArrayList<PerformanceDetailInfoDto>());
//            List<PerformanceDetailInfoDto> sciList = scoreInfoDto.getDetailInfo();
//            for (PerformanceDetailInfoDto detailInfoDto : detailInfoDtoList) {
//                if (envDto.getHierarchyId().equals(detailInfoDto.getScoreDetailInfo().get(0).getTargetInfo().getHierarchyId())) {
//                    sciList.add(detailInfoDto);
//                }
//            }
//            returnList.add(scoreInfoDto);
//          }

        return returnList;
    }

    //查询缺少的月度区域
    @Override
    public List<String> selectMonthlyNotInNameRegion(int year, int month, long elementId) {
        return performanceEnvMapper.selectMonthlyNotInNameRegion(year,month,elementId);
    }

    //单独抽出来用Redis做缓存
    //@Cacheable(value = "monthPerformance",key = "#hierarchyId.concat(#elementId).concat(#year).concat(#month)")
//    public PerformanceMonthly getPerformanceMonthly(String hierarchyId,long elementId,int year,int month){
//
//        String key = "monthPerformance";
//        String field = hierarchyId+elementId+year+month;
//        String result = null;//返回对象的json字符串
//        PerformanceMonthly rpm = null;//最终返回的对象
//        if(RedisUtils.hget(key,field) != null){
//            result = RedisUtils.hget(key,field);
//            rpm = JSON.parseObject(result,PerformanceMonthly.class);
//            return rpm;
//        }
//
//        PerformanceMonthly pm = new PerformanceMonthly(year,month,elementId,hierarchyId);
//        rpm = performanceMonthlyMapper.getSelect(pm);
//        //存入Redis中
//        String josnStr = JSON.toJSONString(rpm);
//        RedisUtils.hset(key,field,josnStr);
//
//        return rpm;
//    }
}
