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.PerformanceCompanyService;
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.Calendar;
import java.util.List;

/**
 * 城市公司信息
 * @author Max Date:2018/09/12
 * @version 1.0
 * @since 1.8
 */
@Service
public class PerformanceCompanyServiceImpl implements PerformanceCompanyService {
    @Autowired
    private PerformanceCompanyMapper performanceCompanyMapper;

    @Autowired
    private TbHsprCommunityMapper tbHsprCommunityMapper;

    @Autowired
    private PerformanceElementMapper performanceElementMapper;

    @Autowired
    private PerformanceScoreMapper performanceScoreMapper;

    @Autowired
    private UserRolesMapper userRolesMapper;

    @Autowired
    private PerformanceTargetMapper performanceTargetMapper;

    @Autowired
    private AssessmentTargetMapper assessmentTargetMapper;

    @Autowired
    private TbHSPRRegionAvatarInfoMapper tbHSPRRegionAvatarInfoMapper;

    @Autowired
    private PerformanceEnvMapper performanceEnvMapper;

    @Autowired
    private PerformanceMonthlyMapper performanceMonthlyMapper;

    @Autowired
    private PerformanceMonthlyStatisticsMapper performanceMonthlyStatisticsMapper;

    @Autowired
    private AssessmentMonthlyTargetService assessmentMonthlyTargetService;

    @Override
    public int deleteByPrimaryKey(Long comId) {
        return performanceCompanyMapper.deleteByPrimaryKey(comId);
    }

    @Override
    public int insertSelective(PerformanceCompany record) {
        return performanceCompanyMapper.insertSelective(record);
    }

    @Override
    public PerformanceCompany selectByPrimaryKey(Long comId) {
        return performanceCompanyMapper.selectByPrimaryKey(comId);
    }

    @Override
    public int updateByPrimaryKeySelective(PerformanceCompany record) {
        return performanceCompanyMapper.updateByPrimaryKeySelective(record);
    }

    //获得有效的城市公司
    @Override
    public List<PerformanceCompany> selectPerformanceCompany() {
        return performanceCompanyMapper.selectPerformanceCompany();
    }

    //查询缺少的城市
    @Override
    public List<String> selectNotInNameCompany(PerformanceScore performanceScore) {
        return performanceCompanyMapper.selectNotInNameCompany(performanceScore);
    }

    //查询月度缺少的城市公司
    @Override
    public List<String> selectMonthlyNotExistCompany(int year,int month,long elementId){
       return performanceCompanyMapper.selectMonthlyNotInNameCompany(year,month,elementId);
    }

    //城市公司我的考核数据查询
    @Override
    public Object selectCompanyScoreInfo(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 = performanceCompanyMapper.selectCompFilter(filterIds);

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

        //返回的结果
        List<PerformanceCompanyScoreInfoDto> returnList = new ArrayList<>();
        List<PerformanceCompanyDto> comDtoList = performanceCompanyMapper.selectByIds(selectComIdList);

        //组装PerformanceCompanyScoreInfoDto

        //条件查询所有三级以上的"城市公司"指标
        Condition condition = new Condition(PerformanceElement.class);
        condition.createCriteria().andNotEqualTo("level", 4).andEqualTo("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","performanceCompany");
        List<UserRoles> userRolesList=userRolesMapper.selectByCondition(conditionField);
        if(userRolesList.size()>0){//表示为城市总的账号
            List<AssessmentTarget> lastPublic = assessmentTargetMapper.selectLastPublicCompany(year,String.valueOf(quarterCount));
            if(lastPublic.size() > 0){
                quarterCount--;
            }
        }

        for(String hierarchyId : selectComIdList){
            PerformanceCompanyScoreInfoDto companyScoreInfoDto = new PerformanceCompanyScoreInfoDto();

            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);
            }
            companyScoreInfoDto.setDetailInfo(detailInfoDtoList);
            returnList.add(companyScoreInfoDto);
        }

        //获取图片URL
        //获取图片
//        List<TbHSPRRegionAvatarInfo> imageList = this.tbHSPRRegionAvatarInfoMapper.selectOrganList(selectComIdList);
//        List<TbHSPRRegionAvatarInfo> commImageList = this.tbHSPRRegionAvatarInfoMapper.selectCommList(selectComIdList);
//        for (PerformanceCompanyDto envDto : comDtoList) {
//            //获取区域图片
//            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 (PerformanceCompanyScoreInfoDto scoreInfoDto : returnList) {
//                if (envDto.getHierarchyId().equals(scoreInfoDto.getDetailInfo().get(0).getScoreDetailInfo().get(0).getScoreInfo().getHierarchyId())) {
//                    scoreInfoDto.setOrganInfo(envDto);
//                }
//            }
//        }
        return returnList;
    }


    /**
     * 绩效分析—城市公司
     * @param element 指标
     * @param userCode 用户UserCode
     * @return JSON
     */
    @Override
    public Object selectScoreCompanyList(String element, String userCode) {
        //从erp获取有区域+城市公司的权限
        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=performanceCompanyMapper.selectCompFilter(hierarchyIdList);//过滤区域和无效的城市公司

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

        List<CompanyPerformanceScoreListDto> scoreListDtoList = new ArrayList<>();//将数据存储到该List中

        //获取最大的季度
        int quarterCount = performanceScoreMapper.selectCountQuarterByYear(year);
        quarterCount = quarterCount > 4 ? 4 : quarterCount;

        //遍历区域
        for (String hierarchyId : hierarchyIdList) {
            CompanyPerformanceScoreListDto performanceScoreListDto = new CompanyPerformanceScoreListDto();

            //先查城市公司相关信息
            List<PerformanceCompany> performanceComs = performanceCompanyMapper.selectByHierarchyId(hierarchyId);
            if (performanceComs.size() == 0) {
                continue;
            } else {
                performanceScoreListDto.setOrganInfo(new PerformanceCompanyDto(performanceComs.get(0)));
            }

            //获取分数相关
            List<PerformanceScore> performanceScores = new ArrayList<>();
            for (int i = quarterCount; i >= 1; i--) {
                PerformanceScoreDto performanceScore = this.performanceEnvMapper.selectScoreList(hierarchyId, element, year, i);
                if (performanceScore != null) {
                    performanceScores.add(performanceScore);
                } else {
                    PerformanceScoreDto score = new PerformanceScoreDto();
                    score.setHierarchyId(hierarchyId);
                    score.setYear(year);
                    score.setQuarterly(String.valueOf(i));
                    performanceScores.add(score);
                }
            }
            performanceScoreListDto.setScoreInfo(performanceScores);
            scoreListDtoList.add(performanceScoreListDto);
        }

        //获取图片
        List<TbHSPRRegionAvatarInfo> imageList = this.tbHSPRRegionAvatarInfoMapper.selectOrganList(hierarchyIdList);
        //List<TbHSPRRegionAvatarInfo> commImageList = this.tbHSPRRegionAvatarInfoMapper.selectCommList(hierarchyIdList);
        for (CompanyPerformanceScoreListDto 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;
    }

    /**
     * 通过hierachyId得到数据
     * @param hierarchy_id 城市公司指标id
     * @return list
     */
    @Override
    public List<PerformanceCompany> selectByHierarchyId(String hierarchy_id) {
        return performanceCompanyMapper.selectByHierarchyId(hierarchy_id);
    }

    /**
     * 得到城市公司所有id
     * @return List
     */
    @Override
    public List<PerformanceCompany> selectValidCompany() {
        return performanceCompanyMapper.selectValidCompany();
    }


    @Override
    public String getTypeByComId(String comId) {
        return performanceCompanyMapper.getTypeByHierarchyId(comId);
    }
}
