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.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *  社区经营服务业务实现类
 *
 * @Author:Wyman
 * @Date:2018/11/3
 */
@Service
public class CommunityServiceImpl<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<CommunityManagement> returnList = new ArrayList<>();

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

            Long elementSqzzfw = 1006001L;//社区增值服务
            Long elementSqzzsq = 1006001001L;//社区增值税前
            Long elementYwjg = 1006001002L;//业务结构系数
            Long elementFwpt = 1006001002001L;//房屋配套
            Long elementShtg = 1006001002002L;//生活团购
            Long elementSqgg = 1006001002003L;//社区广告
            Long elementZyjy = 1006001002004L;//资源经营

            Long elementFczs = 1006002L;//房产租售服务
            Long elementFwsq = 1006002001L;//房屋税前利润
            Long elementFcjysc = 1006002002L;//房产经营市场占有率
            Long elementKpgz = 1006002003L;//控盘工作完成情况

            Long elementJzlgs = 1006003L;//居者乐公司服务

            for(PerformanceArea p : organList){

                CommunityManagement c = new CommunityManagement();

                String hierarchyId = p.getHierachyId();
                c.setHierarchyId(hierarchyId);
                c.setSecond_organization(p.getHierachyName());
                c.setThird_organization(p.getHierachyName());
                c.setHierarchy(p.getHierachyName());
                c.setYear(String.valueOf(year));
                c.setQuarterly(String.valueOf(quarter));

                /*-----------------税前利润部分 start------------------------*/
                recordId = performanceRecordService.getRecordId(elementSqzzsq,year,quarter,hierarchyId);//社区增值税前利润
                target = performanceRecordService.getTarget(recordId);
                score = performanceRecordService.getScore(recordId);
                if(target != null){
                    c.setCvapp_threshold(target.getThresholdTarget());
                    c.setCvapp_atLeast(target.getAtLeastTarget());
                    c.setCvapp_scream(target.getScreamTarget());
                    c.setCvapp_howl(target.getHowlTarget());
                }
                if (score != null) {
                    c.setCvapp_actual(String.valueOf(score.getComplete()));  //税前利润实际值
                }
                /*-----------------税前利润部分 end------------------------*/

                /*-----------------业务结构系数部分 start------------------------*/

                //房屋配套
                recordId = performanceRecordService.getRecordId(elementFwpt,year,quarter,hierarchyId);
                target = performanceRecordService.getTarget(recordId);
                score = performanceRecordService.getScore(recordId);
                if (target != null) {
                    c.setAccommodationTarget(target.getAtLeastTarget());
                }
                if (score != null) {
                    c.setAccommodationRatio(String.valueOf(score.getScore()));
                    c.setAccommodationActual(String.valueOf(score.getComplete()));
                }

                //生活团购
                recordId = performanceRecordService.getRecordId(elementShtg,year,quarter,hierarchyId);
                target = performanceRecordService.getTarget(recordId);
                score = performanceRecordService.getScore(recordId);
                if (target != null) {
                    c.setGroupBuyingTarget(target.getAtLeastTarget());
                }
                if (score != null) {
                    c.setGroupBuyingRatio(String.valueOf(score.getScore()));
                    c.setGroupBuyingActual(String.valueOf(score.getComplete()));
                }

                //社区广告
                recordId = performanceRecordService.getRecordId(elementSqgg,year,quarter,hierarchyId);
                target = performanceRecordService.getTarget(recordId);
                score = performanceRecordService.getScore(recordId);
                if (target != null) {
                    c.setAdvertisementTarget(target.getAtLeastTarget());
                }
                if (score != null) {
                    c.setAdvertisementRatio(String.valueOf(score.getScore()));
                    c.setAdvertisementActual(String.valueOf(score.getComplete()));
                }

                //资源经营
                recordId = performanceRecordService.getRecordId(elementZyjy,year,quarter,hierarchyId);
                target = performanceRecordService.getTarget(recordId);
                score = performanceRecordService.getScore(recordId);
                if (target != null) {
                    c.setResourceManagementTarget(target.getAtLeastTarget());
                }
                if (score != null) {
                    c.setResourceManagementRatio(String.valueOf(score.getScore()));
                    c.setResourceManagementActual(String.valueOf(score.getComplete()));
                }

                //业务结构系数和细项得分
                recordId = performanceRecordService.getRecordId(elementYwjg,year,quarter,hierarchyId);
                target = performanceRecordService.getTarget(recordId);
                if (target != null) {
                    c.setStructulRatio(target.getStructParam());
                }
                recordId = performanceRecordService.getRecordId(elementSqzzfw,year,quarter,hierarchyId);
                score = performanceRecordService.getScore(recordId);
                if (score != null) {
                    c.setCva_score(String.valueOf(score.getScore()));
                }
                /*-----------------业务结构系数部分 end------------------------*/

                /*-----------------房屋租售税前利润部分 start------------------------*/
                recordId = performanceRecordService.getRecordId(elementFwsq,year,quarter,hierarchyId);
                target = performanceRecordService.getTarget(recordId);
                score = performanceRecordService.getScore(recordId);
                if(target != null){
                    c.setHrspp_threshold(target.getThresholdTarget());
                    c.setHrspp_atLeast(target.getAtLeastTarget());
                    c.setHrspp_scream(target.getScreamTarget());
                    c.setHrspp_howl(target.getHowlTarget());
                }
                if (score != null) {
                    c.setHrspp_actual(String.valueOf(score.getComplete()));
                }
                /*-----------------房屋租售税前利润部分 end------------------------*/

                /*-----------------市场占有率部分 start------------------------*/
                recordId = performanceRecordService.getRecordId(elementFcjysc,year,quarter,hierarchyId);
                target = performanceRecordService.getTarget(recordId);
                score = performanceRecordService.getScore(recordId);
                if (score != null) {
                    c.setMo_actual(String.valueOf(score.getComplete()));
                }
                if (target != null) {
                    c.setMo_target(String.valueOf(target.getAtLeastTarget()));//市场占有率目标值
                }
                /*-----------------市场占有率部分 end------------------------*/

                /*-----------------控盘部分 start------------------------*/
                recordId = performanceRecordService.getRecordId(elementKpgz,year,quarter,hierarchyId);
                score = performanceRecordService.getScore(recordId);//年度
                if(score != null){
                    c.setAnnual(String.valueOf(score.getScore()));
                }
                recordId = performanceRecordService.getRecordId(elementKpgz,year,1,hierarchyId);
                score = performanceRecordService.getScore(recordId);//s1
                if(score != null){
                    c.setS1(String.valueOf(score.getComplete()));
                }
                recordId = performanceRecordService.getRecordId(elementKpgz,year,2,hierarchyId);
                score = performanceRecordService.getScore(recordId);//s2
                if(score != null){
                    c.setS2(String.valueOf(score.getComplete()));
                }
                recordId = performanceRecordService.getRecordId(elementKpgz,year,3,hierarchyId);
                score = performanceRecordService.getScore(recordId);//s3
                if(score != null){
                    c.setS3(String.valueOf(score.getComplete()));
                }
                recordId = performanceRecordService.getRecordId(elementKpgz,year,1,hierarchyId);
                score = performanceRecordService.getScore(recordId);//s4
                if(score != null){
                    c.setS4(String.valueOf(score.getComplete()));
                }
                recordId = performanceRecordService.getRecordId(elementFczs,year,quarter,hierarchyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    c.setHrs_score(String.valueOf(score.getScore()));
                }
                /*-----------------控盘部分 end------------------------*/

                /*-----------------居者乐部分 start------------------------*/
                recordId = performanceRecordService.getRecordId(elementJzlgs,year,quarter,hierarchyId);
                target = performanceRecordService.getTarget(recordId);
                score = performanceRecordService.getScore(recordId);
                if (score != null) {
                    c.setJzl_score(String.valueOf(score.getScore()));
                    c.setJzl_actual(String.valueOf(score.getComplete()));
                }
                if (target != null) {
                    c.setJzl_threshold(target.getThresholdTarget());
                    c.setJzl_atLeast(target.getAtLeastTarget());
                    c.setJzl_scream(target.getScreamTarget());
                    c.setJzl_howl(target.getHowlTarget());
                }
                /*-----------------居者乐部分 end------------------------*/
                record = performanceRecordService.getRecordSelective(elementId,year,quarter,hierarchyId);
                if(record != null){
                    c.setIsCheck(String.valueOf(record.getIsExamine()));
                    recordId = record.getRecordId();
                    score = performanceRecordService.getScore(recordId);
                    if (score != null) {
                        c.setTotalScore(String.valueOf(score.getScore()));
                    }
                }
                c.setQuarterly(String.valueOf(quarter));
                returnList.add(c);
            }
            result.setDataList(returnList);
        }
        return result;
    }

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

        Long elementSqzzfw = 1006001L;//社区增值服务
        Long elementSqzzsq = 1006001001L;//社区增值税前
        Long elementFwpt = 1006001002001L;//房屋配套
        Long elementShtg = 1006001002002L;//生活团购
        Long elementSqgg = 1006001002003L;//社区广告
        Long elementZyjy = 1006001002004L;//资源经营
        Long elementYwjg = 1006001002L;//业务结构系数
        Long elementFwsq = 1006002001L;//房屋税前利润
        Long elementFcjysc = 1006002002L;//房产经营市场占有率
        Long elementKpgz = 1006002003L;//控盘工作完成情况
        Long elementFczs = 1006002L;//房产租售服务
        Long elementJzlgs = 1006003L;//居者乐公司服务

        String jsonString = JSONObject.toJSONString(values);

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

        for(CommunityManagement communitym : list){

            String hierachyId = communitym.getHierarchyId();

            RecordPerformanceDto performanceDto = new RecordPerformanceDto();
            performanceDto.setYear(year);
            performanceDto.setQuarter(quarter);
            performanceDto.setHierachyId(hierachyId);
            //--------------------社区增值税前利润
            //实际值
            performanceDto.setElementId(elementSqzzsq);
            performanceDto.setComplete(Float.valueOf(communitym.getCvapp_actual()));
            ////////////////计算社区增值税前利润得分////////////////
            String temp_score_sqzzsq = "-1";
            //实际值  门槛值  保底  尖叫  嚎叫
            if ((!StringUtil.isBlankOrEmpty(communitym.getCvapp_actual())) && (!StringUtil.isBlankOrEmpty(communitym.getCvapp_threshold())) &&
                    (!StringUtil.isBlankOrEmpty(communitym.getCvapp_atLeast())) && (!StringUtil.isBlankOrEmpty(communitym.getCvapp_scream())) &&
                    (!StringUtil.isBlankOrEmpty(communitym.getCvapp_howl()))) {
                try {
                    temp_score_sqzzsq = Calculate.InsertionMethod(Double.valueOf(communitym.getCvapp_actual()),
                            Double.valueOf(communitym.getCvapp_threshold()), Double.valueOf(communitym.getCvapp_atLeast()),
                            Double.valueOf(communitym.getCvapp_scream()), Double.valueOf(communitym.getCvapp_howl()), 1);
                } catch (Exception e) {
                }
            }
            if (temp_score_sqzzsq != null) {
                try {
                    performanceDto.setScore(Float.valueOf(temp_score_sqzzsq));
                } catch (Exception e) {
                    performanceDto.setScore(0);
                }
            } else {
                performanceDto.setScore(0);
            }
            /////////////////////////////////////////////////////////
            //目标值
            performanceDto.setThreshold(communitym.getCvapp_threshold());//社区增值税前利润: 门槛值
            performanceDto.setAt_Least(communitym.getCvapp_atLeast());//社区增值税前利润: 保底
            performanceDto.setScream(communitym.getCvapp_scream());//社区增值税前利润: 尖叫
            performanceDto.setHowl(communitym.getCvapp_howl());//社区增值税前利润: 嚎叫
            performanceRecordService.performanceRecord(performanceDto);

            //-------------------业务结构系数
            //-------房屋配套
            //房屋配套实际值,房屋配套结构系数
            performanceDto.setElementId(elementFwpt);
            //计算房屋配套结构系数
            double accommodationRatio = -1;
            if (communitym.getAccommodationActual() != null && (!communitym.getAccommodationActual().equals("")) && communitym.getAccommodationTarget() != null && (!communitym.getAccommodationTarget().equals(""))) {
                accommodationRatio = single(communitym.getAccommodationActual(), communitym.getAccommodationTarget());
                communitym.setAccommodationRatio(String.valueOf(accommodationRatio));//设置前端返回值
            } else {
                communitym.setAccommodationRatio(null);//设置前端返回值为null
            }
            /////////////////
            performanceDto.setComplete(Float.valueOf(communitym.getAccommodationActual()) == null ? -1 : Float.valueOf(communitym.getAccommodationActual()));
            performanceDto.setScore((float) accommodationRatio);//房屋配套结构系数
            performanceDto.setThreshold(null);
            performanceDto.setAt_Least(communitym.getCvapp_atLeast() == null ? "-1" : communitym.getCvapp_atLeast());//房屋配套保底目标
            performanceDto.setScream(null);
            performanceDto.setHowl(null);
            performanceRecordService.performanceRecord(performanceDto);

            //-------房屋配套
            //生活团购实际值，生活团购结构系数
            performanceDto.setElementId(elementShtg);
            // 生活团购结构系数
            double groupBuyingRatio = -1;
            if (communitym.getGroupBuyingActual() != null && (!communitym.getGroupBuyingActual().equals("")) && communitym.getGroupBuyingTarget() != null && (!communitym.getGroupBuyingTarget().equals(""))) {
                groupBuyingRatio = single(communitym.getGroupBuyingActual(), communitym.getGroupBuyingTarget());
                communitym.setGroupBuyingRatio(String.valueOf(groupBuyingRatio));//设置前端返回值
            } else {
                communitym.setGroupBuyingRatio(null);//设置前端返回值为null
            }
            performanceDto.setComplete(Float.valueOf(communitym.getGroupBuyingActual()) == null ? -1 : Float.valueOf(communitym.getGroupBuyingActual()));//生活团购实际值
            performanceDto.setScore((float)groupBuyingRatio);//生活团购结构系数
            performanceDto.setThreshold(null);
            performanceDto.setAt_Least(communitym.getGroupBuyingTarget() == null ? "-1" : communitym.getGroupBuyingTarget());//房屋配套保底目标
            performanceDto.setScream(null);
            performanceDto.setHowl(null);
            performanceRecordService.performanceRecord(performanceDto);

            //-------社区广告
            //社区广告实际值，社区广告结构系数
            performanceDto.setElementId(elementSqgg);
            double advertisementRatio = -1;
            if (communitym.getAdvertisementActual() != null && (!communitym.getAdvertisementActual().equals(""))
                    && communitym.getAdvertisementTarget() != null && (!communitym.getAdvertisementTarget().equals(""))) {
                advertisementRatio = single(communitym.getAdvertisementActual(), communitym.getAdvertisementTarget());
                communitym.setAdvertisementRatio(String.valueOf(advertisementRatio));//返回前端的数据
            } else {
                communitym.setAdvertisementRatio(null);//设置前端返回值为null
            }
            performanceDto.setComplete(Float.valueOf(communitym.getAdvertisementActual()) == null ? -1 :Float.valueOf(communitym.getAdvertisementActual()));//社区广告实际值
            performanceDto.setScore((float) advertisementRatio);//社区广告结构系数
            performanceDto.setThreshold(null);
            performanceDto.setAt_Least(communitym.getAdvertisementTarget() == null ? "-1" : communitym.getAdvertisementTarget());//社区广告保底目标
            performanceDto.setScream(null);
            performanceDto.setHowl(null);
            performanceRecordService.performanceRecord(performanceDto);

            //-------资源经营实际值
            //资源经营实际值，资源经营结构系数
            performanceDto.setElementId(elementZyjy);
            // 资源经营结构系数
            double resourceManagementRatio = -1;
            if (communitym.getResourceManagementActual() != null && (!communitym.getResourceManagementActual().equals(""))
                    && communitym.getResourceManagementTarget() != null && (!communitym.getResourceManagementTarget().equals(""))) {
                resourceManagementRatio = single(communitym.getResourceManagementActual(),
                        communitym.getResourceManagementTarget());
                communitym.setResourceManagementRatio(String.valueOf(resourceManagementRatio));
            } else {
                communitym.setResourceManagementRatio(String.valueOf(resourceManagementRatio));//设置前端返回值为null
            }
            performanceDto.setComplete(Float.valueOf(communitym.getResourceManagementActual()) == null ? -1 :Float.valueOf(communitym.getResourceManagementActual()));//资源经营实际值);
            performanceDto.setScore((float) resourceManagementRatio);//资源经营结构系数
            performanceDto.setThreshold(null);
            performanceDto.setAt_Least(communitym.getResourceManagementTarget() == null ? "-1" : communitym.getResourceManagementTarget());//资源经营实际值
            performanceDto.setScream(null);
            performanceDto.setHowl(null);

            //-----业务结构系数
            //////////////////////////////////////////
            //业务结构系数
            double structulRatio = -1;
            if (accommodationRatio != -1 && groupBuyingRatio != -1 && advertisementRatio != -1 && resourceManagementRatio != -1) {
                structulRatio = coefficient(accommodationRatio, groupBuyingRatio, advertisementRatio,
                        resourceManagementRatio);
                communitym.setStructulRatio(String.format("%.2f", structulRatio / 100));
            } else {
                communitym.setStructulRatio(null);
            }
            performanceDto.setElementId(elementYwjg);
            performanceDto.setAt_Least(String.format("%.2f", structulRatio / 100));//原target中的结构系数值存到保底值里
            performanceDto.setScore(Float.parseFloat(String.format("%.2f", structulRatio / 100)));
            performanceDto.setComplete(Float.parseFloat(String.format("%.2f", structulRatio / 100)));
            performanceRecordService.performanceRecord(performanceDto);

            //--------社区增值服务-细项得分
            //////////////////////////////////////////////////
            double cva_score = -1;
            if (communitym.getCvapp_actual() != null && (!communitym.getCvapp_actual().equals(""))
                    && communitym.getCvapp_threshold() != null && (!communitym.getCvapp_threshold().equals(""))
                    && communitym.getCvapp_atLeast() != null && (!communitym.getCvapp_atLeast().equals(""))
                    && communitym.getCvapp_scream() != null && (!communitym.getCvapp_scream().equals(""))
                    && communitym.getCvapp_howl() != null && (!communitym.getCvapp_howl().equals(""))) {
                //计算
                cva_score = arithmetic(communitym.getCvapp_actual(), communitym.getCvapp_threshold(),
                        communitym.getCvapp_atLeast(), communitym.getCvapp_scream(), communitym.getCvapp_howl());
                cva_score = new BigDecimal(cva_score * structulRatio / 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();     //增值服务得分* 结构系数
            }
            communitym.setCva_score(String.valueOf(cva_score));//要返回给前端的值
            performanceDto.setElementId(elementSqzzfw);
            performanceDto.setScore((float) cva_score);
            performanceDto.setComplete(-1);
            performanceDto.setAt_Least("");
            performanceRecordService.performanceRecord(performanceDto);

            //-----房屋租售税前利润
            //实际值
            performanceDto.setElementId(elementFwsq);
            ////////////////计算房屋租售税前利润得分////////////////
            String temp_score_Fwsq = "-1";
            //实际值  门槛值  保底  尖叫  嚎叫
            if ((!StringUtil.isBlankOrEmpty(communitym.getHrspp_actual())) && (!StringUtil.isBlankOrEmpty(communitym.getHrspp_threshold())) &&
                    (!StringUtil.isBlankOrEmpty(communitym.getHrspp_atLeast())) && (!StringUtil.isBlankOrEmpty(communitym.getHrspp_scream())) &&
                    (!StringUtil.isBlankOrEmpty(communitym.getHrspp_howl()))) {
                try {
                    temp_score_Fwsq = Calculate.InsertionMethod(Double.valueOf(communitym.getHrspp_actual()),
                            Double.valueOf(communitym.getHrspp_threshold()), Double.valueOf(communitym.getHrspp_atLeast()),
                            Double.valueOf(communitym.getHrspp_scream()), Double.valueOf(communitym.getHrspp_howl()), 1);
                } catch (Exception e) {
                }
            }
            performanceDto.setComplete(Float.valueOf(communitym.getHrspp_actual()) == null ? -1 : Float.valueOf(communitym.getHrspp_actual()));//房屋租售税前利润: 实际值
            performanceDto.setScore(Float.valueOf(temp_score_Fwsq) == null ? -1 :Float.valueOf(temp_score_Fwsq));
            performanceDto.setThreshold(communitym.getHrspp_threshold());//房屋租售税前利润: 门槛值
            performanceDto.setAt_Least(communitym.getHrspp_atLeast());//房屋租售税前利润: 保底
            performanceDto.setScream(communitym.getHrspp_scream());//房屋租售税前利润: 尖叫
            performanceDto.setHowl(communitym.getHrspp_howl());//房屋租售税前利润: 嚎叫
            performanceRecordService.performanceRecord(performanceDto);

            //市场占有率
            performanceDto.setElementId(elementFcjysc);
            performanceDto.setComplete(Float.valueOf(communitym.getMo_actual()) == null ? -1 : Float.valueOf(communitym.getMo_actual()));//市场占有率实际值
            performanceDto.setScore((float) bazaars(communitym.getMo_actual(), communitym.getMo_target()));//市场占有率目标值
            performanceDto.setAt_Least(communitym.getMo_target());
            performanceDto.setThreshold(null);
            performanceDto.setScream(null);
            performanceDto.setHowl(null);
            performanceRecordService.performanceRecord(performanceDto);

            //-----------控盘得分
            String[] scores = {communitym.getS1(), communitym.getS2(), communitym.getS3(), communitym.getS4()};
            int q = quarter;
            q = q > 4 ? 4 : q;

            double annual = Calculate.Year(scores[0], scores[1], scores[2], scores[3]);
            performanceDto.setElementId(elementKpgz);
            performanceDto.setComplete(Float.valueOf(scores[q - 1]) == null ? -1 : Float.valueOf(scores[q - 1]));
            performanceDto.setScore((float) annual);//年度
            performanceDto.setAt_Least(null);
            performanceRecordService.performanceRecord(performanceDto);

            communitym.setAnnual(String.valueOf(annual));//返回给前端
            //----------房屋租售服务-细项得分
            ////////////////////////////////////////
            double befores = -1;
            double bazaars = -1;
            double hrs_score;
            // 税前利润得分：
            if (communitym.getHrspp_actual() != null && (!communitym.getHrspp_actual().equals(""))
                    && communitym.getHrspp_threshold() != null && (!communitym.getHrspp_threshold().equals(""))
                    && communitym.getHrspp_atLeast() != null && (!communitym.getHrspp_atLeast().equals(""))
                    && communitym.getHrspp_scream() != null && (!communitym.getHrspp_scream().equals(""))
                    && communitym.getHrspp_howl() != null && (!communitym.getHrspp_howl().equals(""))) {
                //计算
                befores = arithmetic(communitym.getHrspp_actual(), communitym.getHrspp_threshold(), communitym.getHrspp_atLeast(), communitym.getHrspp_scream(), communitym.getHrspp_howl());
            }
            // 市场占有率
            if (!StringUtil.isBlankOrEmpty(communitym.getMo_actual()) && !StringUtil.isBlankOrEmpty(communitym.getMo_target())) {
                bazaars = bazaars(communitym.getMo_actual(), communitym.getMo_target());
            }
            // ===房屋租售细项得分
            hrs_score = houseScore(befores, bazaars, annual);
            communitym.setHrs_score(String.valueOf(hrs_score));//返回给前端
            ////////////////////////////////////////
            performanceDto.setElementId(elementFczs);
            performanceDto.setScore((float) hrs_score);//房屋租售服务 细项得分
            performanceDto.setComplete(-1);
            performanceRecordService.performanceRecord(performanceDto);

            //-----------居者乐
            //居者乐实际值，细项得分
            performanceDto.setElementId(elementJzlgs);
            // 居者乐细项得分
            double jzl_score = -1;
            if (communitym.getJzl_actual() != null && (!communitym.getJzl_actual().equals(""))
                    && communitym.getJzl_threshold() != null && (!communitym.getJzl_threshold().equals(""))
                    && communitym.getJzl_atLeast() != null && (!communitym.getJzl_atLeast().equals(""))
                    && communitym.getJzl_scream() != null && (!communitym.getJzl_scream().equals(""))
                    && communitym.getJzl_howl() != null && (!communitym.getJzl_howl().equals(""))) {
                jzl_score = arithmetic(communitym.getJzl_actual(), communitym.getJzl_threshold(), communitym.getJzl_atLeast(),
                        communitym.getJzl_scream(), communitym.getJzl_howl());
            }
            communitym.setJzl_score(String.valueOf(jzl_score));//返回给前端
            performanceDto.setScore((float) jzl_score);//居者乐公司服务协作: 得分
            performanceDto.setComplete(Float.valueOf(communitym.getJzl_actual()) == null ? -1 : Float.valueOf(communitym.getJzl_actual()));//居者乐公司服务协作: 实际值
            performanceDto.setThreshold(communitym.getJzl_threshold());//居者乐公司服务协作: 门槛值
            performanceDto.setAt_Least(communitym.getJzl_atLeast());//居者乐公司服务协作: 保底
            performanceDto.setScream(communitym.getJzl_scream());//居者乐公司服务协作: 尖叫
            performanceDto.setHowl(communitym.getJzl_howl());//居者乐公司服务协作: 嚎叫
            performanceRecordService.performanceRecord(performanceDto);

            //---------------指标单项得分
            /////////////////////////
            double totalScore = actual(cva_score, hrs_score, jzl_score);

            if (communitym.getIsCheck().equals("0")) {
                totalScore = -1;
            }
            communitym.setTotalScore(String.valueOf(totalScore));//返回给前端
            performanceDto.setElementId(elementId);
            performanceDto.setScore((float) totalScore);//指标单项得分
            performanceDto.setThreshold(null);
            performanceDto.setAt_Least(null);
            performanceDto.setScream(null);
            performanceDto.setHowl(null);
            performanceDto.setIsExamine(Short.parseShort(communitym.getIsCheck()));
            performanceDto.setWeight(0.15);
            performanceRecordService.performanceRecord(performanceDto);
        }
        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.communityManageUpload(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);
    }


    // =======单项系数得分
    public double single(String value, String atLeastTarget) {
        double values = Double.parseDouble(value);// 传入值
        double atLeastTargets = Double.parseDouble(atLeastTarget); // 保底目标值
        double result = 0;// 结果值
        // 传值判断
        if (value == null || value.equals("")) {
            return -1;
        }
        if (value == null || atLeastTarget.equals("")) {
            return -1;
        }
        // 低于保底目标
        if (values >= atLeastTargets * 0.8 && values < atLeastTargets) {
            result = 60 + 40 * (values - atLeastTargets * 0.8) / (atLeastTargets - atLeastTargets * 0.8);

            // 高于保底目标
        } else if (values >= atLeastTargets) {
            result = 100;

        } else if (values <= atLeastTargets * 0.8) {
            result = 0;

        }
        return new BigDecimal(result).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    // =======社会增值业务结构系数
    public Double coefficient(double houses, double groups, double communitys, double resources) {
        double house = houses; // 房屋配套值
        double group = groups; // 生活团购
        double community = communitys; // 社区广告
        double resource = resources; // 资源经营
        double operation;// 业务结构系数
        int f = 4;
        if (house == -1) {
            house = 0;
            f = f - 1;
        } else if (group == -1) {
            group = 0;
            f = f - 1;
        } else if (community == -1) {
            community = 0;
            f = f - 1;
        } else if (resource == -1) {
            resource = 0;
            f = f - 1;
        }
        operation = (house + group + community + resource) / f;
        return new BigDecimal(operation).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    // =======社会增值服务得分计算 细项得分 线性计算公式
    public double arithmetic(String value, String thresholdTarget, String atLeastTarget, String screamTarget,
                             String howlTarget) {
        double result = 0;// 结果值
        double values = 0;
        double thresholdTargets = 0;// 门槛目标值
        double atLeastTargets = 0;// 保底目标值
        double screamTargets = 0;// 尖叫目标值
        double howlTargets = 0;// 嚎叫值
        if (value != null || !value.equals("")) {
            try {
                values = Double.parseDouble(value);// 传入值
            } catch (NumberFormatException e) {
                values = 0;// 传入值
            }
        } else {
            return values = 0;
        }
        if (thresholdTarget != null && !thresholdTarget.equals("")) {
            thresholdTargets = Double.parseDouble(thresholdTarget);// 门槛目标值
            // 没有门槛值的情况
        } else if (thresholdTarget != null && !thresholdTarget.equals("") && atLeastTarget != null
                && !atLeastTarget.equals("")) {
            atLeastTargets = Double.parseDouble(atLeastTarget); // 保底目标值
            thresholdTargets = atLeastTargets * 0.8;
        }

        // 目标保底值判断
        if (atLeastTarget != null && !atLeastTarget.equals("")) {
            atLeastTargets = Double.parseDouble(atLeastTarget); // 保底目标值
        }
        if (atLeastTarget == null || atLeastTarget.equals("")) {
            return values = 0;
        }

        // 尖叫值判断
        if (screamTarget != null && !screamTarget.equals("")) {
            screamTargets = Double.parseDouble(screamTarget); // 尖叫目标值
        }
        if (screamTarget == null || screamTarget.equals("")) {
            return values = 0;
        }
        // 嚎叫值判断
        if (howlTarget != null && !howlTarget.equals("")) {
            howlTargets = Double.parseDouble(howlTarget); // 嚎叫目标值
        }
        if (howlTarget == null || howlTarget.equals("")) {
            return values = 0;
        }

        // 低于门槛值
        if (values < thresholdTargets) {
            result = 0;
            // 60分～100类型:
        } else if (values >= thresholdTargets && values < atLeastTargets) {
            result = 60 + 40 * ((values - thresholdTargets) / (atLeastTargets - thresholdTargets));

            // 100分～110类型:
        } else if (values >= atLeastTargets && values < screamTargets) {
            result = 100 + 10 * ((values - atLeastTargets) / (screamTargets - atLeastTargets));

            // 100分～120类型:
        } else if (values >= screamTargets && values < howlTargets) {
            result = 110 + 10 * ((values - screamTargets) / (howlTargets - screamTargets));

            // 大于嚎叫:
        } else if (values >= howlTargets) {
            result = 120;

        }
        return new BigDecimal(result).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    // ================市场占有率得分
    public double bazaars(String baza, String cvapp) {
        double result = 0;// 结果

        double before = 0;// 输入值
        try {
            before = Double.parseDouble(baza);
        } catch (NumberFormatException e) {
            before = -1;
        }
        double cvapp_atLeasts = 0;// 目标值
        try {
            cvapp_atLeasts = Double.parseDouble(cvapp);
        } catch (NumberFormatException e) {
            cvapp_atLeasts = 0;
        }

        if (before < cvapp_atLeasts) {
            result = 0;
        } else if (before >= cvapp_atLeasts) {
            result = 100;
        }
        return result;
    }

    // ================房屋租售得分
    public double houseScore(double before, double bazaar, double dish) {
        double result;// 结果
        double weight = 1; //权重
        if (before == -1 && bazaar == -1) {
            return -1;
        }
        if (before == -1) {
            weight -= 0.6;
            before = 0;
        }
        if (bazaar == -1) {
            weight -= 0.2;
            bazaar = 0;
        }
        result = before * 0.6 + bazaar * 0.2 + dish * 0.2;
        result = result / weight;
        return new BigDecimal(result).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    // 居者乐单项得分
    public double actual(double cva_score, double annual, double jzl_score) {
        double result = 0;// 结果
        int f = 3;
        // 为空
        if (jzl_score == -1) {
            f = f - 1;
            jzl_score = 0;
        }
        if (cva_score == -1) {
            f = f - 1;
            cva_score = 0;
        }
        if (annual == -1) {
            f = f - 1;
            annual = 0;
        }

        result = (cva_score + annual + jzl_score) / f;
        return new BigDecimal(result).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
