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

import cn.com.countrygarden.bi.main.dao.performance.PerformanceRecordMapper;
import cn.com.countrygarden.bi.main.dao.performance.PerformanceScoreMapper;
import cn.com.countrygarden.bi.main.dao.performance.PerformanceStatisticsMapper;
import cn.com.countrygarden.bi.main.dao.performance.PerformanceTargetMapper;
import cn.com.countrygarden.bi.main.model.performance.PerformanceRecord;
import cn.com.countrygarden.bi.main.model.performance.PerformanceScore;
import cn.com.countrygarden.bi.main.model.performance.PerformanceTarget;
import cn.com.countrygarden.bi.main.model.performance.dto.RecordPerformanceDto;
import cn.com.countrygarden.bi.main.service.performance.common.PerformanceRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PerformanceRecordServiceImpl implements PerformanceRecordService {

    @Autowired
    private PerformanceRecordMapper performanceRecordMapper;

    @Autowired
    private PerformanceTargetMapper performanceTargetMapper;

    @Autowired
    private PerformanceScoreMapper performanceScoreMapper;

    @Autowired
    private PerformanceStatisticsMapper performanceStatisticsMapper;

    @Override
    public int getTotalRecord(long elementId, int year, int quarter) {
        return performanceRecordMapper.selectCount(elementId,year,quarter);
    }

    @Override
    public void insertPerformanceRecord(PerformanceRecord record) {

        performanceRecordMapper.insertSelective(record);
    }

    @Override
    public List<String> getVacancyAreas(long elementId, int year, int quarter,String typeNo) {
        return performanceRecordMapper.selectNotExistAreaName(elementId,year,quarter,typeNo);
    }

    @Override
    public List<String> getMonthlyVacancyAreas(long elementId, int year, int month,String typeNo) {
        return performanceRecordMapper.selectMonthlyNotExistAreaName(elementId,year,month,typeNo);
    }

    @Override
    public long getRecordId(long elementId, int year, int quarter, String hierachyId) {

        long record_id = 0;
        PerformanceRecord record = new PerformanceRecord(hierachyId,elementId,year,quarter);
        PerformanceRecord record2;
        record2 = performanceRecordMapper.selectBySelective(record);
        if(record2 != null){
            record_id = record2.getRecordId();
        }
        return record_id;
    }

    @Override
    public PerformanceTarget getTarget(long recordId) {

        return performanceTargetMapper.selectByRecordId(recordId);
    }

    @Override
    public PerformanceScore getScore(long recordId) {

        return performanceScoreMapper.selectByRecordId(recordId);
    }

    @Override
    public void insertScoreSelective(long recordId,float score,float complete,float yearScore) {

        PerformanceScore performanceScore =  new PerformanceScore(recordId,score,complete,yearScore);

        performanceScoreMapper.insertScoreSelective(performanceScore);

    }

    @Override
    public void updateScoreSelective(long recordId,float score,float complete,float yearScore) {

        PerformanceScore performanceScore =  new PerformanceScore(recordId,score,complete,yearScore);

        performanceScoreMapper.updateScoreSelective(performanceScore);
    }

    @Override
    public void insertTargetSelective(long recordId, String threshold, String atLeast, String scream, String howl) {

        PerformanceTarget performanceTarget = new PerformanceTarget(recordId,threshold,atLeast,scream,howl);

        performanceTargetMapper.insertTargetSelective(performanceTarget);
    }

    @Override
    public void updateTargetSelective(long recordId, String threshold, String atLeast, String scream, String howl) {

        PerformanceTarget performanceTarget = new PerformanceTarget(recordId,threshold,atLeast,scream,howl);

        performanceTargetMapper.updateTargetSelective(performanceTarget);
    }

    @Override
    public void saveQuartlyAverageScoreAndSumScore(int year, int quarter) {
        //区域相关操作
        this.performanceScoreMapper.deleteQuarterlySumScore(year, quarter);
        this.performanceScoreMapper.insertQuarterlySumScore(year, quarter);//区域
        this.performanceScoreMapper.insertQuarterlySumScoreCompany(year, quarter);//城市公司
        this.performanceStatisticsMapper.deleteQuarterlyAverageScore(year, quarter);
        this.performanceStatisticsMapper.insertQuarterlyAverageScore(year, quarter);


        //区域
        List<PerformanceScore> last = this.performanceScoreMapper.getLastQuarterSort(0, quarter == 1 ? year - 1 : year, quarter == 1 ? 4 : quarter-1);
        List<PerformanceScore> now = this.performanceScoreMapper.getLastQuarterSort(0, year, quarter);

        for (PerformanceScore score : last) {
            for (PerformanceScore performanceScore : now) {
                if (score.getHierarchyId().equals(performanceScore.getHierarchyId())) {
                    int lastNo = score.getNum();
                    int nowNo = performanceScore.getNum();
                    performanceScore.setNum(lastNo - nowNo);
                    performanceScoreMapper.updateNum(performanceScore);
                }
            }
        }

        //城市公司
        List<PerformanceScore> lastCompany = this.performanceScoreMapper.getLastQuarterSortCompany(1, quarter == 1 ? year - 1 : year, quarter == 1 ? 4 : quarter-1);
        List<PerformanceScore> nowCompany = this.performanceScoreMapper.getLastQuarterSortCompany(1, year, quarter);

        for (PerformanceScore score : lastCompany) {
            for (PerformanceScore performanceScore : nowCompany) {
                if (score.getHierarchyId().equals(performanceScore.getHierarchyId())) {
                    int lastNo = score.getNum();
                    int nowNo = performanceScore.getNum();
                    performanceScore.setNum(lastNo - nowNo);
                    performanceScoreMapper.updateNum(performanceScore);
                }
            }
        }
    }

    @Override
    public void insertRecord(String hierachyId, long elementId, int year, int quarter,String rate,double weight,short isExamine) {

        PerformanceRecord performanceRecord = new PerformanceRecord(hierachyId,elementId,year,quarter,rate,weight,isExamine);

        performanceRecordMapper.insertSelective(performanceRecord);
    }

        @Override
        public void updateRecord(long recordId,String rate, double weight, short isExamine) {

            PerformanceRecord performanceRecord = new PerformanceRecord(recordId,rate,weight,isExamine);

            performanceRecordMapper.updateByPrimaryKeySelective(performanceRecord);

        }
        
        
        public void insertRecord(String hierachyId, long elementId, int year, int quarter,String rate,double weight,short isExamine,String lrdb,String fwzzdf) {

            PerformanceRecord performanceRecord = new PerformanceRecord(hierachyId,elementId,year,quarter,rate,weight,isExamine, lrdb, fwzzdf);

            performanceRecordMapper.insertSelective(performanceRecord);
        }

        public void updateRecord(long recordId,String rate, double weight, short isExamine,String lrdb,String fwzzdf) {

            PerformanceRecord performanceRecord = new PerformanceRecord(recordId,rate,weight,isExamine, lrdb, fwzzdf);

            performanceRecordMapper.updateByPrimaryKeySelective(performanceRecord);

        }

    @Override
    public void updateScope(String scope,long recordId) {
        performanceRecordMapper.updateScope(scope,recordId);
    }

    @Override
    public void performanceRecord(RecordPerformanceDto rd) {

        String hierachyId = rd.getHierachyId();
        long elementId = rd.getElementId();
        int year = rd.getYear();
        int quarter = rd.getQuarter();
        String fwzzdf = rd.getFwzzdf();
        String lrdb = rd.getLrdb();

        //从record表中查recordId
        long  recordId = this.getRecordId(elementId,year,quarter,hierachyId);
        if(recordId == 0){//无，新增记录
            this.insertRecord(hierachyId,elementId,year,quarter,"",0,(short)1,fwzzdf,lrdb);
            recordId = this.getRecordId(elementId,year,quarter,hierachyId);
        }

        //有recordId
        //记录Score
        PerformanceScore score = this.getScore(recordId);
        if(score != null){//更新
            this.updateScoreSelective(recordId,rd.getScore(),rd.getComplete(),rd.getYearly_score());
        }else{//新增
            this.insertScoreSelective(recordId,rd.getScore(),rd.getComplete(),rd.getYearly_score());
        }

        //记录Target
        PerformanceTarget target = this.getTarget(recordId);
        if(target != null){//更新
            this.updateTargetSelective(recordId,rd.getThreshold(),rd.getAt_Least(),rd.getScream(),rd.getHowl());
        }else{//新增
            this.insertTargetSelective(recordId,rd.getThreshold(),rd.getAt_Least(),rd.getScream(),rd.getHowl());
        }

        //更新record表的weight、rate、isExamine字段
        this.updateRecord(recordId,rd.getRate(),rd.getWeight(),rd.getIsExamine(),fwzzdf,lrdb);

    }

    @Override
    public void saveQuartlyAverageScoreAndSumScore2(int year, int quarter) {
        /**
         * 思路:1.根据年、季度获取所有elementId为0和1的recordId，删除record表和score表记录,先删除从表score再删除主表record
         *      2.插入record表记录，获取所有recordId再插入score表记录
         *      3.计算排名
         */
        this.performanceScoreMapper.deleteAllByRecordIds(year,quarter);
        this.performanceRecordMapper.deleteAllRecords(year,quarter);
        //区域
        this.performanceRecordMapper.insertQuarterlySumRecords(year,quarter,"1");
        this.performanceScoreMapper.insertQuarterlySumScore2(year,quarter,"1");
        //城市公司
        this.performanceRecordMapper.insertQuarterlySumRecords(year,quarter,"2");
        this.performanceScoreMapper.insertQuarterlySumScore2(year,quarter,"2");
        //新增季度平均成绩
        this.performanceStatisticsMapper.deleteAllByRecordIds(year,quarter);
        this.performanceStatisticsMapper.insertQuarterlyAverageScore2(year,quarter);

        //计算排名
        //区域
        List<PerformanceRecord> last = this.performanceRecordMapper.getLastQuarterSort(0, quarter == 1 ? year - 1 : year, quarter == 1 ? 4 : quarter-1,"1");
        List<PerformanceRecord> now = this.performanceRecordMapper.getLastQuarterSort(0,year,quarter,"1");

        this.updateRecordRange(last,now);

        //城市公司
        List<PerformanceRecord> lastCom = this.performanceRecordMapper.getLastQuarterSort(1, quarter == 1 ? year - 1 : year, quarter == 1 ? 4 : quarter-1,"2");
        List<PerformanceRecord> nowCom = this.performanceRecordMapper.getLastQuarterSort(1,year,quarter,"2");

        this.updateRecordRange(lastCom,nowCom);

    }

    @Override
    public PerformanceRecord getRecordSelective(long elementId, int year, int quarter, String hierachyId) {

        PerformanceRecord record = new PerformanceRecord(hierachyId,elementId,year,quarter);

        return performanceRecordMapper.selectBySelective(record);
    }

    //计算排名
    public  void updateRecordRange(List<PerformanceRecord> lastList, List<PerformanceRecord> nowList){

//        if(lastList.size() == 0 || nowList.size() ==0){
//            throw new RuntimeException("计算排名的集合为空!");
//        }

        for(PerformanceRecord last : lastList){
            for(PerformanceRecord now : nowList){
                if(now.getHierachyId().equals(last.getHierachyId())){
                    int lastNo = last.getRanges();
                    int nowNo = now.getRanges();
                    now.setRanges(lastNo - nowNo);
                    performanceRecordMapper.updateByPrimaryKeySelective(now);
                }
            }
        }
    }
}
