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.AssessmentTargetService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceEnvService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceScoreService;

import cn.com.countrygarden.bi.main.service.performance.UserTargetService;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 安全消防事故
 *
 * @author zhaolie
 * @date 2018年6月12日
 */

/**
 * modify by white
 *
 * @Description: 修改返回总的页数 totalPage 在此之前返回的是每页的个数
 * @Date: 2018-06-27 16:07
 */


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

    @ResponseBody
    @RequestMapping(value = "/showAccidents", method = {RequestMethod.POST, RequestMethod.GET})
    public Object showAccidents(@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 = 1013;//一级id 安全生产、消防责任事故
        long elementId2 = 1013001;//二级id 事故数量

        List<Accidents> accidentsList = 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(year);//年
        performanceScore.setQuarterly(thisQuarter);//季度
        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++) {
                Accidents accidents = new Accidents();
                accidents.setHierarchyId(envList.get(i).getHierarchyId());//组织id
                accidents.setSecond_organization(envList.get(i).getHierarchyName());//二级组织
                accidents.setThird_organization(envList.get(i).getHierarchyName());//三级组织
                accidents.setYear(String.valueOf(year));//设置年份
                accidents.setQuarter(quarterly);
                accidents.setHierarchyname(envList.get(i).getHierarchyName());//获取区域的名字
                //----------事故数量
                //score表里的相关记录
                PerformanceScore scores = new PerformanceScore();
                scores.setYear(year);//年
                scores.setQuarterly(thisQuarter);//季度
                scores.setHierarchyId(envList.get(i).getHierarchyId());//区域
                scores.setElementId(elementId1);//二级id 事故数量
                PerformanceScore score1 = performanceScoreService.getscoreByHierarchyId(scores);
                if (score1 != null) {
                    accidents.setCount(String.valueOf(score1.getComplete()));
                }

                //----------加减分
                PerformanceScore scores2 = new PerformanceScore();
                scores2.setYear(year);//年
                scores2.setQuarterly(thisQuarter);//季度
                scores2.setHierarchyId(envList.get(i).getHierarchyId());//区域
                scores2.setElementId(elementId1);//一级id 安全生产、消防责任事故
                PerformanceScore score2 = performanceScoreService.getscoreByHierarchyId(scores2);
                if (score2 != null) {
                    accidents.setPlus_OR_Less(String.valueOf(score2.getScore()));
                }

                accidentsList.add(accidents);
            }
            map.put("list", accidentsList);
            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 = "/AccidentsCal", method = {RequestMethod.POST, RequestMethod.GET})
    public Object TotalCalculate(@RequestBody List<Accidents> Accidents) {
        Map<String, Object> map = new HashMap<>();
        List<PerformanceScore> scores = new ArrayList<PerformanceScore>();
        long elementId1 = 1013;//一级id 安全生产、消防责任事故
//        long elementId2 = 1013001;//二级id 事故数量
        int count;//事故数量
        int plus_OR_Less; //加减分
        PerformanceScore score = new PerformanceScore();
        PerformanceScore Countscore = new PerformanceScore();
        PerformanceScore Countscore1 = new PerformanceScore();
        PerformanceScore Acciscore = new PerformanceScore();
        PerformanceScore Acciscore1 = new PerformanceScore();
        for (int i = 0; i < Accidents.size(); i++) {
            try {
                count = Integer.valueOf(Accidents.get(i).getCount());
            } catch (NumberFormatException e) {
                count = 0;
            }
            plus_OR_Less = 2 * count;
            if (plus_OR_Less >= 10) {
                plus_OR_Less = 10;
            }
            plus_OR_Less = -plus_OR_Less;
            Accidents.get(i).setPlus_OR_Less(String.valueOf(plus_OR_Less));
            //设置好数据就开始入库
            //先设置好事故数量
            Countscore.setElementId(elementId1);//事故数量
            Countscore.setHierarchyId(Accidents.get(i).getHierarchyId());//按这个区域插
            Countscore.setYear(Integer.parseInt(Accidents.get(i).getYear()));//按年度
            Countscore.setQuarterly(Accidents.get(i).getQuarter());//是根据季度考核的
            Countscore.setComplete(count);//最终的得分是录入 1101的score字段的
            Countscore.setScore(plus_OR_Less);
            Countscore1 = performanceScoreService.getscoreByHierarchyId(Countscore);

            if (Countscore1 == null) {
                performanceScoreService.insertScoreSelective(Countscore);
            } else {
                performanceScoreService.UpdateNewScore(Countscore);
            }
        }
        map.put("list", Accidents);
        List<PerformanceEnv> envList = performanceEnvService.selectPerformanceOrgan();
        int counts = envList.size();
        PerformanceScore performanceScore = new PerformanceScore();
        performanceScore.setYear(Integer.parseInt(Accidents.get(0).getYear()));//年
        performanceScore.setQuarterly(Accidents.get(0).getQuarter());//季度
        performanceScore.setElementId(elementId1);
        int vacancy = counts - performanceScoreService.getTotalPage(performanceScore).getTotalPage();//空缺，还有多少个区域指标没填
        if (vacancy < 0) {
            vacancy = 0;
        }

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

    /**
     * @Author: Create by white
     * @Description: 消防责任事故excel导入接口
     * @Date: 2018-06-30 19:30
     * @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") String 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.accidentsUpload(multipartFile, year, quarterly, token.getUserCode());
            performanceScoreService.saveQuartlyAverageScoreAndSumScore(year, Integer.parseInt(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 = "1013";
        return Response.response(performancePower.getUserPower(elementId,requestMap,request));
    }
}

