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/3
 */
@Service
public class CityPropertyCostServiceImpl<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<CityPropertyCollectionRate> returnList = new ArrayList<>();

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

            long elementId2 = 1017001;//综合收缴率 写死
            long elementId3 = 1017002;//综合已收楼收缴率 写死

            for(PerformanceArea p : organList){

                CityPropertyCollectionRate c = new CityPropertyCollectionRate();

                c.setSecond_organization(p.getHierachyName());//二级组织
                c.setThird_organization(p.getHierachyName());//三级组织

                String hierarchy_id = p.getHierachyId();//城市公司id

                c.setHierarchyId(hierarchy_id);
                c.setYear(String.valueOf(year));
                c.setQuarter(String.valueOf(quarter));

                recordId = performanceRecordService.getRecordId(elementId2,year,quarter,hierarchy_id);
                target = performanceRecordService.getTarget(recordId);
                if(target != null){
                    c.setCompre_threshold(target.getThresholdTarget());
                    c.setCompre_atLeast(target.getAtLeastTarget());
                    c.setCompre_scream(target.getScreamTarget());
                    c.setCompre_howl(target.getHowlTarget());
                }
                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    c.setCompre_complete(String.valueOf(score.getComplete()));//综合收缴率完成值
                    c.setCompre_score(String.valueOf(score.getScore()));//综合收缴率细项得分
                }

                ////综合已收楼收缴率
                //传入的指标id更改
                for (int j = 1; j < 5; j++) {
                    recordId = performanceRecordService.getRecordId(elementId3,year,j,hierarchy_id);
                    target = performanceRecordService.getTarget(recordId);
                    score = performanceRecordService.getScore(recordId);
                    if (target != null && score != null) {
                        if (j == 1) {
                            c.setS1_threshold(target.getThresholdTarget());//插入门槛
                            c.setS1_atLeast(target.getAtLeastTarget());//插入保底
                            c.setS1_scream(target.getScreamTarget());//插入尖叫
                            c.setS1_howl(target.getHowlTarget());//插入嚎叫
                            c.setS1_complete(String.valueOf(score.getComplete())); //完成值
                            c.setS1_score(String.valueOf(score.getScore()));//得分
                        }
                        if (j == 2) {
                            c.setS2_threshold(target.getThresholdTarget());//插入门槛
                            c.setS2_atLeast(target.getAtLeastTarget());//插入保底
                            c.setS2_scream(target.getScreamTarget());//插入尖叫
                            c.setS2_howl(target.getHowlTarget());//插入嚎叫
                            c.setS2_complete(String.valueOf(score.getComplete())); //完成值
                            c.setS2_score(String.valueOf(score.getScore()));//得分
                        }
                        if (j == 3) {
                            c.setS3_threshold(target.getThresholdTarget());//插入门槛
                            c.setS3_atLeast(target.getAtLeastTarget());//插入保底
                            c.setS3_scream(target.getScreamTarget());//插入尖叫
                            c.setS3_howl(target.getHowlTarget());//插入嚎叫
                            c.setS3_complete(String.valueOf(score.getComplete())); //完成值
                            c.setS3_score(String.valueOf(score.getScore()));//得分
                        }
                        if (j == 4) {
                            c.setS4_threshold(target.getThresholdTarget());//插入门槛
                            c.setS4_atLeast(target.getAtLeastTarget());//插入保底
                            c.setS4_scream(target.getScreamTarget());//插入尖叫
                            c.setS4_howl(target.getHowlTarget());//插入嚎叫
                            c.setS4_complete(String.valueOf(score.getComplete())); //完成值
                            c.setS4_score(String.valueOf(score.getScore()));//得分
                        }
                    }
                }


                record = performanceRecordService.getRecordSelective(elementId,year,quarter,hierarchy_id);
                if (record != null) {
                    c.setIs_check(record.getIsExamine() == 1 ? 1 : 0);

                    //////////////查询单项指标得分
                    recordId = performanceRecordService.getRecordId(elementId,year,quarter,hierarchy_id);
                    score = performanceRecordService.getScore(recordId);
                    if(score != null){
                        c.setIndividualScore(String.valueOf(score.getScore()));
                    }

                } else {
                    c.setIs_check(1);
                }
                returnList.add(c);
            }
            result.setDataList(returnList);
        }
            return result;
    }

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

        String jsonString = JSONObject.toJSONString(values);

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

        long elementId2 = 1017001L;//综合收缴率
        long elementId3 = 1017002L;//综合已收楼收缴率

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

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

            String[] thresholds = {c.getCompre_threshold(), c.getS1_threshold(), c.getS2_threshold(), c.getS3_threshold(), c.getS4_threshold()};
            String[] atLasts = {c.getCompre_atLeast(), c.getS1_atLeast(), c.getS2_atLeast(), c.getS3_atLeast(), c.getS4_atLeast()};
            String[] screams = {c.getCompre_scream(), c.getS1_scream(), c.getS2_scream(), c.getS3_scream(), c.getS4_scream()};
            String[] howls = {c.getCompre_howl(), c.getS1_howl(), c.getS2_howl(), c.getS3_howl(), c.getS4_howl()};
            String[] completes = {c.getCompre_complete(), c.getS1_complete(), c.getS2_complete(), c.getS3_complete(), c.getS4_complete()};
            String[] scores = {"-1", "-1", "-1", "-1", "-1"};

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

            label:
            for(int i = 0; i < 5; i++){ //综合、S1-S4

                switch (i) {
                    case 0: {           //综合
                        performanceDto.setElementId(elementId2);
                        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(StringUtil.isBlankOrEmpty(atLasts[i]) ? "-1" : atLasts[i]);       //  保底
                        scream = Double.parseDouble(StringUtil.isBlankOrEmpty(screams[i]) ? "-1" : screams[i]);        // :尖叫
                        howl = Double.parseDouble(StringUtil.isBlankOrEmpty(howls[i]) ? "-1" : 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.setComplete((float) complete);//插入实际值：就是完成值
                    performanceDto.setScore(Float.parseFloat(scores[i]));//综合收缴率细项得分
                    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];
            // S1综合已收楼缴率:细项目得分
            String S1_score = scores[1];
            // S2综合已收楼缴率:细项目得分
            String S2_score = scores[2];
            // S3综合已收楼缴率:细项目得分
            String S3_score = scores[3];
            // S4综合已收楼缴率:细项目得分
            String S4_score = scores[4];
            String IndividualScore = "-1";//指标总得分

            c.setCompre_score(ZH_score);
            c.setS1_score(S1_score);
            c.setS2_score(S2_score);
            c.setS3_score(S3_score);
            c.setS4_score(S4_score);

            //////////计算指标单项得分
            IndividualScore = Calculate.getCityCostIndividualScore(ZH_score,S1_score,S2_score,S3_score,S4_score);

            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) c.getIs_check());
            performanceDto.setWeight(weight);
            performanceRecordService.performanceRecord(performanceDto);

            c.setIndividualScore(IndividualScore);
        }
        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.CityPropertyCollectionRateUpload(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);
    }
}
