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

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.service.performance.PerformanceCompanyService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceScoreService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceTargetService;
import cn.com.countrygarden.bi.main.util.Calculate;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.*;

/*
 * 城市指标--物业服务费追缴率Controller
 */
@Controller("CityPropertyCollectionRateController")
@RequestMapping("/CityPropertyCollectionRateController")
public class CityPropertyCollectionRateController {

    Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PerformancePower performancePower;

    @Autowired
    private PerformanceScoreService performanceScoreService;

    @Autowired
    private PerformanceCompanyService performanceCompanyService;

    @Autowired
    private PerformanceTargetService performanceTargetService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private ExcelAnalysis ea;

    /**
     * 查询所有指标相关值
     * @param pageSize
     * @param pageCurr
     * @param years
     * @param quarterly
     * @return
     */
    @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){
        //城市公司指标--客户满意度编码
        long elementId1 = 1017;//物业服务费收缴率1017 写死
        long elementId2 = 1017001;//综合收缴率 写死
        long elementId3 = 1017002;//综合已收楼收缴率 写死

        Map<String,Object> returnMap = new LinkedHashMap<>();
        List<CityPropertyCollectionRate> returnList = new ArrayList<>();

        try {
            //查询空缺的城市公司值和名称
            PerformanceScore performanceScore = new PerformanceScore();
            performanceScore.setElementId(elementId1);
            performanceScore.setYear(years);
            performanceScore.setQuarterly(quarterly);
            List<String> vacancyHierarchyName = performanceCompanyService.selectNotInNameCompany(performanceScore);//空缺城市公司名称
            int vacancy = vacancyHierarchyName.size();//空缺值

            //查询城市公司的得分、目标值等
            List<PerformanceCompany> envList = performanceCompanyService.selectPerformanceCompany();
            int count = envList.size();//有效城市公司总数量
            int start = (pageCurr-1) * pageSize;
            int end = pageCurr * pageSize;
            envList = envList.subList(start < 0 ? 0 : start, end >= count ? count : end);//分页
                if (envList.size() != 0) {
                    for (int i = 0; i < envList.size(); i++) {
                        CityPropertyCollectionRate c = new CityPropertyCollectionRate();

                        c.setSecond_organization(envList.get(i).getHierarchyName());//二级组织
                        c.setThird_organization(envList.get(i).getHierarchyName());//三级组织

                        String hierarchy_id = envList.get(i).getHierarchyId();//城市公司id

                        c.setHierarchyId(hierarchy_id);
                        c.setYear(String.valueOf(years));
                        c.setQuarter(quarterly);

                        //综合收缴率
                        PerformanceTarget target = new PerformanceTarget();//传参的对象
                        target.setElementId(elementId2);//综合的id
                        target.setYear(years);
                        target.setQuarterly(quarterly);
                        target.setHierarchyId(hierarchy_id);
                        PerformanceTarget tValue = performanceTargetService.getNewByHierarchyId(target);
                        if (tValue != null) {
                            c.setCompre_threshold(tValue.getThresholdTarget());
                            c.setCompre_atLeast(tValue.getAtLeastTarget());
                            c.setCompre_scream(tValue.getScreamTarget());
                            c.setCompre_howl(tValue.getHowlTarget());
                        }

                        PerformanceScore score = new PerformanceScore();//传参的对象
                        score.setElementId(elementId2);
                        score.setHierarchyId(hierarchy_id);
                        score.setYear(years);
                        score.setQuarterly(quarterly);
                        PerformanceScore sValue = performanceScoreService.getscoreByHierarchyId(score);
                        if (sValue != null) {
                            c.setCompre_complete(String.valueOf(sValue.getComplete()));//综合收缴率完成值
                            c.setCompre_score(String.valueOf(sValue.getScore()));//综合收缴率细项得分
                        }

                        ////综合已收楼收缴率
                        //传入的指标id更改
                        target.setElementId(elementId3);
                        score.setElementId(elementId3);

                        //S1-S4已收楼收缴率
                        //[start]
                        for (int j = 1; j < 5; j++) {
                            target.setQuarterly(String.valueOf(j));
                            score.setQuarterly(String.valueOf(j));//季度

                            tValue = performanceTargetService.getNewByHierarchyId(target);//查出该id，该区域，该年度，该年份的目标值
                            sValue = performanceScoreService.getscoreByHierarchyId(score);//查询这个区域的得分
                            if (tValue != null && sValue != null) {
                                if (j == 1) {
                                    c.setS1_threshold(tValue.getThresholdTarget());//插入门槛
                                    c.setS1_atLeast(tValue.getAtLeastTarget());//插入保底
                                    c.setS1_scream(tValue.getScreamTarget());//插入尖叫
                                    c.setS1_howl(tValue.getHowlTarget());//插入嚎叫
                                    c.setS1_complete(String.valueOf(sValue.getComplete())); //完成值
                                    c.setS1_score(String.valueOf(sValue.getScore()));//得分
                                }
                                if (j == 2) {
                                    c.setS2_threshold(tValue.getThresholdTarget());//插入门槛
                                    c.setS2_atLeast(tValue.getAtLeastTarget());//插入保底
                                    c.setS2_scream(tValue.getScreamTarget());//插入尖叫
                                    c.setS2_howl(tValue.getHowlTarget());//插入嚎叫
                                    c.setS2_complete(String.valueOf(sValue.getComplete())); //完成值
                                    c.setS2_score(String.valueOf(sValue.getScore()));//得分
                                }
                                if (j == 3) {
                                    c.setS3_threshold(tValue.getThresholdTarget());//插入门槛
                                    c.setS3_atLeast(tValue.getAtLeastTarget());//插入保底
                                    c.setS3_scream(tValue.getScreamTarget());//插入尖叫
                                    c.setS3_howl(tValue.getHowlTarget());//插入嚎叫
                                    c.setS3_complete(String.valueOf(sValue.getComplete())); //完成值
                                    c.setS3_score(String.valueOf(sValue.getScore()));//得分
                                }
                                if (j == 4) {
                                    c.setS4_threshold(tValue.getThresholdTarget());//插入门槛
                                    c.setS4_atLeast(tValue.getAtLeastTarget());//插入保底
                                    c.setS4_scream(tValue.getScreamTarget());//插入尖叫
                                    c.setS4_howl(tValue.getHowlTarget());//插入嚎叫
                                    c.setS4_complete(String.valueOf(sValue.getComplete())); //完成值
                                    c.setS4_score(String.valueOf(sValue.getScore()));//得分
                                }
                            }
                        }
                        //[end]

                        //////////////查询单项指标得分
                        score.setElementId(elementId1);//设置id拿得分
                        score.setQuarterly(quarterly);//季度
                        sValue = performanceScoreService.getscoreByHierarchyId(score);//查询这个区域的得分
                        if (sValue != null) {
                            c.setIndividualScore(String.valueOf(sValue.getScore()));
                        }

                        //////////////////是否考核

                        target.setElementId(elementId1);
                        target.setQuarterly(quarterly);
                        tValue = performanceTargetService.getNewByHierarchyId(target);
                        if (tValue != null) {
                            c.setIs_check(tValue.getIsCheck().equals("1") ? 1 : 0);
                        } else {
                            c.setIs_check(1);
                        }
                        ////////////////////////////////////////
                        returnList.add(c);
                    }

                    returnMap.put("totalPage", count);
                    returnMap.put("list", returnList);
                    returnMap.put("vacancy", vacancy);
                    returnMap.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
                }
        }catch (Exception e){
            LOGGER.info(e.getMessage());
            return Response.response(e.getMessage());
        }
        return Response.response(returnMap);
    }

    @ResponseBody
    @RequestMapping(value = "/TotalCalculate", method = {RequestMethod.POST, RequestMethod.GET})
    public Object TotalCalculate(@RequestBody List<CityPropertyCollectionRate> cityPropertyCollectionRates){
         Map<String, Object> resultMap = new HashMap<>();
        List<CityPropertyCollectionRate> resultList = new ArrayList<>();

        long elementId1 = 1017L;//城市指标-物业服务费收缴率1017 写死
        long elementId2 = 1017001L;//综合收缴率
        long elementId3 = 1017002L;//综合已收楼收缴率
            try{
                double weight = 0;
                for(CityPropertyCollectionRate c : cityPropertyCollectionRates){//遍历

                    String hierarchyId = c.getHierarchyId();
                    String year = c.getYear();
                    String quarter = c.getQuarter();
                    String type = performanceCompanyService.getTypeByComId(hierarchyId);
                    switch (type){
                        case "单一业主项目":
                            weight = 0.2;
                            break;
                        case "多业主第一年":
                            weight = 0.2;
                            break;
                        case "多业主第二年":
                            weight = 0.2;
                            break;
                    }

                    //综合收缴率
                    double complete = -1;   // 完成值
                    double threshold = -1;  // 门槛值
                    double atLeast = -1;    // 保底
                    double scream = -1;     // 尖叫
                    double howl = -1;       // 嚎叫

                    String[] thresholds = {c.getCompre_threshold(), c.getS1_threshold(), c.getS2_threshold(), c.getS3_threshold(), c.getS4_threshold()};
                    String[] atLasts = {c.getCompre_atLeast(), c.getS1_atLeast(), c.getS2_atLeast(), c.getS3_atLeast(), c.getS4_atLeast()};
                    String[] screams = {c.getCompre_scream(), c.getS1_scream(), c.getS2_scream(), c.getS3_scream(), c.getS4_scream()};
                    String[] howls = {c.getCompre_howl(), c.getS1_howl(), c.getS2_howl(), c.getS3_howl(), c.getS4_howl()};
                    String[] completes = {c.getCompre_complete(), c.getS1_complete(), c.getS2_complete(), c.getS3_complete(), c.getS4_complete()};
                    String[] scores = {"-1", "-1", "-1", "-1", "-1"};

                    PerformanceScore score = new PerformanceScore();
                    score.setHierarchyId(hierarchyId);//按这个区域插
                    score.setYear(Integer.parseInt(year));//按年度

                    PerformanceTarget target = new PerformanceTarget();
                    target.setHierarchyId(hierarchyId);
                    target.setYear(Integer.valueOf(year));

                    label:
                    for(int i = 0; i < 5; i++){ //综合、S1-S4

                        switch (i) {
                            case 0: {           //综合
                                score.setElementId(elementId2);
                                score.setQuarterly(quarter);
                                target.setElementId(elementId2);
                                target.setQuarterly(quarter);
                                break;
                            }
                            default: {          //S1-S4
                                score.setElementId(elementId3);
                                score.setQuarterly(String.valueOf(i));
                                target.setElementId(elementId3);
                                target.setQuarterly(String.valueOf(i));
                                break;
                            }
                        }


                        if (!StringUtil.isBlankOrEmpty(completes[i])) {
                            try {
                                complete = Double.parseDouble(completes[i]);    // 完成值
                                atLeast = Double.parseDouble(atLasts[i]);       //  保底
                                scream = Double.parseDouble(screams[i]);        // :尖叫
                                howl = Double.parseDouble(howls[i]);            // :嚎叫
                            } catch (NumberFormatException e) {
                                //输入数据有误 直接return error不合适，计算成0值返回，各目标值初始化为-1
                                LOGGER.error("目标值输入有误：{},{},{},{}", completes[i], atLasts[i], screams[i], howls[i]);
                            }

                            // 计算出细项目得分综合收费，放入数组中，不设置门槛值
                            scores[i] = Calculate.InsertionMethod(complete, -1, atLeast, scream, howl, 1);

                            //插入计算的数据，和实际值
                            PerformanceScore sValue = performanceScoreService.getscoreByHierarchyId(score);//查询有没有这条记录
                            if (sValue != null) {
                                sValue.setComplete((float) complete);//插入实际值：就是完成值
                                sValue.setScore(Float.parseFloat(scores[i])); //综合收缴率细项得分
                                performanceScoreService.updateScoreSelective(sValue);
                            } else {
                                score.setComplete((float) complete);//插入实际值：就是完成值
                                score.setScore(Float.parseFloat(scores[i])); //综合收缴率细项得分
                                performanceScoreService.insertScoreSelective(score);

                            }

                            //更新目标值
                            PerformanceTarget tValue = performanceTargetService.getByHierarchyId(target);
                            if (tValue != null) {
                                tValue.setThresholdTarget(String.valueOf(atLeast));  //没有门槛值，门槛值跟保底值相等
                                tValue.setAtLeastTarget(String.valueOf(atLeast));
                                tValue.setScreamTarget(String.valueOf(scream));
                                tValue.setHowlTarget(String.valueOf(howl));
                                performanceTargetService.updateTargetSelective(tValue);
                            } else {
                                target.setThresholdTarget(String.valueOf(atLeast));  //没有门槛值，门槛值跟保底值相等
                                target.setAtLeastTarget(String.valueOf(atLeast));
                                target.setScreamTarget(String.valueOf(scream));
                                target.setHowlTarget(String.valueOf(howl));
                                performanceTargetService.insertTargetSelective(target);
                            }
                        }
                    }

                    //综合收缴率:细项目得分
                    String ZH_score = scores[0];
                    // S1综合已收楼缴率:细项目得分
                    String S1_score = scores[1];
                    // S2综合已收楼缴率:细项目得分
                    String S2_score = scores[2];
                    // S3综合已收楼缴率:细项目得分
                    String S3_score = scores[3];
                    // S4综合已收楼缴率:细项目得分
                    String S4_score = scores[4];
                    String IndividualScore = "-1";//指标总得分

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

                    //////////计算指标单项得分
                    IndividualScore = Calculate.getCityCostIndividualScore(ZH_score,S1_score,S2_score,S3_score,S4_score);

                    //以下插入计算结果，先查询是否存在同样数据是的update，否则insert
                    score.setElementId(elementId1);//按这个指标插入
                    score.setQuarterly(quarter);//第几季度

                    score.setScore(-1);
                    score.setComplete(-1);
                    PerformanceScore sValue = performanceScoreService.getscoreByHierarchyId(score);//查询有没有这条记录
                    if (sValue != null) {
                        sValue.setScore(Float.parseFloat(IndividualScore));//更新细项得分值
                        performanceScoreService.updateScoreSelective(sValue);
                    } else {
                        score.setScore(Float.parseFloat(IndividualScore));//插入的细项得分
                        performanceScoreService.insertScoreSelective(score);
                    }
                    target.setElementId(elementId1);
                    target.setQuarterly(quarter);

                    target.setThresholdTarget(null);
                    target.setAtLeastTarget(null);
                    target.setScreamTarget(null);
                    target.setHowlTarget(null);
                    PerformanceTarget tValue = performanceTargetService.getNewByHierarchyId(target);
                    if (tValue != null) {
                        tValue.setIsCheck(String.valueOf(c.getIs_check()));
                        tValue.setWeight(weight);
                        performanceTargetService.updateTargetSelective(tValue);
                    } else {
                        target.setWeight(weight);
                        target.setIsCheck(String.valueOf(c.getIs_check()));
                        performanceTargetService.insertTargetSelective(target);
                    }
                    //回传计算后的值
                    c.setIndividualScore(IndividualScore);
                    resultList.add(c);
                }
                resultMap.put("list", resultList);

                PerformanceScore performanceScore = new PerformanceScore();
                performanceScore.setYear(Integer.parseInt(cityPropertyCollectionRates.get(0).getYear()));//年
                performanceScore.setQuarterly(cityPropertyCollectionRates.get(0).getQuarter());//季度
                performanceScore.setElementId(elementId1);
                List<String> vacancyHierarchyName = performanceCompanyService.selectNotInNameCompany(performanceScore);
                int vacancy = vacancyHierarchyName.size();//空缺，还有多少个城市指标没填

                performanceScoreService.saveQuartlyAverageScoreAndSumScore(Integer.parseInt(cityPropertyCollectionRates.get(0).getYear()), Integer.parseInt(cityPropertyCollectionRates.get(0).getQuarter()));
                resultMap.put("vacancy", vacancy);//设置空缺数据
                resultMap.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
            }catch (Exception e){
                LOGGER.info(e.getMessage());
            }
        return Response.response(resultMap);

    }


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

    @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) {
            return Response.responseFail("请选择需要上传的文件");
        } else if (name == null) {
            return Response.responseFail("请输入文件名");
        }
        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");
        }
        if (!fileName.contains("收缴率")) {
            return Response.responseFail("请选择正确的文件！");
        }
        try {
            ea.CityPropertyCollectionRateUpload(multipartFile, year, quarter, token.getUserCode());
            performanceScoreService.saveQuartlyAverageScoreAndSumScore(year, quarter);
            return Response.response("导入成功");
        } catch (Exception e) {
            LOGGER.info(e.getMessage());
            return Response.responseFail(e.getMessage());
        }

    }
}
