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 com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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/10/22
 */
@Service
public class GetArrearsPropertyCostsServiceImpl<T> extends AbstractIndicatorService<T> {

    Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @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<GetArrearsPropertyCosts> returnList = new ArrayList<>();

            PerformanceTarget target;
            PerformanceScore score;
            PerformanceRecord record;
            long recordId;

            for(PerformanceArea p : organList){

                GetArrearsPropertyCosts propertyCosts = new GetArrearsPropertyCosts();

                //S1-S4
                //[start]
                String hierarchyId = p.getHierachyId();
                propertyCosts.setThird_organization(p.getHierachyName());
                propertyCosts.setSecond_organization(p.getHierachyName());
                propertyCosts.setHierarchyId(hierarchyId);
                propertyCosts.setQuarter(String.valueOf(quarter));//设置季度值

                for (int j = 1; j < 5; j++) {

                    recordId = performanceRecordService.getRecordId(elementId,year,j,hierarchyId);
                    score = performanceRecordService.getScore(recordId);
                    target = performanceRecordService.getTarget(recordId);

                    if (target != null && score != null) {

                        if (j == 1) {
                            propertyCosts.setS1_threshold(target.getThresholdTarget());//门槛
                            propertyCosts.setS1_atLeast(target.getAtLeastTarget());//低保
                            propertyCosts.setS1_scream(target.getScreamTarget());//尖叫
                            propertyCosts.setS1_howl((target.getHowlTarget()));//嚎叫

                            propertyCosts.setS1_Complete_Value(String.valueOf(score.getComplete()));//插入完成值
                            propertyCosts.setS1_score(String.valueOf(score.getYearlyScore()));//插入细项得分
                        }
                        if (j == 2) {
                            propertyCosts.setS2_threshold(target.getThresholdTarget());//门槛
                            propertyCosts.setS2_atLeast(target.getAtLeastTarget());//低保
                            propertyCosts.setS2_scream(target.getScreamTarget());//尖叫
                            propertyCosts.setS2_howl((target.getHowlTarget()));//嚎叫

                            propertyCosts.setS2_Complete_Value(String.valueOf(score.getComplete()));//插入完成值
                            propertyCosts.setS2_score(String.valueOf(score.getYearlyScore()));//插入细项得分
                        }
                        if (j == 3) {
                            propertyCosts.setS3_threshold(target.getThresholdTarget());//门槛
                            propertyCosts.setS3_atLeast(target.getAtLeastTarget());//低保
                            propertyCosts.setS3_scream(target.getScreamTarget());//尖叫
                            propertyCosts.setS3_howl((target.getHowlTarget()));//嚎叫

                            propertyCosts.setS3_Complete_Value(String.valueOf(score.getComplete()));//插入完成值
                            propertyCosts.setS3_score(String.valueOf(score.getYearlyScore()));//插入细项得分
                        }
                        if (j == 4) {
                            propertyCosts.setS4_threshold(target.getThresholdTarget());//门槛
                            propertyCosts.setS4_atLeast(target.getAtLeastTarget());//低保
                            propertyCosts.setS4_scream(target.getScreamTarget());//尖叫
                            propertyCosts.setS4_howl((target.getHowlTarget()));//嚎叫

                            propertyCosts.setS4_Complete_Value(String.valueOf(score.getComplete()));//插入完成值
                            propertyCosts.setS4_score(String.valueOf(score.getYearlyScore()));//插入细项得分
                        }

                    }
                }
                //[end]

                //查出单项细数得分
                record = performanceRecordService.getRecordSelective(elementId,year,quarter,hierarchyId);
                if(record != null) {
                    //是否考核,1表示考核，0表示不考核
                    if (record.getIsExamine() == 1) {
                        propertyCosts.setIs_check(1);
                    } else {
                        propertyCosts.setIs_check(0);
                    }
                    recordId = record.getRecordId();
                    score = performanceRecordService.getScore(recordId);
                    if(score != null){
                        propertyCosts.setIndividualScore(String.valueOf(score.getScore()));//单项系数得分
                    }
                }else{
                    propertyCosts.setIs_check(1);
                }
                propertyCosts.setYear(String.valueOf(year));
                returnList.add(propertyCosts);
            }
            result.setDataList(returnList);
        }
            return result;
    }

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

        String jsonString = JSONObject.toJSONString(values);

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

        RecordPerformanceDto performanceDto = new RecordPerformanceDto();

        //S1欠费追缴率
        double S1_Complete_Value = -1;          //S1欠费追缴率:完成值
        double S1_threshold;  // S1欠费追缴率:门槛值
        double S1_atLeast;    // S1欠费追缴率:保底
        double S1_scream;     // S1欠费追缴率:尖叫
        double S1_howl;       // S1欠费追缴率:嚎叫


        //S2欠费追缴率
        double S2_Complete_Value = -1;          //S2欠费追缴率:完成值
        double S2_threshold = -1;  // S2欠费追缴率:门槛值
        double S2_atLeast;    // S2欠费追缴率:保底
        double S2_scream;     // S2欠费追缴率:尖叫
        double S2_howl;       // S2欠费追缴率:嚎叫


        //S3欠费追缴率
        double S3_Complete_Value = -1;          //S3欠费追缴率:完成值
        double S3_threshold = -1;  // S3欠费追缴率:门槛值
        double S3_atLeast;    // S3欠费追缴率:保底
        double S3_scream;     // S3欠费追缴率:尖叫
        double S3_howl;       // S3欠费追缴率:嚎叫


        //S4欠费追缴率
        double S4_Complete_Value = -1;          //S4综合已收缴率完成值
        double S4_threshold = -1;  // S4综合已收缴率:门槛值
        double S4_atLeast;    // S4综合已收缴率:保底
        double S4_scream;     // S4综合已收缴率:尖叫
        double S4_howl;       // S4综合已收缴率:嚎叫

        for (GetArrearsPropertyCosts costs : list) {

                String hierachyId = costs.getHierarchyId();

                String S1_score = costs.getS1_score() == null ? "0" : costs.getS1_score();      // S1欠费追缴率:细项目得分
                String S2_score = costs.getS2_score() == null ? "0" : costs.getS2_score();      // S2欠费追缴率:细项目得分
                String S3_score = costs.getS3_score() == null ? "0" : costs.getS3_score();      // S3欠费追缴率:细项目得分
                String S4_score = costs.getS4_score() == null ? "0" : costs.getS4_score();      // S4综合已收缴率:细项目得分

                //因为计算必须要完成值所以就判断完成值是否为空
                //////////////////////////算出S1的细项得分
                if (costs.getQuarter().equals("1")) {
                    if (costs.getS1_Complete_Value() != null && !costs.getS1_Complete_Value().equals("")) {
                        try {
                            S1_Complete_Value = Double.parseDouble(costs.getS1_Complete_Value());
                            S1_threshold = Double.parseDouble(costs.getS1_threshold());
                            S1_atLeast = Double.parseDouble(costs.getS1_atLeast());
                            S1_scream = Double.parseDouble(costs.getS1_scream());
                            S1_howl = Double.parseDouble(costs.getS1_howl());
                        } catch (NumberFormatException e) {
                            S1_threshold = S1_atLeast = S1_scream = S1_howl = -1;
                        }
                        if (S1_Complete_Value != -1) {
                            S1_score = Calculate.InsertionMethod(S1_Complete_Value, -1, S1_atLeast, S1_scream, S1_howl, 1);// 计算出细项目得分综合收费
                            costs.setS1_score(S1_score);
                        } else {
                            S1_score = "-1";
                        }
                        //以下插入计算结果，先查询是否存在同样数据是的update，否则insert
                        //S1
                        performanceDto.setHierachyId(hierachyId);
                        performanceDto.setElementId(elementId);
                        performanceDto.setYear(year);
                        performanceDto.setQuarter(quarter);
                        performanceDto.setScore(Float.parseFloat(S1_score));
                        performanceDto.setComplete((float) S1_Complete_Value);
                        performanceDto.setYearly_score(Float.parseFloat(S1_score));
                        performanceDto.setThreshold(String.valueOf(S1_threshold));
                        performanceDto.setAt_Least(String.valueOf(S1_atLeast));
                        performanceDto.setScream(String.valueOf(S1_scream));
                        performanceDto.setHowl(String.valueOf(S1_howl));
                        performanceRecordService.performanceRecord(performanceDto);
                    }
                }

                    /////////////////////算出S2的细项得分
                    if (costs.getQuarter().equals("2")) {
                        if (costs.getS2_Complete_Value() != null && !costs.getS2_Complete_Value().equals("")) {
                            S2_Complete_Value = Double.parseDouble(costs.getS2_Complete_Value());
                            if (costs.getS2_threshold() != null && !costs.getS2_threshold().equals("")) {
                                S2_threshold = Double.parseDouble(costs.getS2_threshold());
                            }
                            S2_atLeast = Double.parseDouble(costs.getS2_atLeast());
                            S2_scream = Double.parseDouble(costs.getS2_scream());
                            S2_howl = Double.parseDouble(costs.getS2_howl());
                            Calculate.InsertionMethod(S2_Complete_Value, -1, S2_atLeast, S2_scream, S2_howl, 1);
                            if (S2_Complete_Value != -1) {
                                S2_score = Calculate.InsertionMethod(S2_Complete_Value, -1, S2_atLeast, S2_scream, S2_howl, 1);// 计算出细项目得分综合收费
                                costs.setS2_score(S2_score);
                            } else {
                                S2_score = "-1";
                            }
                            //以下插入计算结果，先查询是否存在同样数据是的update，否则insert
                            performanceDto.setHierachyId(hierachyId);
                            performanceDto.setElementId(elementId);
                            performanceDto.setYear(year);
                            performanceDto.setQuarter(quarter);
                            performanceDto.setScore( Float.parseFloat(S2_score));
                            performanceDto.setComplete((float) S2_Complete_Value);
                            performanceDto.setYearly_score( Float.parseFloat(S2_score));
                            performanceDto.setThreshold(String.valueOf(S2_threshold));
                            performanceDto.setAt_Least(String.valueOf(S2_atLeast));
                            performanceDto.setScream(String.valueOf(S2_scream));
                            performanceDto.setHowl(String.valueOf(S2_howl));
                            performanceRecordService.performanceRecord(performanceDto);
                        }
                    }

                    ///////////////////////算出s3
                    if (costs.getQuarter().equals("3")) {
                        if (costs.getS3_Complete_Value() != null && !costs.getS3_Complete_Value().equals("")) {
                            S3_Complete_Value = Double.parseDouble(costs.getS3_Complete_Value());
                            if (costs.getS3_threshold() != null && !costs.getS3_threshold().equals("")) {
                                S3_threshold = Double.parseDouble(costs.getS3_threshold());
                            }
                            S3_atLeast = Double.parseDouble(costs.getS3_atLeast());
                            S3_scream = Double.parseDouble(costs.getS3_scream());
                            S3_howl = Double.parseDouble(costs.getS3_howl());
                            Calculate.InsertionMethod(S3_Complete_Value, -1, S3_atLeast, S3_scream, S3_howl, 1);
                            if (S3_Complete_Value != -1) {
                                S3_score = Calculate.InsertionMethod(S3_Complete_Value, -1, S3_atLeast, S3_scream, S3_howl, 1);// 计算出细项目得分综合收费
                                costs.setS3_score(S3_score);
                            } else {
                                S3_score = "-1";
                            }

                            //以下插入计算结果，先查询是否存在同样数据是的update，否则insert
                            performanceDto.setHierachyId(hierachyId);
                            performanceDto.setElementId(elementId);
                            performanceDto.setYear(year);
                            performanceDto.setQuarter(quarter);
                            performanceDto.setScore( Float.parseFloat(S3_score));
                            performanceDto.setComplete((float) S3_Complete_Value);
                            performanceDto.setYearly_score( Float.parseFloat(S3_score));
                            performanceDto.setThreshold(String.valueOf(S3_threshold));
                            performanceDto.setAt_Least(String.valueOf(S3_atLeast));
                            performanceDto.setScream(String.valueOf(S3_scream));
                            performanceDto.setHowl(String.valueOf(S3_howl));
                            performanceRecordService.performanceRecord(performanceDto);
                        }
                    }

                    ////////////////算出s4
                    if (costs.getQuarter().equals("4")) {
                        if (costs.getS4_Complete_Value() != null && !costs.getS4_Complete_Value().equals("")) {
                            S4_Complete_Value = Double.parseDouble(costs.getS4_Complete_Value());
                            if (costs.getS4_threshold() != null && !costs.getS4_threshold().equals("")) {
                                S4_threshold = Double.parseDouble(costs.getS4_threshold());
                            }
                            S4_atLeast = Double.parseDouble(costs.getS4_atLeast());
                            S4_scream = Double.parseDouble(costs.getS4_scream());
                            S4_howl = Double.parseDouble(costs.getS4_howl());
                            Calculate.InsertionMethod(S4_Complete_Value, -1, S4_atLeast, S4_scream, S4_howl, 1);
                            if (S4_Complete_Value != -1) {
                                S4_score = Calculate.InsertionMethod(S4_Complete_Value, -1, S4_atLeast, S4_scream, S4_howl, 1);// 计算出细项目得分综合收费
                                costs.setS4_score(S4_score);
                            } else {
                                S4_score = "-1";
                            }

                            //以下插入计算结果，先查询是否存在同样数据是的update，否则insert
                            performanceDto.setHierachyId(hierachyId);
                            performanceDto.setElementId(elementId);
                            performanceDto.setYear(year);
                            performanceDto.setQuarter(quarter);
                            performanceDto.setScore( Float.parseFloat(S4_score));
                            performanceDto.setComplete((float) S4_Complete_Value);
                            performanceDto.setYearly_score( Float.parseFloat(S4_score));
                            performanceDto.setThreshold(String.valueOf(S4_threshold));
                            performanceDto.setAt_Least(String.valueOf(S4_atLeast));
                            performanceDto.setScream(String.valueOf(S4_scream));
                            performanceDto.setHowl(String.valueOf(S4_howl));
                            performanceRecordService.performanceRecord(performanceDto);
                            /////入库
                        }
                    }
                    //计算
                    String IndividualScore = null;
                    //IndividualScore = Calculate.CalnewS_Score(S1_score, S2_score, S3_score, S4_score);
                    //根据不同的季度来选择不同的计算方式
                    if (costs.getQuarter().equals("1")) {
                        IndividualScore = S1_score;
                    } else if (costs.getQuarter().equals("2")) {
                        try {
                            double s1_temp = Double.parseDouble(S1_score);
                            double s2_temp = Double.parseDouble(S2_score);
                            IndividualScore = String.valueOf((s1_temp * 0.1 + s2_temp * 0.1) / 0.2);
                        } catch (NumberFormatException e) {
                            LOGGER.error("======GetArrearsPropertyCostsController.ArrearsPropertyCostsCal=====quarter：2，individualScore error");
                        }
                    } else if (costs.getQuarter().equals("3")) {
                        try {
                            double s1_temp = Double.parseDouble(S1_score);
                            double s2_temp = Double.parseDouble(S2_score);
                            double s3_temp = Double.parseDouble(S3_score);
                            IndividualScore = String.valueOf((s1_temp * 0.1 + s2_temp * 0.1 + s3_temp * 0.1) / 0.3);
                        } catch (NumberFormatException e) {
                            LOGGER.error("======GetArrearsPropertyCostsController.ArrearsPropertyCostsCal=====quarter：3，individualScore error");
                        }
                    } else if (costs.getQuarter().equals("4")) {
                        try {
                            double s1_temp = Double.parseDouble(S1_score);
                            double s2_temp = Double.parseDouble(S2_score);
                            double s3_temp = Double.parseDouble(S3_score);
                            double s4_temp = Double.parseDouble(S4_score);
                            IndividualScore = String.valueOf(s1_temp * 0.1 + s2_temp * 0.1
                                    + s3_temp * 0.1 + s4_temp * 0.7);
                        } catch (NumberFormatException e) {
                            LOGGER.error("======GetArrearsPropertyCostsController.ArrearsPropertyCostsCal=====quarter：4，individualScore error");
                        }
                    }
                    if (costs.getIs_check() == 0) {
                        IndividualScore = "-1";
                    }

                    if (IndividualScore != null) {
                        costs.setIndividualScore(IndividualScore);
                    }

                    //以下插入计算结果，先查询是否存在同样数据是的update，否则insert
                    performanceDto.setHierachyId(hierachyId);
                    performanceDto.setElementId(elementId);
                    performanceDto.setYear(year);
                    performanceDto.setQuarter(quarter);
                    performanceDto.setRate("季度、年度");
                    performanceDto.setWeight(0.05);
                    performanceDto.setIsExamine((short) costs.getIs_check());
                    performanceDto.setScore(Float.parseFloat(IndividualScore));
                    performanceRecordService.performanceRecord(performanceDto);

            }

            performanceRecordService.saveQuartlyAverageScoreAndSumScore2(year, quarter);

            PerformanceShowDataDto dataDto = new PerformanceShowDataDto();
            dataDto.setDataList(values);
            //空缺值&空缺地区名称
            List<String> vacanHierachyList = performanceRecordService.getVacancyAreas(elementId, year, quarter, "1");
            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.GetArrearsPropertyCostsUploadUpload(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);
    }
}
