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 CityPropertyArrearServiceImpl<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<CityPropertyArrearsRecoveryRate> returnList = new ArrayList<>();

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

            for(PerformanceArea p : organList){

                CityPropertyArrearsRecoveryRate c = new CityPropertyArrearsRecoveryRate();

                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));

                //S1-S4欠费追缴率
                //start
                for (int j = 1; j < 5; j++){

                    record = performanceRecordService.getRecordSelective(elementId,year,j,hierarchy_id);
                    if(record != null){
                        recordId = record.getRecordId();
                        score = performanceRecordService.getScore(recordId);
                        target = performanceRecordService.getTarget(recordId);
                        if(score != null && target != 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()));//得分
                            }

                            //设置单项指标得分与是否考核
                            if(quarter == j){//判断传入季度
                                c.setIndividualScore(String.valueOf(score.getScore()));
                                String isChecked = String.valueOf(record.getIsExamine());
                                if(StringUtil.isBlankOrEmpty(isChecked)){
                                    isChecked = "0";
                                }
                                c.setIs_check(isChecked.equals("1") ? 1 : 0);
                            }
                        }
                    }
                }
                returnList.add(c);
                //end
            }
            result.setDataList(returnList);
        }
        return result;
    }

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

        String jsonString = JSONObject.toJSONString(values);

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

        double weight = 0;
        for(CityPropertyArrearsRecoveryRate c : list){

            String hierarchyId = c.getHierarchyId();
            String type = performanceAreaService.getSubTypeByHierachyId(hierarchyId);
            switch (type){
                case "单一业主项目":
                    weight = 0.1;
                    break;
                case "多业主第一年":
                    weight = 0.1;
                    break;
                case "多业主第二年":
                    weight = 0.1;
                    break;
            }
            //设置初始值
            double complete = -1;   // 完成值
            double threshold = -1;  // 门槛值
            double atLeast = -1;    // 保底
            double scream = -1;     // 尖叫
            double howl = -1;       // 嚎叫

            //null为占位对象
            String[] thresholds = {null,c.getS1_threshold(), c.getS2_threshold(), c.getS3_threshold(), c.getS4_threshold()};
            String[] atLasts = {null,c.getS1_atLeast(), c.getS2_atLeast(), c.getS3_atLeast(), c.getS4_atLeast()};
            String[] screams = {null,c.getS1_scream(), c.getS2_scream(), c.getS3_scream(), c.getS4_scream()};
            String[] howls = {null,c.getS1_howl(), c.getS2_howl(), c.getS3_howl(), c.getS4_howl()};
            String[] completes = {null,c.getS1_complete(), c.getS2_complete(), c.getS3_complete(), c.getS4_complete()};
            String[] scores = {null,"-1", "-1", "-1", "-1"};

            RecordPerformanceDto performanceDto = new RecordPerformanceDto();
            performanceDto.setHierachyId(hierarchyId);
            performanceDto.setYear(year);
            performanceDto.setElementId(elementId);

            for (int i = 1; i < 5; i++) {//S1-S4

                performanceDto.setQuarter(quarter);

                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.setComplete((float) complete);
                    performanceDto.setThreshold(String.valueOf(atLeast));  //没有门槛值，门槛值跟保底值相等
                    performanceDto.setAt_Least(String.valueOf(atLeast));
                    performanceDto.setScream(String.valueOf(scream));
                    performanceDto.setHowl(String.valueOf(howl));
                    performanceDto.setWeight(weight);
                    performanceRecordService.performanceRecord(performanceDto);
                }
              }
        // 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 = null;

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

        //计算单项指标得分
        IndividualScore = Calculate.getCityPropertyArrearsRecoveryRateScore(S1_score,S2_score,S3_score,S4_score);
        if(StringUtil.isEmpty(IndividualScore)){
            IndividualScore = "-1";
        }

        performanceDto.setQuarter(quarter);
        performanceDto.setScore(Float.parseFloat(IndividualScore));
        performanceDto.setIsExamine((short) c.getIs_check());
        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.CityPropertyArrearsRecoveryRateUpload(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);
    }
}
