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.PerformanceScoreService;

import cn.com.countrygarden.bi.main.util.ExcelAnalysis;
import cn.com.countrygarden.bi.main.util.PerformancePower;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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;

//红黄牌第一个接口 一级 1011； 品质黄牌1011001 ，品质红牌1011002
/**
 * modify by white
 * @Description: 修改返回页数totalPage，修改前返回的是每页的个数
 * @Date: 2018-06-27 10:58
 */

/**
 * @Author: modify by white
 * @Description: 添加excel导入接口
 * @Date: 2018-06-30 2:45
 */

@Controller("CardsController")
@RequestMapping("/CardsController")
public class CardsController {

    private static Logger logger = LoggerFactory.getLogger(CardsController.class);

    @Autowired
    private cn.com.countrygarden.bi.main.service.performance.PerformanceTargetService PerformanceTargetService;
    @Autowired
    private PerformanceScoreService performanceScoreService;
    @Autowired
    private cn.com.countrygarden.bi.main.service.performance.PerformanceEnvService PerformanceEnvService;
    @Autowired
    private AccessTokenService accessTokenService;
    @Autowired
    private ExcelAnalysis excelAnalysis;
    @Autowired
    private  PerformancePower performancePower;

    @ResponseBody
    @RequestMapping(value = "/showCards", method = {RequestMethod.POST, RequestMethod.GET})
    public Object showCards(@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 = 1011;//一级id 品质红黄牌数
        long elementId2 = 1011001;//二级id 品质黄牌
        long elementId3 = 1011002;//二级id 品质红牌

        PerformanceScore score = new PerformanceScore();
        List<QualityOFRYCards> Cards = new ArrayList<QualityOFRYCards>();//存放信息返回前端
        List<PerformanceScore> Scores = new ArrayList<PerformanceScore>();//查出数量遍历
        int totalPage = 0;

        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 (PerformanceEnv performanceEnv : envList) {
                PerformanceScore score1 = new PerformanceScore();
                QualityOFRYCards cards = new QualityOFRYCards();
                cards.setHierarchyId(performanceEnv.getHierarchyId());
                cards.setSecond_organization(performanceEnv.getHierarchyName());
                cards.setThird_organization(performanceEnv.getHierarchyName());
                cards.setHierarchyname(performanceEnv.getHierarchyName());
                cards.setQuarter(quarterly);
                cards.setYear(String.valueOf(year));
                //插入黄牌
                score.setElementId(elementId2);
                score.setYear(year);
                score.setHierarchyId(performanceEnv.getHierarchyId());
                score.setQuarterly(quarterly);
                score1 = performanceScoreService.getscoreByHierarchyId(score);
                if (score1 != null) {
                    cards.setYellowcards(String.valueOf(score1.getComplete()));
                }

                //插入红牌
                score.setQuarterly(quarterly);
                score.setElementId(elementId3);
                score.setHierarchyId(performanceEnv.getHierarchyId());
                score.setYear(year);
                score1 = performanceScoreService.getscoreByHierarchyId(score);
                if (score1 != null) {
                    cards.setRedcards(String.valueOf(score1.getComplete()));
                }

                //插入分数
                score.setYear(year);
                score.setElementId(elementId1);
                score.setQuarterly(quarterly);
                score.setHierarchyId(performanceEnv.getHierarchyId());
                score1 = performanceScoreService.getscoreByHierarchyId(score);
                if (score1 != null) {
                    cards.setPlus_OR_Less(String.valueOf(score1.getScore()));
                }
                Cards.add(cards);
            }
            map.put("totalPage", totalPage);
            map.put("list", Cards);
            map.put("vacancy", vacancy);
            map.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
        }
        return Response.response(map);
    }


    ///红黄牌计算入库接口
    @ResponseBody
    @RequestMapping(value = "/CardsCal", method = {RequestMethod.POST, RequestMethod.GET})
    public Object CardsCal(@RequestBody List<QualityOFRYCards> QualityOFRYCards) {
        Map<String, Object> map = new HashMap<>();
        //品质红黄牌数
        long elementId1 = 1011;//一级id 品质红黄牌数
        long elementId2 = 1011001;//二级id 品质黄牌
        long elementId3 = 1011002;//二级id 品质红牌
        int redcards=0;//红牌数
        int yellowcards=0;//黄牌数
        int plus_OR_Less; // 加减分
        PerformanceScore Yscore = new PerformanceScore();//黄的
        PerformanceScore Rscore = new PerformanceScore();//红的
        PerformanceScore score = new PerformanceScore();//加减分
        PerformanceScore Yscore1 = new PerformanceScore();//黄的
        PerformanceScore Rscore1 = new PerformanceScore();//红的
        PerformanceScore score1 = new PerformanceScore();//加减分
        for (QualityOFRYCards qualityOFRYCards : QualityOFRYCards) {
            if(qualityOFRYCards.getRedcards()!=null){
                redcards = Integer.valueOf(qualityOFRYCards.getRedcards());
            }
            if(qualityOFRYCards.getYellowcards()!=null){
                yellowcards = Integer.valueOf(qualityOFRYCards.getYellowcards());
            }
            String quarterly = qualityOFRYCards.getQuarter();
            plus_OR_Less = -(redcards * 2 + yellowcards);
            qualityOFRYCards.setPlus_OR_Less(String.valueOf(plus_OR_Less));
            ////////////以下进入入库和放重复update操作,入库的内容有 红牌数，黄牌数
            ///////////////////////1.黄牌数
            Yscore.setElementId(elementId2);//黄牌数id
            Yscore.setHierarchyId(qualityOFRYCards.getHierarchyId());//按这个区域插
            Yscore.setYear(Integer.parseInt(qualityOFRYCards.getYear()));//按年度
            Yscore.setQuarterly(quarterly);//黄红牌是根据季度考核的
            Yscore.setComplete(yellowcards);//最终的得分是录入 1101的score字段的
            Yscore1 = performanceScoreService.getscoreByHierarchyId(Yscore);
            ///////////////////2.红牌

            Rscore.setElementId(elementId3);//黄牌数id
            Rscore.setHierarchyId(qualityOFRYCards.getHierarchyId());//按这个区域插
            Rscore.setYear(Integer.parseInt(qualityOFRYCards.getYear()));//按年度
            Rscore.setQuarterly(quarterly);//黄红牌是根据季度考核的
            Rscore.setComplete(redcards);//最终的得分是录入 1101的score字段的
            Rscore1 = performanceScoreService.getscoreByHierarchyId(Rscore);
            /////////////3.分数

            score.setElementId(elementId1);//加减法id
            score.setHierarchyId(qualityOFRYCards.getHierarchyId());//按这个区域插
            score.setYear(Integer.parseInt(qualityOFRYCards.getYear()));//按年度
            score.setQuarterly(quarterly);//黄红牌是根据季度考核的
            score.setScore(plus_OR_Less);//最终的得分是录入 1101的score字段的
            score1 = performanceScoreService.getscoreByHierarchyId(score);

            if (score1 == null) {
                performanceScoreService.insertScoreSelective(score);
            } else {
                performanceScoreService.UpdateNewScore(score);
            }
            if (Yscore1 == null) {
                performanceScoreService.insertScoreSelective(Yscore);
            } else {
                performanceScoreService.UpdateNewScore(Yscore);
            }
            if (Rscore1 == null) {
                performanceScoreService.insertScoreSelective(Rscore);
            } else {
                performanceScoreService.UpdateNewScore(Rscore);
            }
        }
        map.put("list", QualityOFRYCards);
        List<PerformanceEnv> envList = PerformanceEnvService.selectPerformanceOrgan();
        int count = envList.size();
        PerformanceScore performanceScore = new PerformanceScore();
        performanceScore.setYear(Integer.parseInt(QualityOFRYCards.get(0).getYear()));//年
        performanceScore.setQuarterly(QualityOFRYCards.get(0).getQuarter());//季度
        performanceScore.setElementId(elementId1);
        int vacancy = count - performanceScoreService.getTotalPage(performanceScore).getTotalPage();//空缺，还有多少个区域指标没填
        if(vacancy<0){
            vacancy=0;
        }
        performanceScoreService.saveQuartlyAverageScoreAndSumScore(Integer.parseInt(QualityOFRYCards.get(0).getYear()), Integer.parseInt(QualityOFRYCards.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 10:22
     @Params: []
      * @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.cardsUpload(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 = "1011";//一级id 品质红黄牌数
        return Response.response(performancePower.getUserPower(elementId,requestMap,request));
    }

}
