package cn.com.countrygarden.bi.main.controller.performance.indicators;

import java.math.BigDecimal;
import java.util.*;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.performance.*;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.util.Calculate;
import cn.com.countrygarden.bi.main.service.performance.*;
import cn.com.countrygarden.bi.main.util.ExcelAnalysis;

import cn.com.countrygarden.bi.main.util.PerformancePower;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 社区经营服务Controller
 */
@Controller("CommunityserviceController")
@RequestMapping("/CommunityserviceController")
public class CommunityserviceController {
    @Autowired
    private PerformanceTargetService performanceTargetService;

    @Autowired
    private PerformanceEnvService PerformanceEnvService;

    @Autowired
    private PerformanceScoreService performanceScoreService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private ExcelAnalysis ea;

    @Autowired
    private  PerformancePower performancePower;

    @ResponseBody
    @RequestMapping(value = "/showTarget", method = {RequestMethod.POST, RequestMethod.GET})
    public Object showTarget(@RequestParam(value = "pageSize") int pageSize, @RequestParam(value = "pageCurr") int pageCurr, @RequestParam(value = "years") int years,
                             @RequestParam(value = "quarterly") String quarterly) {

        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        List<CommunityManagement> resultList = new ArrayList<>();

        PerformanceScore score = new PerformanceScore();
        PerformanceTarget target = new PerformanceTarget();
        PerformanceScore sValue = new PerformanceScore();
        PerformanceTarget tValue = new PerformanceTarget();

        Long elementId = 1006L;

        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;//居者乐公司服务

        try {
            List<PerformanceEnv> envList = PerformanceEnvService.selectPerformanceOrgan();
            int count = envList.size();
            int start = (pageCurr - 1) * pageSize;
            int end = pageCurr * pageSize;

            envList = envList.subList(start < 0 ? 0 : start, end >= count ? count : end);

            //查询多少条数据是录入的
            PerformanceScore performanceScore = new PerformanceScore();
            performanceScore.setYear(years);//年
            performanceScore.setQuarterly(quarterly);//季度
            performanceScore.setElementId(elementId);
            int vacancy = count - performanceScoreService.getTotalPage(performanceScore).getTotalPage();//空缺，还有多少个区域指标没填
            if (vacancy < 0) {
                vacancy = 0;
            }
            List<String> vacancyHierarchyName = PerformanceEnvService.selectNotInName(performanceScore);

            if (envList.size() != 0) {
                for (PerformanceEnv performanceEnv : envList) {

                    CommunityManagement c = new CommunityManagement();

                    String hierarchyId = performanceEnv.getHierarchyId();
                    c.setHierarchyId(hierarchyId);
                    c.setSecond_organization(performanceEnv.getHierarchyName());
                    c.setThird_organization(performanceEnv.getHierarchyName());
                    c.setHierarchy(performanceEnv.getHierarchyName());
                    c.setYear(String.valueOf(years));
                    c.setQuarterly(quarterly);

                    /*-----------------税前利润部分 start------------------------*/
                    target.setHierarchyId(hierarchyId);
                    target.setYear(years);
                    target.setQuarterly(quarterly);
                    target.setElementId(elementSqzzsq); //社区增值税前利润
                    tValue = performanceTargetService.getNewByHierarchyId(target);

                    //获税前利润实际值
                    score.setHierarchyId(hierarchyId);
                    score.setYear(years);
                    score.setQuarterly(quarterly);
                    score.setElementId(elementSqzzsq);  //社区增值税前利润
                    sValue = performanceScoreService.getscoreByHierarchyId(score);

                    if (tValue != null) {
                        c.setCvapp_threshold(tValue.getThresholdTarget());
                        c.setCvapp_atLeast(tValue.getAtLeastTarget());
                        c.setCvapp_scream(tValue.getScreamTarget());
                        c.setCvapp_howl(tValue.getHowlTarget());
                    }

                    if (sValue != null) {
                        c.setCvapp_actual(String.valueOf(sValue.getComplete()));  //税前利润实际值
                    }
                    /*-----------------税前利润部分 start------------------------*/

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

                    //房屋配套
                    target.setElementId(elementFwpt);
                    score.setElementId(elementFwpt);

                    tValue = performanceTargetService.getNewByHierarchyId(target);
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (tValue != null) {
                        c.setAccommodationTarget(tValue.getAtLeastTarget());
                    }
                    if (sValue != null) {
                        c.setAccommodationRatio(String.valueOf(sValue.getScore()));
                        c.setAccommodationActual(String.valueOf(sValue.getComplete()));
                    }

                    //生活团购
                    target.setElementId(elementShtg);
                    score.setElementId(elementShtg);

                    tValue = performanceTargetService.getNewByHierarchyId(target);
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (tValue != null) {
                        c.setGroupBuyingTarget(tValue.getAtLeastTarget());
                    }
                    if (sValue != null) {
                        c.setGroupBuyingRatio(String.valueOf(sValue.getScore()));
                        c.setGroupBuyingActual(String.valueOf(sValue.getComplete()));
                    }

                    //社区广告
                    target.setElementId(elementSqgg);
                    score.setElementId(elementSqgg);

                    tValue = performanceTargetService.getNewByHierarchyId(target);
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (tValue != null) {
                        c.setAdvertisementTarget(tValue.getAtLeastTarget());
                    }
                    if (sValue != null) {
                        c.setAdvertisementRatio(String.valueOf(sValue.getScore()));
                        c.setAdvertisementActual(String.valueOf(sValue.getComplete()));
                    }
                    //资源经营
                    target.setElementId(elementZyjy);
                    score.setElementId(elementZyjy);

                    tValue = performanceTargetService.getNewByHierarchyId(target);
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (tValue != null) {
                        c.setResourceManagementTarget(tValue.getAtLeastTarget());
                    }
                    if (sValue != null) {
                        c.setResourceManagementRatio(String.valueOf(sValue.getScore()));
                        c.setResourceManagementActual(String.valueOf(sValue.getComplete()));
                    }

                    //业务结构系数和细项得分
                    target.setElementId(elementYwjg);
                    score.setElementId(elementSqzzfw);
                    tValue = performanceTargetService.getNewByHierarchyId(target);
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (tValue != null) {
                        c.setStructulRatio(tValue.getStructParam());
                    }
                    if (sValue != null) {
                        c.setCva_score(String.valueOf(sValue.getScore()));
                    }
                    /*-----------------业务结构系数部分 end------------------------*/

                    /*-----------------房屋租售税前利润部分 start------------------------*/
                    target.setElementId(elementFwsq);
                    score.setElementId(elementFwsq);
                    tValue = performanceTargetService.getNewByHierarchyId(target);
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (tValue != null) {
                        c.setHrspp_threshold(tValue.getThresholdTarget());
                        c.setHrspp_atLeast(tValue.getAtLeastTarget());
                        c.setHrspp_scream(tValue.getScreamTarget());
                        c.setHrspp_howl(tValue.getHowlTarget());
                    }
                    if (sValue != null) {
                        c.setHrspp_actual(String.valueOf(sValue.getComplete()));
                    }

                    /*-----------------房屋租售税前利润部分 end------------------------*/

                    /*-----------------市场占有率部分 start------------------------*/
                    target.setElementId(elementFcjysc);
                    score.setElementId(elementFcjysc);
                    tValue = performanceTargetService.getNewByHierarchyId(target);
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
//                    if (tValue != null) {
//                        c.setMo_target(tValue.getAtLeastTarget());
//                    }
                    if (sValue != null) {
                        c.setMo_actual(String.valueOf(sValue.getComplete()));
                    }
                    if (tValue != null) {
                        c.setMo_target(String.valueOf(tValue.getAtLeastTarget()));//市场占有率目标值
                    }
                    /*-----------------市场占有率部分 end------------------------*/

                    /*-----------------控盘部分 start------------------------*/
                    score.setElementId(elementKpgz);
                    score.setQuarterly(quarterly);   //年度
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (sValue != null) {
                        c.setAnnual(String.valueOf(sValue.getScore()));
                    }
                    score.setQuarterly("1");   //S1
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (sValue != null) {
                        c.setS1(String.valueOf(sValue.getComplete()));
                    }
                    score.setQuarterly("2");   //S2
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (sValue != null) {
                        c.setS2(String.valueOf(sValue.getComplete()));
                    }
                    score.setQuarterly("3");   //S3
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (sValue != null) {
                        c.setS3(String.valueOf(sValue.getComplete()));
                    }
                    score.setQuarterly("4");   //S4
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (sValue != null) {
                        c.setS4(String.valueOf(sValue.getComplete()));
                    }

                    score.setQuarterly(quarterly);
                    score.setElementId(elementFczs);
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (sValue != null) {
                        c.setHrs_score(String.valueOf(sValue.getScore()));
                    }
                    /*-----------------控盘部分 end------------------------*/

                    /*-----------------居者乐部分 start------------------------*/
                    target.setElementId(elementJzlgs);
                    score.setElementId(elementJzlgs);

                    tValue = performanceTargetService.getNewByHierarchyId(target);
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (sValue != null) {
                        c.setJzl_score(String.valueOf(sValue.getScore()));
                        c.setJzl_actual(String.valueOf(sValue.getComplete()));
                    }
                    if (tValue != null) {
                        c.setJzl_threshold(tValue.getThresholdTarget());
                        c.setJzl_atLeast(tValue.getAtLeastTarget());
                        c.setJzl_scream(tValue.getScreamTarget());
                        c.setJzl_howl(tValue.getHowlTarget());
                    }

                    /*-----------------居者乐部分 end------------------------*/

                    score.setElementId(elementId);
                    target.setElementId(elementId);
                    tValue = performanceTargetService.getNewByHierarchyId(target);
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (sValue != null) {
                        c.setTotalScore(String.valueOf(sValue.getScore()));
                    }
                    if (tValue != null) {
                        c.setIsCheck(tValue.getIsCheck());
                    }
                    c.setQuarterly(quarterly);
                    resultList.add(c);
                }

                resultMap.put("list", resultList);
                resultMap.put("totalPage", count);
                resultMap.put("vacancy", vacancy);
            } else {
                List<CommunityManagement> cmm = new ArrayList<>();
                resultMap.put("list", cmm);
                resultMap.put("totalPage", 0);
                resultMap.put("vacancy", count);
            }
            resultMap.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Response.response(resultMap);
    }

    /*
        重构保存-自动计算接口
        @author Max 陈彩君
    */
    @ResponseBody
    @RequestMapping(value = "/TotalCalculate", method = {RequestMethod.POST, RequestMethod.GET})
    public Object TotalCalculate(@RequestBody List<CommunityManagement> values) {
        //关键字段
        Long elementIdSqjyff = 1006L;//社区经营服务的ElementId
        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;//居者乐公司服务

        List<CommunityManagement> result = new ArrayList<>();// 页面返回

        for (CommunityManagement communitym : values) {
            int year = Integer.parseInt(communitym.getYear());
            String quarter = communitym.getQuarterly();
            String hierarchyId = communitym.getHierarchyId();
            
            String lrdb=communitym.getLrdb();          //整体利润是否达标
            //--------------------社区增值税前利润
            //实际值
            PerformanceScore scoreSqzzsq = new PerformanceScore();
            scoreSqzzsq.setYear(year);//年
            //scoreSqzzsq.setQuarterly("6");
            scoreSqzzsq.setQuarterly(quarter);//设置季度
            scoreSqzzsq.setHierarchyId(hierarchyId);
            scoreSqzzsq.setElementId(elementSqzzsq);

            if (!StringUtil.isBlankOrEmpty(communitym.getCvapp_actual())) {
                scoreSqzzsq.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 {
                    scoreSqzzsq.setScore(Float.valueOf(temp_score_sqzzsq));
                } catch (Exception e) {
                    scoreSqzzsq.setScore(0);
                }
            } else {
                scoreSqzzsq.setScore(0);
            }
            /////////////////////////////////////////////////////////
            PerformanceScore sValueSqzzsq = performanceScoreService.getNewScore(scoreSqzzsq);////查询有没有这条记录
            //判断是否重复是就更新否就插入
            if (sValueSqzzsq == null) {
                scoreSqzzsq.setCreatedDate(new Date());//创建日期
                //插入
                performanceScoreService.insertScoreSelective(scoreSqzzsq);
            } else {
                performanceScoreService.updateScoreSelective(scoreSqzzsq);
            }

            //目标值
            PerformanceTarget targetSqzzsq = new PerformanceTarget();
            targetSqzzsq.setYear(year);
            //targetSqzzsq.setQuarterly("6");
            targetSqzzsq.setQuarterly(quarter);//按照季度指标来
            targetSqzzsq.setHierarchyId(hierarchyId);
            targetSqzzsq.setElementId(elementSqzzsq);

            PerformanceTarget tValueSqzzsq = performanceTargetService.getNewByHierarchyId(targetSqzzsq);
            if (tValueSqzzsq != null) {
                //更新4个目标值
                tValueSqzzsq.setThresholdTarget(communitym.getCvapp_threshold());//社区增值税前利润: 门槛值
                tValueSqzzsq.setAtLeastTarget(communitym.getCvapp_atLeast());//社区增值税前利润: 保底
                tValueSqzzsq.setScreamTarget(communitym.getCvapp_scream());//社区增值税前利润: 尖叫
                tValueSqzzsq.setHowlTarget(communitym.getCvapp_howl());//社区增值税前利润: 嚎叫
                //执行更新操作
                performanceTargetService.updateTargetSelective(tValueSqzzsq);
            } else {
                //插入4个目标值
                targetSqzzsq.setThresholdTarget(communitym.getCvapp_threshold());//社区增值税前利润: 门槛值
                targetSqzzsq.setAtLeastTarget(communitym.getCvapp_atLeast());//社区增值税前利润: 保底
                targetSqzzsq.setScreamTarget(communitym.getCvapp_scream());//社区增值税前利润: 尖叫
                targetSqzzsq.setHowlTarget(communitym.getCvapp_howl());//社区增值税前利润: 嚎叫
                targetSqzzsq.setCreatedDate(new Date());
                performanceTargetService.insertTargetSelective(targetSqzzsq);
            }

            //-------------------业务结构系数
            //-------房屋配套
            //房屋配套实际值,房屋配套结构系数
            PerformanceScore scoreFwpt = new PerformanceScore();
            //设置年/季/区/考核指标
            scoreFwpt.setYear(year);
            //targetFwpt.setQuarterly("6");//年度指标
            scoreFwpt.setQuarterly(quarter);//按照季度指标来
            scoreFwpt.setHierarchyId(hierarchyId);
            scoreFwpt.setElementId(elementFwpt);
            PerformanceScore sValueFwpt = performanceScoreService.getscoreByHierarchyId(scoreFwpt);
            //////////////////
            //计算房屋配套结构系数
            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
            }
            /////////////////
            if (sValueFwpt != null) {
                try {
                    sValueFwpt.setComplete(Float.valueOf(communitym.getAccommodationActual()));//房屋配套实际值
                } catch (NumberFormatException e) {
                    sValueFwpt.setComplete(-1);//房屋配套实际值
                }
                sValueFwpt.setScore((float) accommodationRatio);//房屋配套结构系数

                sValueFwpt.setUpdateDate(new Date());//修改日期
                performanceScoreService.updateScoreSelective(sValueFwpt);
            } else {
                try {
                    scoreFwpt.setComplete(Float.valueOf(communitym.getAccommodationActual()));//房屋配套实际值
                } catch (NumberFormatException e) {
                    scoreFwpt.setComplete(-1);//房屋配套实际值
                }

                scoreFwpt.setScore((float) accommodationRatio);//房屋配套结构系数

                scoreFwpt.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceScoreService.insertScoreSelective(scoreFwpt);
            }

            //房屋配套保底目标
            PerformanceTarget targetFwpt = new PerformanceTarget();
            targetFwpt.setYear(year);
            //targetFwpt.setQuarterly("6");//年度指标
            targetFwpt.setQuarterly(quarter);//设置季度指标
            targetFwpt.setHierarchyId(hierarchyId);
            targetFwpt.setElementId(elementFwpt);
            PerformanceTarget tValueFwpt = performanceTargetService.getNewByHierarchyId(targetFwpt);
            if (tValueFwpt != null) {
                tValueFwpt.setAtLeastTarget(communitym.getAccommodationTarget());//房屋配套保底目标
                tValueFwpt.setUpdateDate(new Date());//修改日期
                performanceTargetService.updateTargetSelective(tValueFwpt);
            } else {
                targetFwpt.setAtLeastTarget(communitym.getAccommodationTarget());//房屋配套保底目标
                targetFwpt.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceTargetService.insertTargetSelective(targetFwpt);
            }

            //-------房屋配套
            //生活团购实际值，生活团购结构系数
            PerformanceScore scoreShtg = new PerformanceScore();
            scoreShtg.setYear(year);
            //scoreShtg.setQuarterly("6");//年度指标
            scoreShtg.setQuarterly(quarter);//设置季度指标
            scoreShtg.setHierarchyId(hierarchyId);
            scoreShtg.setElementId(elementShtg);
            PerformanceScore sValueShtg = performanceScoreService.getscoreByHierarchyId(scoreShtg);
            /////////////////////////////////////////
            // 生活团购结构系数
            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
            }
            ///////////////////////////////////////
            if (sValueShtg != null) {
                try {
                    sValueShtg.setComplete(Float.valueOf(communitym.getGroupBuyingActual()));//生活团购实际值
                } catch (NumberFormatException e) {
                    sValueShtg.setComplete(-1);//生活团购实际值
                }

                sValueShtg.setScore((float) groupBuyingRatio);//生活团购结构系数

                sValueShtg.setUpdateDate(new Date());//修改日期
                performanceScoreService.updateScoreSelective(sValueShtg);
            } else {
                try {
                    scoreShtg.setComplete(Float.valueOf(communitym.getGroupBuyingActual()));//生活团购实际值
                } catch (NumberFormatException e) {
                    scoreShtg.setComplete(-1);//生活团购实际值
                }

                scoreShtg.setScore((float) groupBuyingRatio);//生活团购结构系数

                scoreShtg.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceScoreService.insertScoreSelective(scoreShtg);
            }
            //生活团购保底目标
            PerformanceTarget targetShtg = new PerformanceTarget();
            targetShtg.setYear(year);
//            targetShtg.setQuarterly("6");//年度指标
            targetShtg.setQuarterly(quarter);//设置季度指标
            targetShtg.setHierarchyId(hierarchyId);
            targetShtg.setElementId(elementShtg);
            PerformanceTarget tValueShtg = performanceTargetService.getByHierarchyId(targetShtg);
            if (tValueShtg != null) {
                tValueShtg.setAtLeastTarget(communitym.getGroupBuyingTarget());//生活团购保底目标
                tValueShtg.setUpdateDate(new Date());//修改日期
                performanceTargetService.updateTargetSelective(tValueShtg);
            } else {
                targetShtg.setAtLeastTarget(communitym.getGroupBuyingTarget());//生活团购保底目标
                targetShtg.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceTargetService.insertTargetSelective(targetShtg);
            }

            //-------社区广告
            //社区广告实际值，社区广告结构系数
            PerformanceScore scoreSqgg = new PerformanceScore();
            scoreSqgg.setYear(year);
            //scoreSqgg.setQuarterly("6");//年度指标
            scoreSqgg.setQuarterly(quarter);//设置季度指标
            scoreSqgg.setHierarchyId(hierarchyId);
            scoreSqgg.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
            }
            /////////////////////////////
            PerformanceScore sValueSqgg = performanceScoreService.getscoreByHierarchyId(scoreSqgg);
            if (sValueSqgg != null) {
                try {
                    sValueSqgg.setComplete(Float.valueOf(communitym.getAdvertisementActual()));//社区广告实际值
                } catch (NumberFormatException e) {
                    sValueSqgg.setComplete(-1);//社区广告实际值
                }

                sValueSqgg.setScore((float) advertisementRatio);//社区广告结构系数

                sValueSqgg.setUpdateDate(new Date());//修改日期
                performanceScoreService.updateScoreSelective(sValueSqgg);
            } else {
                try {
                    scoreSqgg.setComplete(Float.valueOf(communitym.getAdvertisementActual()));//社区广告实际值
                } catch (NumberFormatException e) {
                    scoreSqgg.setComplete(-1);//社区广告实际值
                }

                scoreSqgg.setScore((float) advertisementRatio);//社区广告结构系数

                scoreSqgg.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceScoreService.insertScoreSelective(scoreSqgg);
            }
            //社区广告保底目标
            PerformanceTarget targetSqgg = new PerformanceTarget();
            //设置年/季/区/考核指标
            targetSqgg.setYear(year);
            //targetSqgg.setQuarterly("6");//年度指标
            targetSqgg.setQuarterly(quarter);//设置季度指标
            targetSqgg.setHierarchyId(hierarchyId);
            targetSqgg.setElementId(elementSqgg);
            PerformanceTarget tValueSqgg = performanceTargetService.getByHierarchyId(targetSqgg);
            if (tValueSqgg != null) {
                tValueSqgg.setAtLeastTarget(communitym.getAdvertisementTarget());//社区广告保底目标
                tValueSqgg.setUpdateDate(new Date());//修改日期
                performanceTargetService.updateTargetSelective(tValueSqgg);
            } else {
                targetSqgg.setAtLeastTarget(communitym.getAdvertisementTarget());//社区广告保底目标
                targetSqgg.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceTargetService.insertTargetSelective(targetSqgg);
            }

            //-------资源经营实际值
            //资源经营实际值，资源经营结构系数
            PerformanceScore scoreZyjy = new PerformanceScore();
            scoreZyjy.setYear(year);
//            scoreZyjy.setQuarterly("6");//年度指标
            scoreZyjy.setQuarterly(quarter);//季度指标
            scoreZyjy.setHierarchyId(hierarchyId);
            scoreZyjy.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
            }
            ////////////////////////////////////
            PerformanceScore sValueZyjy = performanceScoreService.getscoreByHierarchyId(scoreZyjy);
            if (sValueZyjy != null) {
                try {
                    sValueZyjy.setComplete(Float.valueOf(communitym.getResourceManagementActual()));//资源经营实际值
                } catch (NumberFormatException e) {
                    sValueZyjy.setComplete(-1);//资源经营实际值
                }

                sValueZyjy.setScore((float) resourceManagementRatio);//资源经营结构系数

                sValueZyjy.setUpdateDate(new Date());//修改日期
                performanceScoreService.updateScoreSelective(sValueZyjy);
            } else {
                try {
                    scoreZyjy.setComplete(Float.valueOf(communitym.getResourceManagementActual()));//资源经营实际值
                } catch (NumberFormatException e) {
                    scoreZyjy.setComplete(-1);//资源经营实际值
                }

                scoreZyjy.setScore((float) resourceManagementRatio);//资源经营结构系数

                scoreZyjy.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceScoreService.insertScoreSelective(scoreZyjy);
            }
            //资源经营保底目标
            PerformanceTarget targetZyjy = new PerformanceTarget();
            targetZyjy.setYear(year);
//            targetZyjy.setQuarterly("6");//年度指标
            targetZyjy.setQuarterly(quarter);//季度指标
            targetZyjy.setHierarchyId(hierarchyId);
            targetZyjy.setElementId(elementZyjy);
            PerformanceTarget tValueZyjy = performanceTargetService.getByHierarchyId(targetZyjy);
            if (tValueZyjy != null) {
                tValueZyjy.setAtLeastTarget(communitym.getResourceManagementTarget());//资源经营实际值
                tValueZyjy.setUpdateDate(new Date());//修改日期
                performanceTargetService.updateTargetSelective(tValueZyjy);
            } else {
                targetZyjy.setAtLeastTarget(communitym.getResourceManagementTarget());//资源经营实际值
                targetZyjy.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceTargetService.insertTargetSelective(targetZyjy);
            }

            //-----业务结构系数
            //////////////////////////////////////////
            //业务结构系数
            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);
            }
            //////////////////////////////////////////
            PerformanceTarget targetYwjg = new PerformanceTarget();
            //设置performanceTarget要保存的数据
            //设置年/季/区/考核指标
            targetYwjg.setYear(year);
            //targetYwjg.setQuarterly("6");//年度指标
            targetYwjg.setQuarterly(quarter);//季度指标
            targetYwjg.setHierarchyId(hierarchyId);
            targetYwjg.setElementId(elementYwjg);
            PerformanceTarget tValueYwjg = performanceTargetService.getByHierarchyId(targetYwjg);
            if (tValueYwjg != null) {

                tValueYwjg.setStructParam(String.format("%.2f", structulRatio / 100));//业务结构系数

                tValueYwjg.setUpdateDate(new Date());//修改日期
                performanceTargetService.updateTargetSelective(tValueYwjg);
            } else {

                targetYwjg.setStructParam(String.format("%.2f", structulRatio / 100));//业务结构系数

                targetYwjg.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceTargetService.insertTargetSelective(targetYwjg);
            }
            PerformanceScore scoreYwjg = new PerformanceScore();
            scoreYwjg.setYear(year);
            //targetYwjg.setQuarterly("6");//年度指标
            scoreYwjg.setQuarterly(quarter);//按照季度指标来
            scoreYwjg.setHierarchyId(communitym.getHierarchyId());
            scoreYwjg.setElementId(elementYwjg);

            PerformanceScore sValueYwjg = performanceScoreService.getscoreByHierarchyId(scoreYwjg);
            if (sValueYwjg != null) {
                sValueYwjg.setScore(Float.parseFloat(String.format("%.2f", structulRatio / 100)));
                sValueYwjg.setComplete(Float.parseFloat(String.format("%.2f", structulRatio / 100)));
                sValueYwjg.setUpdateDate(new Date());
                performanceScoreService.updateScoreSelective(sValueYwjg);
            } else {
                scoreYwjg.setScore(Float.parseFloat(String.format("%.2f", structulRatio / 100)));
                scoreYwjg.setComplete(Float.parseFloat(String.format("%.2f", structulRatio / 100)));
                scoreYwjg.setCreatedDate(new Date());//创建日期

                performanceScoreService.insertScoreSelective(scoreYwjg);
            }

            //--------社区增值服务-细项得分
            //////////////////////////////////////////////////
            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(),lrdb);
                cva_score = new BigDecimal(cva_score * structulRatio / 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();     //增值服务得分* 结构系数
            }
            communitym.setCva_score(String.valueOf(cva_score));//要返回给前端的值
            /////////////////////////////////////////////////
            PerformanceScore scoreSqzzfw = new PerformanceScore();
            //设置performanceScore要保存的数据
            scoreSqzzfw.setYear(year);
//            scoreSqzzfw.setQuarterly("6");//年度指标
            scoreSqzzfw.setQuarterly(quarter);//季度指标
            scoreSqzzfw.setHierarchyId(hierarchyId);
            scoreSqzzfw.setElementId(elementSqzzfw);

            PerformanceScore sValueSqzzfw = performanceScoreService.getscoreByHierarchyId(scoreSqzzfw);
            if (sValueSqzzfw != null) {
                sValueSqzzfw.setScore((float) cva_score);//细项得分
                sValueSqzzfw.setUpdateDate(new Date());//修改日期
                performanceScoreService.updateScoreSelective(sValueSqzzfw);
            } else {
                scoreSqzzfw.setScore((float) cva_score);//细项得分
                scoreSqzzfw.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceScoreService.insertScoreSelective(scoreSqzzfw);
            }

            //-----房屋租售税前利润
            //实际值
            PerformanceScore scoreFwsq = new PerformanceScore();
            scoreFwsq.setYear(year);
//            scoreFwsq.setQuarterly("6");//年度指标
            scoreFwsq.setQuarterly(quarter);//季度指标
            scoreFwsq.setHierarchyId(hierarchyId);
            scoreFwsq.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) {
                }
            }
            ////////////////////////////////////////////////////////
            PerformanceScore sValueFwsq = performanceScoreService.getscoreByHierarchyId(scoreFwsq);
            if (sValueFwsq != null) {
                try {
                    sValueFwsq.setComplete(Float.valueOf(communitym.getHrspp_actual()));//房屋租售税前利润: 实际值
                } catch (NumberFormatException e) {
                    sValueFwsq.setComplete(-1);//房屋租售税前利润: 实际值
                }
                if (temp_score_Fwsq != null) {
                    try {
                        sValueFwsq.setScore(Float.valueOf(temp_score_Fwsq));
                    } catch (Exception e) {
                        sValueFwsq.setScore(-1);
                    }
                } else {
                    sValueFwsq.setScore(-1);
                }
                sValueFwsq.setUpdateDate(new Date());//修改日期
                performanceScoreService.updateScoreSelective(sValueFwsq);
            } else {
                try {
                    scoreFwsq.setComplete(Float.valueOf(communitym.getHrspp_actual()));//房屋租售税前利润: 实际值
                } catch (NumberFormatException e) {
                    scoreFwsq.setComplete(-1);//房屋租售税前利润: 实际值
                }
                if (temp_score_Fwsq != null) {
                    try {
                        scoreFwsq.setScore(Float.valueOf(temp_score_Fwsq));
                    } catch (Exception e) {
                        scoreFwsq.setScore(-1);
                    }
                } else {
                    scoreFwsq.setScore(-1);
                }
                scoreFwsq.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceScoreService.insertScoreSelective(scoreFwsq);
            }
            //目标值
            PerformanceTarget targetFwsq = new PerformanceTarget();
            targetFwsq.setYear(year);
            //targetFwsq.setQuarterly("6");//年度指标
            targetFwsq.setQuarterly(quarter);//季度指标
            targetFwsq.setHierarchyId(hierarchyId);
            targetFwsq.setElementId(elementFwsq);

            PerformanceTarget tValueFwsq = performanceTargetService.getByHierarchyId(targetFwsq);
            if (tValueFwsq != null) {
                tValueFwsq.setThresholdTarget(communitym.getHrspp_threshold());//房屋租售税前利润: 门槛值
                tValueFwsq.setAtLeastTarget(communitym.getHrspp_atLeast());//房屋租售税前利润: 保底
                tValueFwsq.setScreamTarget(communitym.getHrspp_scream());//房屋租售税前利润: 尖叫
                tValueFwsq.setHowlTarget(communitym.getHrspp_howl());//房屋租售税前利润: 嚎叫
                tValueFwsq.setUpdateDate(new Date());//修改日期
                performanceTargetService.updateTargetSelective(tValueFwsq);
            } else {
                targetFwsq.setThresholdTarget(communitym.getHrspp_threshold());//房屋租售税前利润: 门槛值
                targetFwsq.setAtLeastTarget(communitym.getHrspp_atLeast());//房屋租售税前利润: 保底
                targetFwsq.setScreamTarget(communitym.getHrspp_scream());//房屋租售税前利润: 尖叫
                targetFwsq.setHowlTarget(communitym.getHrspp_howl());//房屋租售税前利润: 嚎叫
                targetFwsq.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceTargetService.insertTargetSelective(targetFwsq);
            }

            //市场占有率
            PerformanceScore scoreFcjysc = new PerformanceScore();
            PerformanceTarget targetFcjysc = new PerformanceTarget();
            scoreFcjysc.setYear(year);
            //scoreFcjysc.setQuarterly("6");//年度指标
            scoreFcjysc.setQuarterly(quarter);//季度指标
            scoreFcjysc.setHierarchyId(hierarchyId);
            scoreFcjysc.setElementId(elementFcjysc);

            targetFcjysc.setYear(year);
            //scoreFcjysc.setQuarterly("6");//年度指标
            targetFcjysc.setQuarterly(quarter);//按照季度指标来
            targetFcjysc.setHierarchyId(communitym.getHierarchyId());
            targetFcjysc.setElementId(elementFcjysc);

            PerformanceScore sValueFcjysc = performanceScoreService.getscoreByHierarchyId(scoreFcjysc);
            if (sValueFcjysc != null) {
                try {
                    sValueFcjysc.setComplete(Float.valueOf(communitym.getMo_actual()));//市场占有率实际值
                } catch (NumberFormatException e) {
                    sValueFcjysc.setComplete(-1);//市场占有率实际值
                }
                try {
                    sValueFcjysc.setScore((float) bazaars(communitym.getMo_actual(), communitym.getMo_target()));//市场占有率目标值
                } catch (NumberFormatException e) {
                    sValueFcjysc.setScore(-1);//市场占有率目标值
                }
                sValueFcjysc.setUpdateDate(new Date());//修改日期
                performanceScoreService.updateScoreSelective(sValueFcjysc);
            } else {
                try {
                    scoreFcjysc.setComplete(Float.valueOf(communitym.getMo_actual()));//市场占有率实际值
                } catch (NumberFormatException e) {
                    scoreFcjysc.setComplete(-1);//市场占有率实际值
                }
                try {
                    scoreFcjysc.setScore((float) bazaars(communitym.getMo_actual(), communitym.getMo_target()));//市场占有率目标值
                } catch (NumberFormatException e) {
                    scoreFcjysc.setScore(-1);//市场占有率目标值
                }
                scoreFcjysc.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceScoreService.insertScoreSelective(scoreFcjysc);
            }

            PerformanceTarget tValueFcjysc = performanceTargetService.getNewByHierarchyId(targetFcjysc);
            if (tValueFcjysc != null) {
                tValueFcjysc.setAtLeastTarget(communitym.getMo_target());//市场占有率目标值
                performanceTargetService.updateTargetSelective(tValueFcjysc);
            } else {
                targetFcjysc.setAtLeastTarget(communitym.getMo_target());
                performanceTargetService.insertTargetSelective(targetFcjysc);
            }

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

            double annual = Calculate.Year(scores[0], scores[1], scores[2], scores[3]);

            PerformanceScore scoreKpgz = new PerformanceScore();
            scoreKpgz.setYear(year);
            scoreKpgz.setQuarterly(quarter);//第一季度指标
            scoreKpgz.setHierarchyId(hierarchyId);
            scoreKpgz.setElementId(elementKpgz);

            PerformanceScore sValueKpgz = performanceScoreService.getscoreByHierarchyId(scoreKpgz);
            if (sValueKpgz != null) {
                try {
                    sValueKpgz.setComplete(Float.valueOf(scores[q - 1]));
                    sValueKpgz.setScore((float) annual);//年度
                } catch (NumberFormatException e) {
                    sValueKpgz.setComplete(-1);
                }
                sValueKpgz.setUpdateDate(new Date());//修改日期
                performanceScoreService.updateScoreSelective(sValueKpgz);
            } else {
                try {
                    scoreKpgz.setComplete(Float.valueOf(scores[q - 1]));
                    scoreKpgz.setScore((float) annual);//年度
                } catch (NumberFormatException e) {
                    scoreKpgz.setComplete(-1);//第一季度
                }
                scoreKpgz.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceScoreService.insertScoreSelective(scoreKpgz);
                //重新校验为0
            }

            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(),null);
            }
            // 市场占有率
            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));//返回给前端
            ////////////////////////////////////////
            PerformanceScore scoreFczs = new PerformanceScore();
            scoreFczs.setYear(year);
//            scoreFczs.setQuarterly("6");//年度指标
            scoreFczs.setQuarterly(quarter);//季度指标
            scoreFczs.setHierarchyId(hierarchyId);
            scoreFczs.setElementId(elementFczs);

            PerformanceScore sValueFczs = performanceScoreService.getscoreByHierarchyId(scoreFczs);
            if (sValueFczs != null) {
                sValueFczs.setScore((float) hrs_score);//房屋租售服务 细项得分
                sValueFczs.setUpdateDate(new Date());//修改日期
                performanceScoreService.updateScoreSelective(sValueFczs);
            } else {
                scoreFczs.setScore((float) hrs_score);//房屋租售服务 细项得分
                scoreFczs.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceScoreService.insertScoreSelective(scoreFczs);
            }

            //-----------居者乐
            //居者乐实际值，细项得分
            PerformanceScore scoreJzlgs = new PerformanceScore();
            scoreJzlgs.setYear(year);
            //scoreJzlgs.setQuarterly("6");//年度指标
            scoreJzlgs.setQuarterly(quarter);//季度指标
            scoreJzlgs.setHierarchyId(hierarchyId);
            scoreJzlgs.setElementId(elementJzlgs);
            PerformanceScore sValueJzlgs = performanceScoreService.getscoreByHierarchyId(scoreJzlgs);
            ////////////////////////
            // 居者乐细项得分
            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(),null);
            }
            communitym.setJzl_score(String.valueOf(jzl_score));//返回给前端
            ///////////////////////
            if (sValueJzlgs != null) {
                try {
                    sValueJzlgs.setComplete(Float.valueOf(communitym.getJzl_actual()));//居者乐公司服务协作: 实际值
                } catch (NumberFormatException e) {
                    sValueJzlgs.setComplete(-1);//居者乐公司服务协作: 实际值
                }
                sValueJzlgs.setScore((float) jzl_score);//居者乐公司服务协作: 得分

                sValueJzlgs.setUpdateDate(new Date());//修改日期
                performanceScoreService.updateScoreSelective(sValueJzlgs);
            } else {
                try {
                    scoreJzlgs.setComplete(Float.valueOf(communitym.getJzl_actual()));//居者乐公司服务协作: 实际值
                } catch (NumberFormatException e) {
                    scoreJzlgs.setComplete(-1);//居者乐公司服务协作: 实际值
                }
                scoreJzlgs.setScore((float) jzl_score);//居者乐公司服务协作: 得分
                scoreJzlgs.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceScoreService.insertScoreSelective(scoreJzlgs);
            }

            //居者乐公司服务协作
            PerformanceTarget targetJzlgsfwxz = new PerformanceTarget();
            targetJzlgsfwxz.setYear(year);
            //targetJzlgsfwxz.setQuarterly("6");//年度指标
            targetJzlgsfwxz.setQuarterly(quarter);// 季度指标
            targetJzlgsfwxz.setHierarchyId(hierarchyId);
            targetJzlgsfwxz.setElementId(elementJzlgs);
            PerformanceTarget tValueJzlgsfwxz = performanceTargetService.getByHierarchyId(targetJzlgsfwxz);
            if (tValueJzlgsfwxz != null) {
                tValueJzlgsfwxz.setThresholdTarget(communitym.getJzl_threshold());//居者乐公司服务协作: 门槛值
                tValueJzlgsfwxz.setAtLeastTarget(communitym.getJzl_atLeast());//居者乐公司服务协作: 保底
                tValueJzlgsfwxz.setScreamTarget(communitym.getJzl_scream());//居者乐公司服务协作: 尖叫
                tValueJzlgsfwxz.setHowlTarget(communitym.getJzl_howl());//居者乐公司服务协作: 嚎叫
                tValueJzlgsfwxz.setUpdateDate(new Date());//修改日期
                performanceTargetService.updateTargetSelective(tValueJzlgsfwxz);
            } else {
                targetJzlgsfwxz.setThresholdTarget(communitym.getJzl_threshold());//居者乐公司服务协作: 门槛值
                targetJzlgsfwxz.setAtLeastTarget(communitym.getJzl_atLeast());//居者乐公司服务协作: 保底
                targetJzlgsfwxz.setScreamTarget(communitym.getJzl_scream());//居者乐公司服务协作: 尖叫
                targetJzlgsfwxz.setHowlTarget(communitym.getJzl_howl());//居者乐公司服务协作: 嚎叫
                targetJzlgsfwxz.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceTargetService.insertTargetSelective(targetJzlgsfwxz);
            }

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

            if (communitym.getIsCheck().equals("0")) {
                totalScore = -1;
            }
            communitym.setTotalScore(String.valueOf(totalScore));//返回给前端
            //////////////////////////
            PerformanceScore scoreSqjyff = new PerformanceScore();
            //设置performanceScore要保存的数据
            scoreSqjyff.setYear(year);
//            scoreSqjyff.setQuarterly("6");//年度指标
            scoreSqjyff.setQuarterly(quarter);//季度指标
            scoreSqjyff.setHierarchyId(hierarchyId);
            scoreSqjyff.setElementId(elementIdSqjyff);

            PerformanceScore sValueSqjyff = performanceScoreService.getscoreByHierarchyId(scoreSqjyff);
            if (sValueSqjyff != null) {
                sValueSqjyff.setScore((float) totalScore);//指标单项得分
                sValueSqjyff.setUpdateDate(new Date());//修改日期
                performanceScoreService.updateScoreSelective(sValueSqjyff);
            } else {
                scoreSqjyff.setScore((float) totalScore);//指标单项得分
                scoreSqjyff.setCreatedDate(new Date());//创建日期
                //执行插入操作
                performanceScoreService.insertScoreSelective(scoreSqjyff);
            }

            ///////////////////
            PerformanceTarget targetSqjyff = new PerformanceTarget();
            targetSqjyff.setElementId(elementIdSqjyff);
            targetSqjyff.setYear(year);
            targetSqjyff.setQuarterly(quarter);
            targetSqjyff.setHierarchyId(hierarchyId);

            targetSqjyff.setThresholdTarget(null);
            targetSqjyff.setAtLeastTarget(null);
            targetSqjyff.setScreamTarget(null);
            targetSqjyff.setHowlTarget(null);

            PerformanceTarget tValueSqjyff = performanceTargetService.getByHierarchyId(targetSqjyff);
            if(tValueSqjyff != null){
                tValueSqjyff.setIsCheck(communitym.getIsCheck());
                tValueSqjyff.setUpdateDate(new Date());
                performanceTargetService.updateTargetSelective(tValueSqjyff);
            }else{
                targetSqjyff.setIsCheck(communitym.getIsCheck());
                targetSqjyff.setWeight(0.15);
                targetSqjyff.setCreatedDate(new Date());
                performanceTargetService.insertTargetSelective(targetSqjyff);
            }

            result.add(communitym);
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("list", result);
        List<PerformanceEnv> envList = PerformanceEnvService.selectPerformanceOrgan();
        int count = envList.size();
        PerformanceScore performanceScore = new PerformanceScore();
        performanceScore.setYear(Integer.parseInt(values.get(0).getYear()));//年
        performanceScore.setQuarterly(values.get(0).getQuarterly());//季度
        performanceScore.setElementId(elementIdSqjyff);
        int vacancy = count - performanceScoreService.getTotalPage(performanceScore).getTotalPage();//空缺，还有多少个区域指标没填
        if (vacancy < 0) {
            vacancy = 0;
        }

        performanceScoreService.saveQuartlyAverageScoreAndSumScore(Integer.parseInt(values.get(0).getYear()), Integer.parseInt(values.get(0).getQuarterly()));
        map.put("vacancy", vacancy);//设置空缺数据
        List<String> vacancyHierarchyName = PerformanceEnvService.selectNotInName(performanceScore);
        map.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
        return Response.response(map);
    }

    // 居者乐单项得分
    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;
        if(Double.isNaN(result) || Double.isInfinite(result)){
            result = 0.0;
        }
        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 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 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 arithmetic(String value, String thresholdTarget, String atLeastTarget, String screamTarget,
                             String howlTarget,String lrdb) {
        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<0){
        	//实际值小于0
        	result = 0;
        }else if(values>0){
         if (values < thresholdTargets) {
        	 // 低于门槛值
            if(lrdb.equals("是")){
       		 result = 50;
       	 	}else{
       	 	 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();
    }

    @ResponseBody
    @RequestMapping(value = "/upload", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result upload(@RequestParam(value = "year") int year, @RequestParam(value = "quarter") int quarter,
                         @RequestParam(value = "name") String name,
                         @RequestParam(value = "uploadfile", required = true) MultipartFile multipartFile,
                         HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        if (multipartFile == null) {
            throw new ServiceException("请选择需要上传的文件");
        } else if (name == null) {
            throw new ServiceException("请输入文件名");
        }
        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
        if (commonsMultipartFile.isEmpty()) {
            return Response.responseFail("上传文件为空文件");
        }
        String fileName = commonsMultipartFile.getOriginalFilename();
        if (fileName.indexOf(".xlsx") <= 0 || fileName.indexOf(".xls") <= 0) {
            return Response.responseFail("上传文件应为excel文件格式为：xlsx 或 xls");
        }
        try {
            ea.communityManageUpload(multipartFile, year, quarter, token.getUserCode());
            performanceScoreService.saveQuartlyAverageScoreAndSumScore(year, quarter);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Response.response("导入成功");
    }

    /**
     * 查询和更新解锁状态，handle=1表示查询，handle=2表示更新
     *
     * @param requestMap json
     * @return Object
     * @author Max
     */
    @ResponseBody
    @RequestMapping(value = "/judgeLock")
    public Object judgeLock(@RequestBody Map<String, Object> requestMap, HttpServletRequest request) {
        String elementId = "1006";
        return Response.response(performancePower.getUserPower(elementId,requestMap,request));
    }

}
