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.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/11/2
 */

@Service
public class GetPropertyCostsServiceImpl<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) {

            long elementId2 = 1003001;//综合收缴率 写死
            long elementId3 = 1003002;//综合已收楼收缴率
            long elementId4 = 1003003;//已收楼收缴率(外拓)id 写死

            List<GetPropertyCosts> returnList = new ArrayList<>();
            PerformanceTarget target;
            PerformanceScore score;
            PerformanceRecord record;
            long recordId;

            for(PerformanceArea p : organList){
                GetPropertyCosts g = new GetPropertyCosts();//bean
                ////////////下面设置区域的 中文名
                String hierarchyId = p.getHierachyId();
                g.setHierarchyId(hierarchyId);
                g.setThird_organization(p.getHierachyName());//插入区域名字
                g.setSecond_organization(p.getHierachyName());//插入区域名字
                g.setYear(String.valueOf(year));
                g.setQuarter(String.valueOf(quarter));

                //综合收缴率
                recordId = performanceRecordService.getRecordId(elementId2,year,quarter,hierarchyId);
                target = performanceRecordService.getTarget(recordId);
                if(target != null){
                    g.setThreshold(target.getThresholdTarget());//bean插入门槛
                    g.setAtLeast(target.getAtLeastTarget());//bean插入低保
                    g.setScream(target.getScreamTarget());//bean插入尖叫
                    g.setHowl((target.getHowlTarget()));//bean插入嚎叫
                }

                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    g.setComplete_Value(String.valueOf(score.getComplete()));//完成值插入
                    g.setScore(String.valueOf(score.getScore()));//细项得分
                }
                ////////////////////////////////////综合满意率数据填好
                //以下是综合已收楼收缴率

                //S1-S4综合收缴率
                for (int j = 1; j < 5; j++) {
                    recordId = performanceRecordService.getRecordId(elementId3,year,j,hierarchyId);
                    target = performanceRecordService.getTarget(recordId);
                    score = performanceRecordService.getScore(recordId);

                    if (target != null && score != null) {
                        if (j == 1) {
                            g.setS1_threshold(target.getThresholdTarget());//插入门槛
                            g.setS1_atLeast(target.getAtLeastTarget());//插入低保
                            g.setS1_scream(target.getScreamTarget());//插入尖叫
                            g.setS1_howl(target.getHowlTarget());//插入嚎叫
                            g.setS1_Complete_Value(String.valueOf(score.getComplete())); //完成值
                            g.setS1_score(String.valueOf(score.getScore()));//得分
                        }
                        if (j == 2) {
                            g.setS2_threshold(target.getThresholdTarget());//插入门槛
                            g.setS2_atLeast(target.getAtLeastTarget());//插入低保
                            g.setS2_scream(target.getScreamTarget());//插入尖叫
                            g.setS2_howl(target.getHowlTarget());//插入嚎叫
                            g.setS2_Complete_Value(String.valueOf(score.getComplete())); //完成值
                            g.setS2_score(String.valueOf(score.getScore()));//得分
                        }
                        if (j == 3) {
                            g.setS3_threshold(target.getThresholdTarget());//插入门槛
                            g.setS3_atLeast(target.getAtLeastTarget());//插入低保
                            g.setS3_scream(target.getScreamTarget());//插入尖叫
                            g.setS3_howl(target.getHowlTarget());//插入嚎叫
                            g.setS3_Complete_Value(String.valueOf(score.getComplete())); //完成值
                            g.setS3_score(String.valueOf(score.getScore()));//得分
                        }
                        if (j == 4) {
                            g.setS4_threshold(target.getThresholdTarget());//插入门槛
                            g.setS4_atLeast(target.getAtLeastTarget());//插入低保
                            g.setS4_scream(target.getScreamTarget());//插入尖叫
                            g.setS4_howl(target.getHowlTarget());//插入嚎叫
                            g.setS4_Complete_Value(String.valueOf(score.getComplete())); //完成值
                            g.setS4_score(String.valueOf(score.getScore()));//得分
                        }
                    }
                }

                //修改外拓年度半年度展示  12季度展示到半年度，年度部分为空；34季度展示到年度，半年度部分展示2季度数据
                if (quarter <= 2) {
                    //查询半年度的数据  外拓
                    recordId = performanceRecordService.getRecordId(elementId4,year,quarter,hierarchyId);
                    score = performanceRecordService.getScore(recordId);//查询这个区域的得分
                    target = performanceRecordService.getTarget(recordId);
                    if (target != null) {
                        g.setHY_threshold(target.getThresholdTarget());//门槛
                        g.setHY_atLeast(target.getAtLeastTarget());//保底
                        g.setHY_scream(target.getScreamTarget());//尖叫
                        g.setHY_howl(target.getHowlTarget());//傲叫

                        g.setAL_threshold(target.getThresholdTarget());//门槛
                        g.setAL_atLeast(target.getAtLeastTarget());//保底
                        g.setAL_scream(target.getScreamTarget());//尖叫
                        g.setAL_howl(target.getHowlTarget());//傲叫
                    }
                    //给半年的入分
                    if (score != null) {
                        g.setHY_Complete_Value(String.valueOf(score.getComplete()));
                        g.setHY_score(String.valueOf(score.getScore()));

                        g.setAL_Complete_Value(String.valueOf(score.getComplete()));
                        g.setAL_score(String.valueOf(score.getScore()));
                    }
                } else {
                    //查询半年度的数据  外拓
                    recordId = performanceRecordService.getRecordId(elementId4,year,2,hierarchyId);
                    score = performanceRecordService.getScore(recordId);//查询这个区域的得分
                    target = performanceRecordService.getTarget(recordId);
                    if (target != null) {
                        g.setHY_threshold(target.getThresholdTarget());//门槛
                        g.setHY_atLeast(target.getAtLeastTarget());//保底
                        g.setHY_scream(target.getScreamTarget());//尖叫
                        g.setHY_howl(target.getHowlTarget());//傲叫
                    }
                    //给半年的入分
                    if (score != null) {
                        g.setHY_Complete_Value(String.valueOf(score.getComplete()));
                        g.setHY_score(String.valueOf(score.getScore()));
                    }


                    //年度外拓收缴率
                    recordId = performanceRecordService.getRecordId(elementId4,year,quarter,hierarchyId);
                    score = performanceRecordService.getScore(recordId);//查询这个区域的得分
                    target = performanceRecordService.getTarget(recordId);
                    if (target != null) {
                        g.setAL_threshold(target.getThresholdTarget());//门槛
                        g.setAL_atLeast(target.getAtLeastTarget());//保底
                        g.setAL_scream(target.getScreamTarget());//尖叫
                        g.setAL_howl(target.getHowlTarget());//傲叫
                    }

                    if (score != null) {
                        g.setAL_Complete_Value(String.valueOf(score.getComplete()));
                        g.setAL_score(String.valueOf(score.getScore()));
                    }
                }
                //[end]

                //////////////查询单项指标得分
                record = performanceRecordService.getRecordSelective(elementId,year,quarter,hierarchyId);
                //////////////////是否考核
                if(record == null){
                    g.setIs_check(1);
                }else{
                    g.setIs_check(record.getIsExamine());
                    recordId = record.getRecordId();
                    score = performanceRecordService.getScore(recordId);
                    if (score != null) {
                        g.setIndividualScore(String.valueOf(score.getScore()));
                    }
                }

                returnList.add(g);
            }
            result.setDataList(returnList);
        }
            return result;
    }

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

        long elementId2 = 1003001;//综合收缴率 写死
        long elementId3 = 1003002;//综合已收楼收缴率
        long elementId4 = 1003003;//已收楼收缴率(外拓)id 写死

        String jsonString = JSONObject.toJSONString(values);

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

        for(GetPropertyCosts propertyCost : list){

            RecordPerformanceDto performanceDto = new RecordPerformanceDto();

            String hierarchyId = propertyCost.getHierarchyId();

            performanceDto.setYear(year);
            performanceDto.setHierachyId(hierarchyId);
            performanceDto.setWeight(0.1);
            performanceDto.setIsExamine((short)propertyCost.getIs_check());

            //综合收缴率
            double complete = -1;   // 完成值
            double threshold = -1;  // 门槛值
            double atLeast = -1;    // 保底
            double scream = -1;     // 尖叫
            double howl = -1;       // 嚎叫

            String[] thresholds = {propertyCost.getThreshold(), propertyCost.getS1_threshold(), propertyCost.getS2_threshold(), propertyCost.getS3_threshold(), propertyCost.getS4_threshold(), propertyCost.getHY_threshold(), propertyCost.getAL_threshold()};
            String[] atLasts = {propertyCost.getAtLeast(), propertyCost.getS1_atLeast(), propertyCost.getS2_atLeast(), propertyCost.getS3_atLeast(), propertyCost.getS4_atLeast(), propertyCost.getHY_atLeast(), propertyCost.getAL_atLeast()};
            String[] screams = {propertyCost.getScream(), propertyCost.getS1_scream(), propertyCost.getS2_scream(), propertyCost.getS3_scream(), propertyCost.getS4_scream(), propertyCost.getHY_scream(), propertyCost.getAL_scream()};
            String[] howls = {propertyCost.getHowl(), propertyCost.getS1_howl(), propertyCost.getS2_howl(), propertyCost.getS3_howl(), propertyCost.getS4_howl(), propertyCost.getHY_howl(), propertyCost.getAL_howl()};
            String[] completes = {propertyCost.getComplete_Value(), propertyCost.getS1_Complete_Value(), propertyCost.getS2_Complete_Value(), propertyCost.getS3_Complete_Value(), propertyCost.getS4_Complete_Value(), propertyCost.getHY_Complete_Value(), propertyCost.getAL_Complete_Value()};
            String[] scores = {"-1", "-1", "-1", "-1", "-1", "-1", "-1"};

            //用来从switch中跳出循环的标记,java goto不能用 = =,
            label:
            for (int i = 0; i < 7; i++) {       //综合、S1-S4、两个外拓 一共7个,除了指标编号、季度有区别，其他的没啥区别

                switch (i) {
                    case 0: {           //综合
                        performanceDto.setElementId(elementId2);
                        performanceDto.setQuarter(quarter);
                        break;
                    }
                      /*
                    这个外拓收入的处理逻辑是这样的:
                    1、2季度的，更新到半年度的地方，也就是element_id = 1003003  quarter = 1 or 2;
                    1、2、3、4季度的更新到年度的地方                    */
                    case 5: {           //外拓半年
                        String q = String.valueOf(quarter);
                        if (quarter > 2) {
                            q = "2";
                        }
                        performanceDto.setElementId(elementId4);
                        performanceDto.setQuarter(Integer.parseInt(q));
                        break;
                    }
                    case 6: {           //外拓年度
                        performanceDto.setElementId(elementId4);
                        performanceDto.setQuarter(quarter);
                        break;
                    }
                    default: {          //S1-S4
                        performanceDto.setElementId(elementId3);
                        performanceDto.setQuarter(i);
                        break;
                    }
                }

                if (!StringUtil.isBlankOrEmpty(completes[i])) {
                    try {
                        complete = Double.parseDouble(completes[i]);    // 完成值
                        atLeast = Double.parseDouble(atLasts[i]);       //  保底
                        scream = Double.parseDouble(screams[i]);        // :尖叫
                        howl = Double.parseDouble(howls[i]);            // :嚎叫
                    } catch (NumberFormatException e) {
                        //输入数据有误 直接return error不合适，计算成0值返回，各目标值初始化为-1
                        LOGGER.error("目标值输入有误：{},{},{},{}", completes[i], atLasts[i], screams[i], howls[i]);
                    }

                    // 计算出细项目得分综合收费，放入数组中，不设置门槛值
                    scores[i] = Calculate.InsertionMethod(complete, -1, atLeast, scream, howl, 1);

                    //插入计算的数据，和实际值
                    performanceDto.setScore(Float.parseFloat(scores[i]));
                    performanceDto.setComplete((float)complete);
                    performanceDto.setThreshold(String.valueOf(atLeast));
                    performanceDto.setAt_Least(String.valueOf(atLeast));
                    performanceDto.setScream(String.valueOf(scream));
                    performanceDto.setHowl(String.valueOf(howl));
                    performanceRecordService.performanceRecord(performanceDto);
                }
            }
            String ZH_score = scores[0];
            //综合收缴率:细项目得分
            String S1_score = scores[1];
            // S1综合已收楼缴率:细项目得分
            String S2_score = scores[2];
            // S2综合已收楼缴率:细项目得分
            String S3_score = scores[3];
            // S3综合已收楼缴率:细项目得分
            String S4_score = scores[4];
            // S4综合已收楼缴率:细项目得分
            String HY_score = scores[5];
            // 上半年外拓已收楼收缴率:细项目得分
            String AL_score = scores[6];
            // 年度外拓已收楼收缴率:细项目得分
            String WT_score = "-1";     //外拓按权重算完的总得分
            String S_score = "-1";      //季度总按权重算完的总得分
            String IndividualScore = "-1";     //指标总得分


            propertyCost.setScore(ZH_score);
            propertyCost.setS1_score(S1_score);
            propertyCost.setS2_score(S2_score);
            propertyCost.setS3_score(S3_score);
            propertyCost.setS4_score(S4_score);
            propertyCost.setHY_score(HY_score);
            propertyCost.setAL_score(AL_score);

            if ("-1".equals(AL_score) && "-1".equals(HY_score)) {
                WT_score = "-1";
            } else {
                //年度有数据，半年度 * 5% + 年度 * 10%; 只有半年度数据，半年度 * 15%;只有年度数据，年度 15%
                HY_score = String.format("%.2f", "-1".equals(AL_score) ? Double.parseDouble(HY_score) * 0.15 : Double.parseDouble(HY_score) * 0.05);
                AL_score = String.format("%.2f", "-1".equals(HY_score) ? Double.parseDouble(AL_score) * 0.15 : Double.parseDouble(AL_score) * 0.10);
                WT_score = String.format("%.2f", Double.parseDouble(AL_score) + Double.parseDouble(HY_score));
            }


            //////////////根据权重计算年度（外拓值）
            ////////计算指标单项得分
            IndividualScore = Calculate.getCostIndividualScore(ZH_score, S1_score, S2_score, S3_score, S4_score, WT_score);

            //以下插入计算结果，先查询是否存在同样数据是的update，否则insert
            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);
            performanceRecordService.performanceRecord(performanceDto);

            //回传计算后的值
            propertyCost.setIndividualScore(IndividualScore);
        }
        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.GetPropertyCostsUpload(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);
    }
}
