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

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

            for(PerformanceArea p : organList){
                CommunityProfix communityProfixTemp = new CommunityProfix();
                communityProfixTemp.setHierarchyId(p.getHierachyId());//组织id
                communityProfixTemp.setSecond_organization(p.getHierachyName());//二级组织
                communityProfixTemp.setThird_organization(p.getHierachyName());//三级组织
                communityProfixTemp.setYear(year);//设置年份
                communityProfixTemp.setQuarter(String.valueOf(quarter));//设置季度

                //---------完成值，指标单项得分---------
                String hierachyId = p.getHierachyId();
                record = performanceRecordService.getRecordSelective(elementId,year,quarter,hierachyId);
                if(record != null){
                    communityProfixTemp.setIsCheck((String.valueOf(record.getIsExamine())));//是否考核

                    recordId = performanceRecordService.getRecordId(elementId,year,quarter,hierachyId);
                    score = performanceRecordService.getScore(recordId);
                    target = performanceRecordService.getTarget(recordId);
                    if(score != null){
                        communityProfixTemp.setComplete(String.valueOf(score.getComplete()));//设置完成值
                        communityProfixTemp.setIndividualScore(String.valueOf(score.getScore()));//设置指标单项得分
                    }
                    if(target != null){
                        communityProfixTemp.setThresholdTarget(target.getThresholdTarget());//门槛值
                        communityProfixTemp.setAtLeastTarget(target.getAtLeastTarget());//保底
                        communityProfixTemp.setScreamTarget(target.getScreamTarget());//尖叫
                        communityProfixTemp.setHowlTarget(target.getHowlTarget());//嚎叫
                    }
                }else{
                    communityProfixTemp.setIsCheck("0");//是否考核(无数据情况下，为了不让前端报错，返回0)
                }
                recordId = performanceRecordService.getRecordId(elementId,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                target = performanceRecordService.getTarget(recordId);
                if(score != null){
                    communityProfixTemp.setComplete(String.valueOf(score.getComplete()));//设置完成值
                    communityProfixTemp.setIndividualScore(String.valueOf(score.getScore()));//设置指标单项得分
                }
                if(target != null){
                    communityProfixTemp.setThresholdTarget(target.getThresholdTarget());//门槛值
                    communityProfixTemp.setAtLeastTarget(target.getAtLeastTarget());//保底
                    communityProfixTemp.setScreamTarget(target.getScreamTarget());//尖叫
                    communityProfixTemp.setHowlTarget(target.getHowlTarget());//嚎叫
                }
                returnList.add(communityProfixTemp);
            }
            result.setDataList(returnList);
        }
        return result;
    }

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

        String jsonString = JSONObject.toJSONString(values);

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

        double weight = 0;
        for(CommunityProfix communityProfix : list){

            String hierarchyId = communityProfix.getHierarchyId();
            String type = performanceAreaService.getSubTypeByHierachyId(hierarchyId);
            switch (type){
                case "单一业主项目":
                    weight = 0.3;
                    break;
                case "多业主第一年":
                    weight = 0.1;
                    break;
                case "多业主第二年":
                    weight = 0.2;
                    break;
            }

            RecordPerformanceDto performanceDto = new RecordPerformanceDto();
            //存入社区经营税前利润目标值
            performanceDto.setElementId(elementId);
            performanceDto.setYear(year);
            performanceDto.setQuarter(quarter);
            performanceDto.setHierachyId(hierarchyId);
            performanceDto.setIsExamine(Short.parseShort(communityProfix.getIsCheck()));
            performanceDto.setWeight(weight);
            performanceDto.setThreshold(communityProfix.getThresholdTarget());//门槛值
            performanceDto.setAt_Least(communityProfix.getAtLeastTarget());//保底
            performanceDto.setScream(communityProfix.getScreamTarget());//尖叫
            performanceDto.setHowl(communityProfix.getHowlTarget());//嚎叫
            performanceRecordService.performanceRecord(performanceDto);

        //完全值存储
        double complete=-1;//记录完成值
        double thresholdTarget=-1;
        double atLeastTarget=-1;
        double screamTarget=-1;
        double howlTarget=-1;
        //完成值
        if(communityProfix.getComplete()!=null){
            try {
                complete=Double.parseDouble(communityProfix.getComplete());
            } catch (NumberFormatException e) {
                logger.error("======communityProfixController=====complete number is error format");
            }
        }
        //门槛值
        if(communityProfix.getThresholdTarget()!=null){
            try {
                thresholdTarget=Double.parseDouble(communityProfix.getThresholdTarget());
            } catch (NumberFormatException e) {
                logger.error("======communityProfixController=====thresholdTarget number is error format");
            }
        }

        //保底
        if(communityProfix.getAtLeastTarget()!=null){
            try {
                atLeastTarget=Double.parseDouble(communityProfix.getAtLeastTarget());
            } catch (NumberFormatException e) {
                logger.error("======communityProfixController=====atLeastTarget number is error format");
            }
        }

        //尖叫
        if(communityProfix.getThresholdTarget()!=null){
            try {
                screamTarget=Double.parseDouble(communityProfix.getComplete());
            } catch (NumberFormatException e) {
                logger.error("======communityProfixController=====screamTarget number is error format");
            }
        }

        //嚎叫
        if(communityProfix.getHowlTarget()!=null){
            try {
                howlTarget=Double.parseDouble(communityProfix.getHowlTarget());
            } catch (NumberFormatException e) {
                logger.error("======communityProfixController=====complete number is error format");
            }
        }

        double individualScore=0.0;
        //计算指标单项得分
        if(complete!=-1&&thresholdTarget!=-1&&atLeastTarget!=-1&&screamTarget!=-1&&howlTarget!=-1){
            individualScore= Double.parseDouble(Calculate.InsertionMethod(complete,thresholdTarget,atLeastTarget,screamTarget,howlTarget,1));
        }

        //设置
        communityProfix.setIndividualScore(String.valueOf(individualScore));//设置指标单项得分

        performanceDto.setComplete((float)complete);
        performanceDto.setScore((float)individualScore);
        performanceDto.setThreshold(null);
        performanceDto.setAt_Least(null);
        performanceDto.setScream(null);
        performanceDto.setHowl(null);
        performanceRecordService.performanceRecord(performanceDto);
        }
        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.communityProfixUpload(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);
    }
}
