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 PretaxprofitServiceImpl<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<ProfitBeforeTax> returnList = new ArrayList<>();

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

            long elementId2 = 1005001L;
            long elementId3 = 1005002L;

            for(PerformanceArea p : organList){

                ProfitBeforeTax profitBeforeTax = new ProfitBeforeTax();// 税前利润实体bean
                String hierarchyId = p.getHierachyId();

                profitBeforeTax.setSecond_organization(p.getHierachyName());// 项目区域
                profitBeforeTax.setThird_organization(p.getHierachyName());// 项目区域
                profitBeforeTax.setHierarchyId(hierarchyId);
                profitBeforeTax.setYear(String.valueOf(year));
                profitBeforeTax.setQuarter(String.valueOf(quarter));

                int quarterly;
                //上半年 综合利润 HY
                if (quarter > 2) {
                    quarterly = 2;
                }else{
                    quarterly = quarter;
                }
                recordId = performanceRecordService.getRecordId(elementId2,year,quarterly,hierarchyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    profitBeforeTax.setHY_Complete_Value(String.valueOf(score.getComplete()));
                    profitBeforeTax.setHY_score(String.valueOf(score.getScore()));
                }

                recordId = performanceRecordService.getRecordId(elementId3,year,quarterly,hierarchyId);
                target = performanceRecordService.getTarget(recordId);
                if(target != null){
                    profitBeforeTax.setHY_threshold(target.getThresholdTarget());
                    profitBeforeTax.setHY_atLeast(target.getAtLeastTarget());
                    profitBeforeTax.setHY_scream(target.getScreamTarget());
                    profitBeforeTax.setHY_howl(target.getHowlTarget());
                }

                // 上半年 税前利润 HYC
                recordId = performanceRecordService.getRecordId(elementId3,year,quarterly,hierarchyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    profitBeforeTax.setHYC_Complete_Value(String.valueOf(score.getComplete()));
                    profitBeforeTax.setHYC_score(String.valueOf(score.getScore()));
                }
                target = performanceRecordService.getTarget(recordId);
                if(target != null){
                    profitBeforeTax.setHYC_threshold(target.getThresholdTarget());
                    profitBeforeTax.setHYC_atLeast(target.getAtLeastTarget());
                    profitBeforeTax.setHYC_scream(target.getScreamTarget());
                    profitBeforeTax.setHYC_howl(target.getHowlTarget());
                }

                //全年 综合利润 AL
                //设置月份
                quarterly = quarter;

                recordId = performanceRecordService.getRecordId(elementId2,year,quarterly,hierarchyId);
                target = performanceRecordService.getTarget(recordId);
                if(target != null){
                    profitBeforeTax.setAL_threshold(target.getThresholdTarget());
                    profitBeforeTax.setAL_atLeast(target.getAtLeastTarget());
                    profitBeforeTax.setAL_scream(target.getScreamTarget());
                    profitBeforeTax.setAL_howl(target.getHowlTarget());
                }
                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    profitBeforeTax.setAL_Complete_Value(String.valueOf(score.getComplete()));
                    profitBeforeTax.setAL_score(String.valueOf(score.getScore()));
                }

                // 全年 税前利润 ALC
                recordId = performanceRecordService.getRecordId(elementId3,year,quarterly,hierarchyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    profitBeforeTax.setALC_Complete_Value(String.valueOf(score.getComplete()));
                    profitBeforeTax.setALC_score(String.valueOf(score.getScore()));
                }
                target = performanceRecordService.getTarget(recordId);
                if(target != null){
                    profitBeforeTax.setALC_threshold(target.getThresholdTarget());
                    profitBeforeTax.setALC_atLeast(target.getAtLeastTarget());
                    profitBeforeTax.setALC_scream(target.getScreamTarget());
                    profitBeforeTax.setALC_howl(target.getHowlTarget());
                }
                //指标总得分
                record = performanceRecordService.getRecordSelective(elementId,year,quarterly,hierarchyId);
                if(record != null){
                    profitBeforeTax.setIs_check(record.getIsExamine() == 1 ? 1 : 0);
                    recordId = record.getRecordId();
                    score = performanceRecordService.getScore(recordId);
                    if(score != null){
                        profitBeforeTax.setIndividualScore(String.valueOf(score.getScore()));
                    }
                }else{
                    profitBeforeTax.setIs_check(1);
                }
                returnList.add(profitBeforeTax);
            }
            result.setDataList(returnList);
        }
            return result;
    }

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

        //返回的对象
        RecordPerformanceDto recordDto = new RecordPerformanceDto();

        String jsonString = JSONObject.toJSONString(values);

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

        long elementId2 = 1005001L;
        long elementId3 = 1005002L;

        for(ProfitBeforeTax profitBeforeTax : list){

            String hierachyId = profitBeforeTax.getHierarchyId();

            String[] thresholds = {profitBeforeTax.getHY_threshold(), profitBeforeTax.getAL_threshold(), profitBeforeTax.getHYC_threshold(), profitBeforeTax.getALC_threshold()};
            String[] atLasts = {profitBeforeTax.getHY_atLeast(), profitBeforeTax.getAL_atLeast(), profitBeforeTax.getHYC_atLeast(), profitBeforeTax.getALC_atLeast()};
            String[] screams = {profitBeforeTax.getHY_scream(), profitBeforeTax.getAL_scream(), profitBeforeTax.getHYC_scream(), profitBeforeTax.getALC_scream()};
            String[] howls = {profitBeforeTax.getHY_howl(), profitBeforeTax.getAL_howl(), profitBeforeTax.getHYC_howl(), profitBeforeTax.getALC_howl()};
            String[] completes = {profitBeforeTax.getHY_Complete_Value(), profitBeforeTax.getAL_Complete_Value(), profitBeforeTax.getHYC_Complete_Value(), profitBeforeTax.getALC_Complete_Value()};
            String[] scores = {"-1", "-1", "-1", "-1"};

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

            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);// 计算结果

                recordDto.setElementId(subElementId);
                recordDto.setHierachyId(hierachyId);
                recordDto.setYear(year);
                recordDto.setQuarter(q);
                recordDto.setComplete((float) complete);
                recordDto.setScore(Float.parseFloat(scores[i]));
                recordDto.setThreshold(String.valueOf(atLeast));  //没有门槛值，门槛值跟保底值相等
                recordDto.setAt_Least(String.valueOf(atLeast));
                recordDto.setScream(String.valueOf(scream));
                recordDto.setHowl(String.valueOf(howl));
                performanceRecordService.performanceRecord(recordDto);
            }

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

            profitBeforeTax.setHY_score(String.valueOf(HY_score));
            profitBeforeTax.setAL_score(String.valueOf(AL_score));
            profitBeforeTax.setHYC_score(String.valueOf(HYC_score));
            profitBeforeTax.setALC_score(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);
            }
            profitBeforeTax.setIndividualScore(IndividualScore);

            recordDto.setElementId(elementId);
            recordDto.setHierachyId(hierachyId);
            recordDto.setYear(year);
            recordDto.setQuarter(quarter);
            recordDto.setScore(Float.parseFloat(IndividualScore));
            recordDto.setComplete(-1);
            recordDto.setThreshold(null);  //没有门槛值，门槛值跟保底值相等
            recordDto.setAt_Least(null);
            recordDto.setScream(null);
            recordDto.setHowl(null);
            recordDto.setIsExamine((short)profitBeforeTax.getIs_check());
            recordDto.setWeight(0.1);
            performanceRecordService.performanceRecord(recordDto);

        }
        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.PretaxProfitUpload(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);
    }
}
