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.util.*;

/*
 * 城市指标-物业服务费欠费追缴率
 * 2018/9/7
 * author:Wyman
 */
@Controller("CityPropertyArrearsRecoveryRateController")
@RequestMapping("/CityPropertyArrearsRecoveryRateController")
public class CityPropertyArrearsRecoveryRateController {

    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 elementId = 1018;//物业服务费欠费追缴率1018 写死

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

        try{
            //查询空缺的城市公司值和名称
            PerformanceScore performanceScore = new PerformanceScore();
            performanceScore.setElementId(elementId);
            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){
                //设置Score传入对象
                PerformanceScore score = new PerformanceScore();
                score.setElementId(elementId);
                score.setYear(years);
                //通过城市id、年份、季度、elementId查询返回的score对象
                PerformanceScore sScore = null;
                PerformanceTarget tTarget = null;

                //设置Target传入对象
                PerformanceTarget target = new PerformanceTarget();
                target.setElementId(elementId);
                target.setYear(years);

                for(int i = 0; i < envList.size(); i ++){
                    CityPropertyArrearsRecoveryRate c = new CityPropertyArrearsRecoveryRate();

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

                    //设置城市公司id
                    score.setHierarchyId(hierarchy_id);
                    target.setHierarchyId(hierarchy_id);

                    //S1-S4欠费追缴率
                    //start
                    for (int j = 1; j < 5; j++){
                        //设置季度
                        score.setQuarterly(String.valueOf(j));
                        target.setQuarterly(String.valueOf(j));

                        sScore = performanceScoreService.getscoreByHierarchyId(score);//通过id、指标id、年份季度查询得分值
                        tTarget = performanceTargetService.getByHierarchyId(target);////通过id、指标id、年份季度查询目标值
                        if(sScore != null && tTarget != null){//得分与目标值同时有才赋值
                            if (j == 1) {
                                c.setS1_threshold(tTarget.getThresholdTarget());//插入门槛
                                c.setS1_atLeast(tTarget.getAtLeastTarget());//插入保底
                                c.setS1_scream(tTarget.getScreamTarget());//插入尖叫
                                c.setS1_howl(tTarget.getHowlTarget());//插入嚎叫
                                c.setS1_complete(String.valueOf(sScore.getComplete())); //完成值
                                c.setS1_score(String.valueOf(sScore.getScore()));//得分
                            }
                            if (j == 2) {
                                c.setS2_threshold(tTarget.getThresholdTarget());//插入门槛
                                c.setS2_atLeast(tTarget.getAtLeastTarget());//插入保底
                                c.setS2_scream(tTarget.getScreamTarget());//插入尖叫
                                c.setS2_howl(tTarget.getHowlTarget());//插入嚎叫
                                c.setS2_complete(String.valueOf(sScore.getComplete())); //完成值
                                c.setS2_score(String.valueOf(sScore.getScore()));//得分
                            }
                            if (j == 3) {
                                c.setS3_threshold(tTarget.getThresholdTarget());//插入门槛
                                c.setS3_atLeast(tTarget.getAtLeastTarget());//插入保底
                                c.setS3_scream(tTarget.getScreamTarget());//插入尖叫
                                c.setS3_howl(tTarget.getHowlTarget());//插入嚎叫
                                c.setS3_complete(String.valueOf(sScore.getComplete())); //完成值
                                c.setS3_score(String.valueOf(sScore.getScore()));//得分
                            }
                            if (j == 4) {
                                c.setS4_threshold(tTarget.getThresholdTarget());//插入门槛
                                c.setS4_atLeast(tTarget.getAtLeastTarget());//插入保底
                                c.setS4_scream(tTarget.getScreamTarget());//插入尖叫
                                c.setS4_howl(tTarget.getHowlTarget());//插入嚎叫
                                c.setS4_complete(String.valueOf(sScore.getComplete())); //完成值
                                c.setS4_score(String.valueOf(sScore.getScore()));//得分
                            }

                            //设置单项指标得分与是否考核
                            if(quarterly.equals(String.valueOf(j))){//判断传入季度
                                c.setIndividualScore(String.valueOf(sScore.getScore()));
                                String isChecked = tTarget.getIsCheck();
                                if(StringUtil.isBlankOrEmpty(isChecked)){
                                    isChecked = "0";
                                }
                                c.setIs_check(isChecked.equals("1") ? 1 : 0);
                            }
                        }
                    }
                    returnList.add(c);
                    //end
                }
                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<CityPropertyArrearsRecoveryRate> cityPropertyArrearsRecoveryRates) {
        Map<String, Object> returnMap = new HashMap<>();
        List<CityPropertyArrearsRecoveryRate> returnList = new ArrayList<>();//返回的list

        long elementId = 1018L;//城市公司指标-物业服务费欠费追缴率1018 写死

        try{
            double weight = 0;
        for (CityPropertyArrearsRecoveryRate c : cityPropertyArrearsRecoveryRates) {

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

            //设置初始值
            double complete = -1;   // 完成值
            double threshold = -1;  // 门槛值
            double atLeast = -1;    // 保底
            double scream = -1;     // 尖叫
            double howl = -1;       // 嚎叫

            //null为占位对象
            String[] thresholds = {null,c.getS1_threshold(), c.getS2_threshold(), c.getS3_threshold(), c.getS4_threshold()};
            String[] atLasts = {null,c.getS1_atLeast(), c.getS2_atLeast(), c.getS3_atLeast(), c.getS4_atLeast()};
            String[] screams = {null,c.getS1_scream(), c.getS2_scream(), c.getS3_scream(), c.getS4_scream()};
            String[] howls = {null,c.getS1_howl(), c.getS2_howl(), c.getS3_howl(), c.getS4_howl()};
            String[] completes = {null,c.getS1_complete(), c.getS2_complete(), c.getS3_complete(), c.getS4_complete()};
            String[] scores = {null,"-1", "-1", "-1", "-1"};

            //设置传入score对象
            PerformanceScore score = new PerformanceScore();
            score.setHierarchyId(hierarchyId);//按这个区域插
            score.setYear(Integer.parseInt(year));//按年度
            score.setElementId(elementId);

            //设置传入target对象
            PerformanceTarget target = new PerformanceTarget();
            target.setHierarchyId(hierarchyId);
            target.setYear(Integer.valueOf(year));
            target.setElementId(elementId);

            for (int i = 1; i < 5; i++) {//S1-S4
                score.setQuarterly(String.valueOf(i));//设置季度
                target.setQuarterly(String.valueOf(i));
                //设置默认值
                //completes[i] = completes[i] == null ? "-1" : completes[i];

                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);//插入完成值
                        performanceScoreService.updateScoreSelective(sValue);
                    } else {
                        score.setComplete((float) complete);//插入完成值
                        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));
                        tValue.setWeight(weight);
                        performanceTargetService.updateTargetSelective(tValue);
                    } else {
                        target.setThresholdTarget(String.valueOf(atLeast));  //没有门槛值，门槛值跟保底值相等
                        target.setAtLeastTarget(String.valueOf(atLeast));
                        target.setScreamTarget(String.valueOf(scream));
                        target.setHowlTarget(String.valueOf(howl));
                        target.setWeight(weight);
                        performanceTargetService.insertTargetSelective(target);
                    }
                }
            }

            // 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 = null;

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

            //计算单项指标得分
            IndividualScore = Calculate.getCityPropertyArrearsRecoveryRateScore(S1_score,S2_score,S3_score,S4_score);
            if(StringUtil.isEmpty(IndividualScore)){
                IndividualScore = "-1";
            }

            //更新计算结果
            score.setQuarterly(quarter);


                //更新score值
                PerformanceScore sValue = performanceScoreService.getscoreByHierarchyId(score);
                if(sValue != null){
                    sValue.setScore(Float.parseFloat(IndividualScore));
                    performanceScoreService.updateScoreSelective(sValue);
                }

            //更新is_check值
            target.setQuarterly(quarter);
            PerformanceTarget tValue = performanceTargetService.getNewByHierarchyId(target);
            if(tValue != null){
                tValue.setIsCheck(String.valueOf(c.getIs_check()));
                performanceTargetService.updateTargetSelective(tValue);
            }

            //回传计算后的值
            c.setIndividualScore(IndividualScore);
            returnList.add(c);
        }
        returnMap.put("list",returnList);

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

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

    /**
     * 查询和更新解锁状态，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 = "1018";
        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.CityPropertyArrearsRecoveryRateUpload(multipartFile, year, quarter, token.getUserCode());
            performanceScoreService.saveQuartlyAverageScoreAndSumScore(year, quarter);
            return Response.response("导入成功");
        } catch (Exception e) {
            return Response.responseFail(e.getMessage());
        }

    }
}
