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

import java.util.*;

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.*;
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.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 cn.com.countrygarden.bi.main.core.Response;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

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

/**
 * modify by white
 *
 * @Description: [add] 添加参数季度quarterly
 * [modify] 修改查询返回总页数totalPage,在此之前返回的是PerformanceScore
 * @Date: 2018-06-26 14:27
 */

//停车收费
@Controller("ParkingCostControllerController")
@RequestMapping("/ParkingCostControllerController")
public class ParkingCostController {
    @Autowired
    private PerformanceTargetService PerformanceTargetService;
    @Autowired
    private PerformanceElementService PerformanceElementService;
    @Autowired
    private PerformanceScoreService PerformanceScoreService;
    @Autowired
    private PerformanceEnvService performanceEnvService;
    @Autowired
    private PerformanceTargetService performanceTargetService;
    @Autowired
    private AccessTokenService accessTokenService;
    @Autowired
    private ExcelAnalysis excelAnalysis;
    @Autowired
    private  PerformancePower performancePower;

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

        Map<String, Object> map = new HashMap<>();

        long elementId = 1014;
        long elementId1 = 1014001;//停车收费双百目标应实施数 停车收费双百目标已实施数
        long elementId2 = 1014002;//停车收费收入目标值  停车收费收入实际值

        List<ParkingCost> parkingCostList = new ArrayList<>();

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

        String thisQuarter = quarterly;

        //查询多少条数据是录入的
        PerformanceScore performanceScore = new PerformanceScore();
        performanceScore.setYear(years);//年
        performanceScore.setQuarterly(thisQuarter);//季度
        performanceScore.setElementId(elementId);
        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++) {
                ParkingCost parkingCost = new ParkingCost();
                parkingCost.setHierarchyId(envList.get(i).getHierarchyId());//组织id
                parkingCost.setSecond_organization(envList.get(i).getHierarchyName());//二级组织
                parkingCost.setThird_organization(envList.get(i).getHierarchyName());//三级组织
                parkingCost.setYear(years);//设置年份
                parkingCost.setQuarter(quarterly);

                //----------停车收费
                //score表里的相关记录
                PerformanceScore scores = new PerformanceScore();
                scores.setYear(years);//年
                scores.setQuarterly(thisQuarter);//季度
                scores.setHierarchyId(envList.get(i).getHierarchyId());//区域
                scores.setElementId(elementId);//停车收费
                PerformanceScore score1 = PerformanceScoreService.getscoreByHierarchyId(scores);
                if (score1 != null) {
                    parkingCost.setPlus_OR_Less((int) score1.getScore());
                }

                //----------停车收费双百
                //---应实施数
                PerformanceTarget t1 = new PerformanceTarget();
                t1.setYear(years);//年
                t1.setQuarterly(thisQuarter);//季度
                t1.setHierarchyId(envList.get(i).getHierarchyId());//区域
                t1.setElementId(elementId1);//停车收费双百
                PerformanceTarget t1Value = performanceTargetService.getByHierarchyId(t1);
                if (t1Value != null) {
                    parkingCost.setShould_Count(t1Value.getHowlTarget());//停车收费双百目标应实施数
                }
                //--已实施数
                PerformanceScore scoress = new PerformanceScore();
                scoress.setYear(years);//年
                scoress.setQuarterly(thisQuarter);//季度
                scoress.setHierarchyId(envList.get(i).getHierarchyId());//区域
                scoress.setElementId(elementId1);//停车收费
                PerformanceScore sss = PerformanceScoreService.getscoreByHierarchyId(scoress);
                if (sss != null) {
                    parkingCost.setDone_Count(String.valueOf(sss.getComplete())); //停车收费双百目标已实施数
                }

                //----------停车收费收入
                //---实际值
                PerformanceScore scoresj = new PerformanceScore();
                scoresj.setYear(years);//年
                scoresj.setQuarterly(thisQuarter);//季度
                scoresj.setHierarchyId(envList.get(i).getHierarchyId());//区域
                scoresj.setElementId(elementId2);//停车收费
                PerformanceScore ssj = PerformanceScoreService.getscoreByHierarchyId(scoresj);
                if (ssj != null) {
                    parkingCost.setRealIncome(String.valueOf(ssj.getComplete()));//停车收费收入实际值
                }

                //---目标值
                PerformanceTarget t2 = new PerformanceTarget();
                t2.setYear(years);//年
                t2.setQuarterly(thisQuarter);//季度
                t2.setHierarchyId(envList.get(i).getHierarchyId());//区域
                t2.setElementId(elementId2);//停车收费双百
                PerformanceTarget t2Value = performanceTargetService.getByHierarchyId(t2);
                if (t2Value != null) {
                    parkingCost.setPointIncome(t2Value.getHowlTarget());//停车收费双百目标应实施数
                }
                parkingCostList.add(parkingCost);
            }
            map.put("list", parkingCostList);
            map.put("totalPage", count);
            map.put("vacancy", vacancy);
        } else {
            map.put("list", null);
            map.put("totalPage", 0);
            map.put("vacancy", count);
        }
        map.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
        return Response.response(map);
    }

    // 停车收费计算
    @ResponseBody
    @RequestMapping(value = "/CountValue", method = {RequestMethod.POST, RequestMethod.GET})
    public Object TotalCalculate(@RequestBody List<ParkingCost> values) {
        PerformanceElement element = new PerformanceElement();// 停车收费
        Map<String, Object> map = new LinkedHashMap<String, Object>();// 返回值
        Map<String, Object> map1 = new LinkedHashMap<String, Object>();// 接收值
        // 获取一级id的list
        long elementid = 1014;// 停车收费
        PerformanceScore scores = new PerformanceScore();// 操作值
        element.setElementId(elementid);
        // 获取一级停车收费的id
        List<PerformanceElement> list2 = null;
        // 停车收费
        list2 = PerformanceElementService.getElementId(element);
        for (int i = 0; i < list2.size(); i++) {

            if (list2.get(i).getName().equals("双百完成率（小区车辆授权管控完成率100%、进出车辆收费完成率100%）")) {
                map1.put("双百完成率（小区车辆授权管控完成率100%、进出车辆收费完成率100%）", list2.get(i).getElementId());
            }
            if (list2.get(i).getName().equals("停车收费收入")) {
                map1.put("停车收费收入", list2.get(i).getElementId());
            }
        }
        try {
            List<PerformanceScore> scoreList = new ArrayList<>();
            for (int i = 0; i < values.size(); i++) {
                int should_Count = 0;
                int done_Count = 0;
                if (values.get(i).getShould_Count() != null && (!values.get(i).getShould_Count().equals(""))) {
                    should_Count = Integer.valueOf(values.get(i).getShould_Count());// 停车收费双百目标应实施数
                }
                if (values.get(i).getDone_Count() != null && (!values.get(i).getDone_Count().equals(""))) {
                    done_Count = Integer.valueOf(values.get(i).getDone_Count());// 停车收费双百目标已实施数
                }
                double realIncome = 0;// 实际收入
                String realIncome1 = values.get(i).getRealIncome();
                if (realIncome1 != null && !realIncome1.equals("")) {
                    realIncome = Double.parseDouble(realIncome1);
                }

                double pointIncome = 0;// 停车收费收入目标值
                String pointIncome1 = values.get(i).getPointIncome();
                if (pointIncome1 != null && !pointIncome1.equals("")) {
                    pointIncome = Double.parseDouble(pointIncome1);
                }
                int plus_OR_Less = values.get(i).getPlus_OR_Less(); // 加减分
                //modify by white
                //修改计算公式
                if (done_Count >= should_Count && realIncome >= pointIncome) {
                    plus_OR_Less = 0;
                } else {
                    plus_OR_Less = -3;
                }
//                if (done_Count  < should_Count && realIncome < pointIncome) {
//                    plus_OR_Less = plus_OR_Less - 3;
//                }
                values.get(i).setPlus_OR_Less(plus_OR_Less);// 设置计算结果返回值
                // modify by white
                // 判断数据库是否已经存在该数据，有则更新，没有则插入
                PerformanceScore score = new PerformanceScore();
                score.setYear(values.get(i).getYear());// 年度
                score.setElementId(elementid);//设置
                score.setYear(values.get(i).getYear());// 设置年份
                score.setHierarchyId(values.get(i).getHierarchyId());// 区域ID
                score.setScore(plus_OR_Less);// 计算结果入库值
                score.setQuarterly(values.get(i).getQuarter());//设计考核频率为‘年度’
                PerformanceScore score1 = PerformanceScoreService.getNewScore(score);
//                PerformanceScoreService.UpdateNewScore(scores);// 计算结果入库
                PerformanceScore scoreOfDone = new PerformanceScore();
                element.setElementId(Long.parseLong(map1.get("双百完成率（小区车辆授权管控完成率100%、进出车辆收费完成率100%）").toString()));
                scoreOfDone.setYear(values.get(i).getYear());// 年度
                scoreOfDone.setElementId(element.getElementId());// 对应的elemenid
                scoreOfDone.setYear(values.get(i).getYear());// 设置年份
                scoreOfDone.setHierarchyId(values.get(i).getHierarchyId());// 区域ID
                scoreOfDone.setComplete((float) done_Count);// 实际完成值
                scoreOfDone.setQuarterly(values.get(i).getQuarter());
                PerformanceScore score2 = PerformanceScoreService.getNewScore(scoreOfDone);
//                PerformanceScoreService.UpdateNewScore(scores);// 计算结果入库

                PerformanceTarget target = new PerformanceTarget();
                target.setYear(values.get(i).getYear());//设置年份
                target.setElementId(Long.parseLong(map1.get("双百完成率（小区车辆授权管控完成率100%、进出车辆收费完成率100%）").toString()));
                target.setHierarchyId(values.get(i).getHierarchyId());//设置区域ID
                target.setHowlTarget(String.valueOf(should_Count));//设置双百目标值
                target.setQuarterly(values.get(i).getQuarter());//设置季度
                PerformanceTarget targetOfShouldCount = PerformanceTargetService.getByHierarchyId(target);//获取判断是否有记录存在

                // 停车收费收入完成值
                PerformanceScore scoreOfRealInCome = new PerformanceScore();
                element.setElementId(Long.parseLong(map1.get("停车收费收入").toString()));
                scoreOfRealInCome.setYear(values.get(i).getYear());// 年度
                scoreOfRealInCome.setElementId(element.getElementId());// 对应的elemenid
                scoreOfRealInCome.setYear(values.get(i).getYear());// 设置年份
                scoreOfRealInCome.setHierarchyId(values.get(i).getHierarchyId());// 区域ID
                scoreOfRealInCome.setComplete((float) realIncome);// 完成值（实际值）
                scoreOfRealInCome.setQuarterly(values.get(i).getQuarter());//设置季度
                PerformanceScore score3 = PerformanceScoreService.getNewScore(scoreOfRealInCome);
//                PerformanceScoreService.UpdateNewScore(scores);// 计算结果入库

                //停车收费实际值，realIncome
                PerformanceTarget target2 = new PerformanceTarget();
                target2.setElementId(Long.parseLong(map1.get("停车收费收入").toString()));
                target2.setHierarchyId(values.get(i).getHierarchyId());
                target2.setYear(values.get(i).getYear());
                target2.setHowlTarget(String.valueOf(pointIncome));//设置停车收费目标值
                target2.setQuarterly(values.get(i).getQuarter());//设置季度
                PerformanceTarget targetOfPointIncome = PerformanceTargetService.getByHierarchyId(target2);//获取判断是否有记录存在

                //判断数据是否已经存在，有则更新，，没有则插入
                if (score1 == null) {
                    PerformanceScoreService.insertScoreSelective(score);
                } else {
                    PerformanceScoreService.UpdateNewScore(score);
                }
                if (score2 == null) {
                    PerformanceScoreService.insertScoreSelective(scoreOfRealInCome);
                } else {
                    PerformanceScoreService.UpdateNewScore(scoreOfRealInCome);
                }
                if (score3 == null) {
                    PerformanceScoreService.insertScoreSelective(scoreOfDone);
                } else {
                    PerformanceScoreService.UpdateNewScore(scoreOfDone);
                }

                if (targetOfShouldCount == null) {
                    PerformanceTargetService.insertTargetSelective(target);
                } else {
                    target.setTargetId(targetOfShouldCount.getTargetId());
                    PerformanceTargetService.updateTargetByTargetId(target);
                }

                if (targetOfPointIncome == null) {
                    PerformanceTargetService.insertTargetSelective(target2);
                } else {
                    target2.setTargetId(targetOfPointIncome.getTargetId());
                    PerformanceTargetService.updateTargetByTargetId(target2);
                }
            }
            map.put("list", values);
            List<PerformanceEnv> envList = performanceEnvService.selectPerformanceOrgan();
            int count = envList.size();
            PerformanceScore performanceScore = new PerformanceScore();
            performanceScore.setYear(values.get(0).getYear());//年
            performanceScore.setQuarterly(values.get(0).getQuarter());//季度
            performanceScore.setElementId(elementid);
            int vacancy = count - PerformanceScoreService.getTotalPage(performanceScore).getTotalPage();//空缺，还有多少个区域指标没填
            if (vacancy < 0) {
                vacancy = 0;
            }
            PerformanceScoreService.saveQuartlyAverageScoreAndSumScore(values.get(0).getYear(), Integer.parseInt(values.get(0).getQuarter()));
            map.put("vacancy", vacancy);//设置空缺数据
            List<String> vacancyHierarchyName = performanceEnvService.selectNotInName(performanceScore);
            map.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
            return Response.response(map);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return Response.responseFail("服务出现异常");
        }

    }

    /**
     * @Author: Create by white
     * @Description: 停车收费excel导入接口
     * @Date: 2018-06-30 19:34
     * @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.parkingCostUpload(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 = "1014";//停车收费
        return Response.response(performancePower.getUserPower(elementId,requestMap,request));
    }
}
