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

import cn.com.countrygarden.bi.main.model.performance.*;
import cn.com.countrygarden.bi.main.model.performance.dto.PerformanceShowDataDto;
import cn.com.countrygarden.bi.main.model.performance.dto.RecordPerformanceDto;
import cn.com.countrygarden.bi.main.service.performance.indicators.AbstractIndicatorService;
import cn.com.countrygarden.bi.main.util.Calculate;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 主营税前利润【城】
 *
 * @Author：Wyman
 * @Date：2018/11/3
 */
@Service
public class PrincipalProfitServiceImpl<T> extends AbstractIndicatorService<T> {

    @Override
    public Object showData(long elementId, int year, int quarter, int pageCurr, int pageSize, String typeNo) {

        //展示的dto实体
        PerformanceShowDataDto result = this.setVacancyInfo(elementId,year,quarter,typeNo);

        //使用mybatis PageHelper类进行分页
        PageHelper.startPage(pageCurr,pageSize);
        List<PerformanceArea> organList = this.performanceAreaService.getAllAreasByType(typeNo);//查出来的分页记录数

        if(organList.size() != 0){

            //组装返回的数据
            List<PrincipalProfit> returnList = new ArrayList<>();

            PerformanceTarget target;
            PerformanceScore score;
            PerformanceRecord record;
            long recordId;
            long elementId2 = 1019001L;
            long elementId3 = 1019002L;

            for(PerformanceArea p : organList){

                String hierachyId = p.getHierachyId();

                PrincipalProfit principalProfit = new PrincipalProfit();// 税前利润实体bean
                principalProfit.setHierarchyId(hierachyId);//区域id
                principalProfit.setYear(year);//年
                principalProfit.setQuarter(String.valueOf(quarter));//季度
                principalProfit.setSecond_organization(p.getHierachyName());// 项目区域
                principalProfit.setThird_organization(p.getHierachyName());// 项目区域

                //---------------上半年 综合利润 HY---------------
                if (quarter > 2) {
                    recordId = performanceRecordService.getRecordId(elementId2,year,2,hierachyId);
                } else {
                    recordId = performanceRecordService.getRecordId(elementId2,year,quarter,hierachyId);
                }
                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    principalProfit.setHyComplete(String.valueOf(score.getComplete()));//综合税前利润完成值
                    principalProfit.setHyScore(String.valueOf(score.getScore()));//综合税前利润细项得分
                }
                target = performanceRecordService.getTarget(recordId);
                if (target != null) {
                    principalProfit.setHyThreshold(target.getThresholdTarget());//门槛
                    principalProfit.setHyAtLeast(target.getAtLeastTarget());//保底
                    principalProfit.setHyScream(target.getScreamTarget());//尖叫
                    principalProfit.setHyHowl(target.getHowlTarget());//嚎叫
                }

                //--------------上半年 税前利润 HYC--------------
                if (quarter > 2) {
                    recordId = performanceRecordService.getRecordId(elementId3,year,2,hierachyId);
                } else {
                    recordId = performanceRecordService.getRecordId(elementId3,year,quarter,hierachyId);
                }
                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    principalProfit.setHyComplete(String.valueOf(score.getComplete()));//综合税前利润完成值
                    principalProfit.setHyScore(String.valueOf(score.getScore()));//综合税前利润细项得分
                }
                target = performanceRecordService.getTarget(recordId);
                if (target != null) {
                    principalProfit.setHyThreshold(target.getThresholdTarget());//门槛
                    principalProfit.setHyAtLeast(target.getAtLeastTarget());//保底
                    principalProfit.setHyScream(target.getScreamTarget());//尖叫
                    principalProfit.setHyHowl(target.getHowlTarget());//嚎叫
                }

                //--------------全年 综合利润 AL--------------
                recordId = performanceRecordService.getRecordId(elementId2,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if (score != null) {
                    principalProfit.setAlComplete(String.valueOf(score.getComplete()));
                    principalProfit.setAlScore(String.valueOf(score.getScore()));
                }

                target = performanceRecordService.getTarget(recordId);
                if (target != null) {
                    principalProfit.setAlThreshold(target.getThresholdTarget());
                    principalProfit.setAlAtLeast(target.getAtLeastTarget());
                    principalProfit.setAlScream(target.getScreamTarget());
                    principalProfit.setAlHowl(target.getHowlTarget());
                }

                //--------------全年 税前利润 ALC--------------
                recordId = performanceRecordService.getRecordId(elementId3,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    principalProfit.setAlcComplete(String.valueOf(score.getComplete()));
                    principalProfit.setAlcScore(String.valueOf(score.getScore()));
                }
                target = performanceRecordService.getTarget(recordId);
                if(target != null){
                    principalProfit.setAlcThreshold(target.getThresholdTarget());
                    principalProfit.setAlcAtLeast(target.getAtLeastTarget());
                    principalProfit.setAlcScream(target.getScreamTarget());
                    principalProfit.setAlcHowl(target.getHowlTarget());
                }

                //-----------指标总得分---------
                record = performanceRecordService.getRecordSelective(elementId,year,quarter,hierachyId);
                if (record != null) {
                    principalProfit.setIsCheck(record.getIsExamine() == 1 ? "1" : "0");

                    recordId = record.getRecordId();
                    score = performanceRecordService.getScore(recordId);
                    if(score != null){
                        principalProfit.setIndividualscore(String.valueOf(score.getScore()));
                    }
                } else {
                    principalProfit.setIsCheck("0");
                }
                returnList.add(principalProfit);
            }
            result.setDataList(returnList);
        }
        return result;
    }

    @Override
    public Object saveData(long elementId, int year, int quarter, List<Object> values) {

        String jsonString = JSONObject.toJSONString(values);

        List<PrincipalProfit> list = JSON.parseObject(jsonString,new TypeReference<List<PrincipalProfit>>(){});

        long elementId2 = 1019001L;
        long elementId3 = 1019002L;

        for(PrincipalProfit principalProfit : list){

            String hierachyId = principalProfit.getHierarchyId();
            String type = performanceAreaService.getSubTypeByHierachyId(hierachyId);
            double weight = 0;
            switch (type){
                case "单一业主项目":
                    weight = 0.1;
                    break;
                case "多业主第一年":
                    weight = 0.1;
                    break;
                case "多业主第二年":
                    weight = 0.1;
                    break;
            }

            String[] thresholds = {principalProfit.getHyThreshold(), principalProfit.getAlThreshold(), principalProfit.getHycThreshold(), principalProfit.getAlcThreshold()};
            String[] atLasts = {principalProfit.getHyAtLeast(), principalProfit.getAlAtLeast(), principalProfit.getHycAtLeast(), principalProfit.getAlcAtLeast()};
            String[] screams = {principalProfit.getHyScream(), principalProfit.getAlScream(), principalProfit.getHycScream(), principalProfit.getAlcScream()};
            String[] howls = {principalProfit.getHyHowl(), principalProfit.getAlHowl(), principalProfit.getHycHowl(), principalProfit.getAlcHowl()};
            String[] completes = {principalProfit.getHyComplete(), principalProfit.getAlComplete(), principalProfit.getHycComplete(), principalProfit.getAlcComplete()};
            String[] scores = {"-1", "-1", "-1", "-1"};

            double complete = -1;
            double threshold = -1;
            double atLeast = -1;
            double scream = -1;
            double howl = -1;


            RecordPerformanceDto performanceDto = new RecordPerformanceDto();
            performanceDto.setYear(year);
            performanceDto.setHierachyId(hierachyId);

            for (int i = 0; i < 4; i++) {
                long subElementId = i <= 1 ? elementId2 : elementId3;
                int q = quarter;
                if (i % 2 == 0) {       // 0 2 上半年
                    q = quarter > 2 ? 2 : quarter;
                }

                if (!StringUtil.isBlankOrEmpty(completes[i])) {
                    complete = Double.parseDouble(completes[i]);// 完成值
                } else {
                    continue;
                }
                if (!StringUtil.isBlankOrEmpty(thresholds[i])) {
                    threshold = Double.parseDouble(thresholds[i]);// 门槛
                }
                if (!StringUtil.isBlankOrEmpty(atLasts[i])) {
                    atLeast = Double.parseDouble(atLasts[i]);// 保底
                }
                if (!StringUtil.isBlankOrEmpty(screams[i])) {
                    scream = Double.parseDouble(screams[i]);// 尖叫
                }
                if (!StringUtil.isBlankOrEmpty(howls[i])) {
                    howl = Double.parseDouble(howls[i]);// 嚎叫
                }
                //计算得分值存入数组中
                scores[i] = Calculate.InsertionMethod(complete, -1, atLeast, scream, howl, 1);// 计算结果


                performanceDto.setQuarter(q);
                performanceDto.setElementId(subElementId);
                performanceDto.setScore(Float.parseFloat(scores[i])); //综合收缴率细项得分
                performanceDto.setComplete((float) complete);//插入实际值：就是完成值
                performanceDto.setThreshold(String.valueOf(threshold));  //门槛值
                performanceDto.setAt_Least(String.valueOf(atLeast));
                performanceDto.setScream(String.valueOf(scream));
                performanceDto.setHowl(String.valueOf(howl));
                performanceRecordService.performanceRecord(performanceDto);
            }

            double HY_score = Double.valueOf(scores[0]);
            double AL_score = Double.valueOf(scores[1]);
            double HYC_score = Double.valueOf(scores[2]);
            double ALC_score = Double.valueOf(scores[3]);
            String IndividualScore = "-1";

            principalProfit.setHyScore(String.valueOf(HY_score));
            principalProfit.setAlScore(String.valueOf(AL_score));
            principalProfit.setHycScore(String.valueOf(HYC_score));
            principalProfit.setAlcScore(String.valueOf(ALC_score));

            if (HY_score == -1 && AL_score == -1 && HYC_score == -1 && ALC_score == -1) {
                IndividualScore = "-1";
            } else {
                if (HYC_score == -1 && ALC_score == -1) {  //社区经营不考核
                    if (HY_score != -1) {   //上半年和下半年都有数据
                        HY_score *= 0.3;
                        AL_score *= 0.7;
                        HYC_score = ALC_score = 0.0;
                    } else {        //上半年不考核
                        AL_score *= 1;
                        HY_score = HYC_score = ALC_score = 0.0;
                    }
                } else {            //社区经营考核
                    if (HY_score == -1 && HYC_score == -1) {        //上半年不考核
                        AL_score *= 0.7;
                        ALC_score *= 0.3;
                        HY_score = HYC_score = 0.0;
                    } else {        //上半年考核
                        HY_score *= 0.2;
                        AL_score *= 0.5;
                        HYC_score *= 0.1;
                        ALC_score *= 0.2;
                    }
                }
                IndividualScore = String.valueOf(HY_score + AL_score + HYC_score + ALC_score);
            }

            principalProfit.setIndividualscore(IndividualScore);

            performanceDto.setElementId(elementId);
            performanceDto.setQuarter(quarter);
            performanceDto.setScore(Float.parseFloat(IndividualScore));
            performanceDto.setComplete(-1);
            performanceDto.setThreshold(null);
            performanceDto.setAt_Least(null);
            performanceDto.setScream(null);
            performanceDto.setHowl(null);
            performanceDto.setIsExamine(Short.parseShort(principalProfit.getIsCheck()));
            performanceDto.setWeight(weight);
            performanceRecordService.performanceRecord(performanceDto);
        }
        performanceRecordService.saveQuartlyAverageScoreAndSumScore2(year,quarter);

        PerformanceShowDataDto dataDto = new PerformanceShowDataDto();
        dataDto.setDataList(values);
        //空缺值&空缺地区名称
        List<String> vacanHierachyList = performanceRecordService.getVacancyAreas(elementId,year,quarter,"2");
        dataDto.setNameList(vacanHierachyList);
        int vacancy = vacanHierachyList.size();
        dataDto.setVacancy(vacancy);
        return dataDto;
    }

    @Override
    public void uploadData(long elementId, int year, int quarter, MultipartFile mf, String OperatorId) {

        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile)mf;
        String fileName = commonsMultipartFile.getOriginalFilename();
        if(!fileName.contains("主营税前利润")){
            throw new IllegalArgumentException("文件名不正确!");
        }

        //保存数据
        ea.PrincipalProfitUpload(mf, year, quarter, OperatorId);
        //保存平均分和总分
        this.performanceRecordService.saveQuartlyAverageScoreAndSumScore2(year,quarter);

    }

    @Override
    public Object selectAuthority(long elementId, Map<String, Object> requestMap, HttpServletRequest request) {
        return this.performancePower.getUserPower(String.valueOf(elementId),requestMap,request);
    }
}
