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

import cn.com.countrygarden.bi.main.core.Response;
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.PerformanceEnvService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceScoreService;
import cn.com.countrygarden.bi.main.util.Arith;
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 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.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//入室内盗窃

/**
 * modify by white
 *
 * @Description: [add] 添加季度参数的传递 quarterly
 * [modify] 修改页数totalPage 在此之前返回的是每页的个数
 * @Date: 2018-06-27 16:28
 */

@Controller("BurglaryController")
@RequestMapping("/BurglaryController")
public class BurglaryController {
    @Autowired
    private cn.com.countrygarden.bi.main.service.performance.PerformanceTargetService PerformanceTargetService;
    @Autowired
    private PerformanceScoreService performanceScoreService;
    @Autowired
    private AccessTokenService accessTokenService;
    @Autowired
    private PerformanceEnvService performanceEnvService;
    @Autowired
    private ExcelAnalysis excelAnalysis;
    @Autowired
    private  PerformancePower performancePower;

    @ResponseBody
    @RequestMapping(value = "/showBurglary", method = {RequestMethod.POST, RequestMethod.GET})
    public Object showBurglary(@RequestParam(value = "pageSize") int pageSize, @RequestParam(value = "pageCurr") int pageCurr,
                               @RequestParam(value = "years") int year, @RequestParam(value = "quarterly") String quarterly) {
        Map<String, Object> map = new HashMap<>();
        long elementId1 = 1012;//一级id 入室盗窃案案发
        long elementId2 = 1012001;//二级id 入室盗窃案案发数量
        long elementId3 = 1012002;//二级id 入室盗窃案导致人员伤亡案件数
        long elementId4 = 1012003;//二级id 期末接管户数
        long elementId5 = 1012004;//二级id 折算任期户数
        long elementId6 = 1012005;//二级id 入室盗窃案案发率

        int totalPage = 0;
        PerformanceScore score = new PerformanceScore();
        List<BurglaryIncident> Burglarys = new ArrayList<BurglaryIncident>();//存放信息返回前端
        List<PerformanceScore> Scores = new ArrayList<PerformanceScore>();//查出有多少个
        score.setElementId(elementId1);
        score.setYear(year);
        score.setPageCur((pageCurr - 1) * pageSize);
        score.setPageSize(pageSize);
        score.setQuarterly(quarterly);
//        Scores=performanceScoreService.selectList(score);//没分页
        PerformanceScore score2 = performanceScoreService.getTotalPage(score);
        if (score2 != null) {
//            totalPage = score2.getTotalPage();
//            totalPage = (score2.getTotalPage()%pageSize == 0) ? score2.getTotalPage()/pageSize:score2.getTotalPage()/pageSize+1;
        }

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

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

        envList = envList.subList(start < 0 ? 0 : start, end >= count ? count : end);
        if (envList.size() != 0) {
            for (int i = 0; i < envList.size(); i++) {
                PerformanceScore score1 = new PerformanceScore();
                BurglaryIncident burglaryIncident = new BurglaryIncident();
                burglaryIncident.setHierarchyId(envList.get(i).getHierarchyId());
                burglaryIncident.setSecond_organization(envList.get(i).getHierarchyName());
                burglaryIncident.setThird_organization(envList.get(i).getHierarchyName());
                burglaryIncident.setQuarter(quarterly);
                burglaryIncident.setYear(String.valueOf(year));
                burglaryIncident.setHierarchyname(envList.get(i).getHierarchyName());
                //入室盗窃案案发数量
                score.setElementId(elementId2);
                score.setYear(year);
                score.setQuarterly(quarterly);
                score.setHierarchyId(envList.get(i).getHierarchyId());
                score1 = performanceScoreService.getscoreByHierarchyId(score);
                if (score1 != null) {
                    burglaryIncident.setBurglaryIncident_Count(String.valueOf(score1.getComplete()));
                }
                //入室盗窃案导致人员伤亡案件数
                score.setElementId(elementId3);
                score1 = performanceScoreService.getscoreByHierarchyId(score);
                if (score1 != null) {
                    burglaryIncident.setHurt_OR_Dead(String.valueOf(score1.getComplete()));
                }

                //期末接管户数
                score.setElementId(elementId4);
                score1 = performanceScoreService.getscoreByHierarchyId(score);
                if (score1 != null) {
                    burglaryIncident.setFinal_Count(String.valueOf(score1.getComplete()));
                }

                //折算任期户数
                score.setElementId(elementId5);
                score1 = performanceScoreService.getscoreByHierarchyId(score);
                if (score1 != null) {
                    burglaryIncident.setCal_Count(String.valueOf(score1.getComplete()));
                }

                //入室盗窃案案发率
                score.setElementId(elementId6);
                score1 = performanceScoreService.getscoreByHierarchyId(score);
                if (score1 != null) {
                    float rate = score1.getComplete();
                    //BigDecimal bd = new BigDecimal(rate);
                    //burglaryIncident.setRate(String.valueOf(bd));
                    //burglaryIncident.setRate(String.valueOf(rate));
                    DecimalFormat df = new DecimalFormat();
                    String style = "0.00000";//要显示的格式
                    df.applyPattern(style);// 将格式应用于格式化器
                    burglaryIncident.setRate(df.format(rate));
                    //burglaryIncident.setRate(String.valueOf(new BigDecimal(rate).setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue()));
                }

                //插入得分
                score.setElementId(elementId1);
                score1 = performanceScoreService.getscoreByHierarchyId(score);
                if (score1 != null) {
                    burglaryIncident.setPlus_OR_Less(String.valueOf(score1.getScore()));
                }
                Burglarys.add(burglaryIncident);
            }
            map.put("totalPage", totalPage);
            map.put("list", Burglarys);
            map.put("vacancy", vacancy);
            map.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
        }
        return Response.response(map);
    }

    //入室盗窃计算入库接口
    @ResponseBody
    @RequestMapping(value = "/BurglaryCal", method = {RequestMethod.POST, RequestMethod.GET})
    public Object BurglaryCal(@RequestBody List<BurglaryIncident> BurglaryIncident) {
        Map<String, Object> map = new HashMap<>();
        List<PerformanceScore> scores = new ArrayList<PerformanceScore>();
        long elementId1 = 1012;//一级id 入室盗窃案案发
        long elementId2 = 1012001;//二级id 入室盗窃案案发数量
        long elementId3 = 1012002;//二级id 入室盗窃案导致人员伤亡案件数
        long elementId4 = 1012003;//二级id 期末接管户数
        long elementId5 = 1012004;//二级id 折算任期户数
        long elementId6 = 1012005;//二级id 入室盗窃案案发率
        //组织
        String Second_organization;    //二级组织
        String Third_organization;     //三级组织
        //入室盗窃案案发
        double BurglaryIncident_Count;//入室盗窃案案发数量
        double Hurt_OR_Dead; //入室盗窃案导致人员伤亡案件数
        double final_Count;   //期末接管户数
        double rate; //入室盗窃案案发率
        double cal_Count;//折算任期户数
        double plus_OR_Less; // 加减分
        String hierarchyname;// 区域名称
        PerformanceScore Bscore = new PerformanceScore();//案发
        PerformanceScore Dscore = new PerformanceScore();//死的
        PerformanceScore score = new PerformanceScore();//加减分
        PerformanceScore Rscore = new PerformanceScore();//案发率
        PerformanceScore Cscore = new PerformanceScore();//折算任期户数
        PerformanceScore Fscore = new PerformanceScore();//期末接管户数
        PerformanceScore Bscore1 = new PerformanceScore();//黄的
        PerformanceScore Dscore1 = new PerformanceScore();//红的
        PerformanceScore score1 = new PerformanceScore();//加减分
        PerformanceScore Rscore1 = new PerformanceScore();//案发率
        PerformanceScore Fscore1 = new PerformanceScore();//期末接管户数
        PerformanceScore Cscore1 = new PerformanceScore();//折算任期户数
        try {
            for (BurglaryIncident incident : BurglaryIncident) {
                //入室盗窃案发数量
                BurglaryIncident BI = new BurglaryIncident();
                BurglaryIncident_Count = Double.valueOf(incident.getBurglaryIncident_Count());//入室盗窃案案发数量
                Hurt_OR_Dead = Double.valueOf( incident.getHurt_OR_Dead());//入室盗窃案导致人员伤亡案件数
                final_Count = Double.valueOf( incident.getFinal_Count());//期末接管户数
                cal_Count = Double.valueOf( incident.getCal_Count());//折算任期户数
                //rate=Double.parseDouble(BurglaryIncident.get(i).getRate());//入室盗窃案案发率
                plus_OR_Less = Calculate.CalBurglary(BurglaryIncident_Count, Hurt_OR_Dead, cal_Count);//加减法
                rate = new BigDecimal(cal_Count == 0 ? 0 : Arith.div(BurglaryIncident_Count , cal_Count)).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();//计算案发率
                incident.setPlus_OR_Less(String.valueOf(plus_OR_Less));
                //设置案发率返回值
//                System.out.println(rate);
                incident.setRate(String.valueOf(rate));
                ////////////以下进入入库和放重复update操作,入库的内容有 案发数目，伤亡数
                ///////////////////////案发数
                Bscore.setElementId(elementId2);//1案发数
                Bscore.setHierarchyId(incident.getHierarchyId());//按这个区域插
                Bscore.setYear(Integer.parseInt(incident.getYear()));//按年度
                Bscore.setQuarterly(incident.getQuarter());//入室盗窃看成是年度考核
                Bscore.setComplete((float) BurglaryIncident_Count);//最终的得分是录入 1101的score字段的
                scores.add(Bscore);
                Bscore1 = performanceScoreService.getscoreByHierarchyId(scores.get(0));
                scores.clear();//清除
                ///////////////////2.死
                Dscore.setElementId(elementId3);//
                Dscore.setHierarchyId(incident.getHierarchyId());//按这个区域插
                Dscore.setYear(Integer.parseInt(incident.getYear()));//按年度
                Dscore.setQuarterly(incident.getQuarter());//
                Dscore.setComplete((float) Hurt_OR_Dead);//完成值字段
                scores.add(Dscore);
                Dscore1 = performanceScoreService.getscoreByHierarchyId(scores.get(0));
                scores.clear();//清除
                ///////////////////3.期末接管户数
                Fscore.setElementId(elementId4);//
                Fscore.setHierarchyId(incident.getHierarchyId());//按这个区域插
                Fscore.setYear(Integer.parseInt(incident.getYear()));//按年度
                Fscore.setQuarterly(incident.getQuarter());//
                Fscore.setComplete((float) final_Count);//完成值字段
                scores.add(Fscore);
                Fscore1 = performanceScoreService.getscoreByHierarchyId(scores.get(0));
                scores.clear();//清除
                ///////////////////4.折户
                Cscore.setElementId(elementId5);//
                Cscore.setHierarchyId(incident.getHierarchyId());//按这个区域插
                Cscore.setYear(Integer.parseInt(incident.getYear()));//按年度
                Cscore.setQuarterly(incident.getQuarter());//
                Cscore.setComplete((float) cal_Count);//完成值字段
                scores.add(Cscore);
                Cscore1 = performanceScoreService.getscoreByHierarchyId(scores.get(0));
                scores.clear();//清除
                ///////////////////5.案发率
                Rscore.setElementId(elementId6);//死id
                Rscore.setHierarchyId(incident.getHierarchyId());//按这个区域插
                Rscore.setYear(Integer.parseInt(incident.getYear()));//按年度
                Rscore.setQuarterly(incident.getQuarter());//
                Rscore.setComplete((float) rate);//完成值字段
                scores.add(Rscore);
                Rscore1 = performanceScoreService.getscoreByHierarchyId(scores.get(0));
                scores.clear();//清除
                /////////////6.分数
                score.setElementId(elementId1);//折算任期户数
                score.setHierarchyId(incident.getHierarchyId());//按这个区域插
                score.setYear(Integer.parseInt(incident.getYear()));//按年度
                score.setQuarterly(incident.getQuarter());//
                score.setScore((float) plus_OR_Less);//最终的得分是录入 1101的score字段的
                scores.add(score);
                score1 = performanceScoreService.getscoreByHierarchyId(scores.get(0));
                scores.clear();//清除
                
                if (score1 == null) {
                    performanceScoreService.insertScoreSelective(score);
                } else {
                    performanceScoreService.UpdateNewScore(score);
                }

                if (Dscore1 == null) {
                    performanceScoreService.insertScoreSelective(Dscore);
                } else {
                    performanceScoreService.UpdateNewScore(Dscore);
                }

                if (Bscore1 == null) {
                    performanceScoreService.insertScoreSelective(Bscore);
                } else {
                    performanceScoreService.UpdateNewScore(Bscore);
                }

                if (Fscore1 == null) {
                    performanceScoreService.insertScoreSelective(Fscore);
                } else {
                    performanceScoreService.UpdateNewScore(Fscore);
                }

                if (Cscore1 == null) {
                    performanceScoreService.insertScoreSelective(Cscore);
                } else {
                    performanceScoreService.UpdateNewScore(Cscore);
                }

                if (Rscore1 == null) {
                    performanceScoreService.insertScoreSelective(Rscore);
                } else {
                    performanceScoreService.UpdateNewScore(Rscore);
                }
//            if(score1==null&&Dscore1==null&&Bscore1==null&&Fscore==null&&Cscore==null&&Rscore==null){
//                List<PerformanceScore> list=new ArrayList<PerformanceScore>();
//                list.add(score);//加减分
//                list.add(Dscore);//死
//                list.add(Bscore);//案发
//                list.add(Fscore);//
//                list.add(Cscore);//
//                list.add(Rscore);//
//                performanceScoreService.insertScoreList(list);
//                list.clear();
//            }else {
//                performanceScoreService.UpdateNewScore(score);
//                performanceScoreService.UpdateNewScore(Dscore);
//                performanceScoreService.UpdateNewScore(Bscore);
//                performanceScoreService.UpdateNewScore(Fscore);
//                performanceScoreService.UpdateNewScore(Cscore);
//                performanceScoreService.UpdateNewScore(Rscore);
//            }
            }
            map.put("list", BurglaryIncident);
            List<PerformanceEnv> envList = performanceEnvService.selectPerformanceOrgan();
            int count = envList.size();
            PerformanceScore performanceScore = new PerformanceScore();
            performanceScore.setYear(Integer.parseInt(BurglaryIncident.get(0).getYear()));//年
            performanceScore.setQuarterly(BurglaryIncident.get(0).getQuarter());//季度
            performanceScore.setElementId(elementId1);
            int vacancy = count - performanceScoreService.getTotalPage(performanceScore).getTotalPage();//空缺，还有多少个区域指标没填
            if(vacancy<0){
                vacancy=0;
            }
            performanceScoreService.saveQuartlyAverageScoreAndSumScore(Integer.parseInt(BurglaryIncident.get(0).getYear()), Integer.parseInt(BurglaryIncident.get(0).getQuarter()));
            map.put("vacancy", vacancy);//设置空缺数据
            List<String> vacancyHierarchyName = performanceEnvService.selectNotInName(performanceScore);
            map.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
            return Response.response(map);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail("服务出现异常");
        }

    }

    /**
     * @Author: Create by white
     * @Description: 用于excel导入数据接口，入室盗窃案案发率
     * @Date: 2018-06-30 19:25
     * @Params: [year, quarterly, name, multipartFile, request, response]
     * @Return: java.lang.Object
     * @Throws:
     */
    @ResponseBody
    @RequestMapping(value = "/upload", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Object upload(@RequestParam(value = "year") int year,
                         @RequestParam(value = "quarter") int quarterly,
                         @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");
        }
        try {
            excelAnalysis.burglaryUpload(multipartFile, year, String.valueOf(quarterly), token.getUserCode());
            performanceScoreService.saveQuartlyAverageScoreAndSumScore(year,quarterly);
            return Response.response("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail("服务出现异常,请联系管理员");
        }

    }


    /**
     * 查询和更新解锁状态，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 = "1012";//一级id 入室盗窃案案发
        return Response.response(performancePower.getUserPower(elementId,requestMap,request));
    }
}
