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

/**
 * @Author: white
 * @Date: create in 2018-06-29 19:23
 * @Description: 媒体曝光或群诉
 * @Modify_By:
 */
@RequestMapping(value = "NegativeEffectiveController")
@Controller(value = "NegativeEffectiveController")
public class NegativeeffectiveController {

    private Logger logger = LoggerFactory.getLogger(NegativeeffectiveController.class);

    @Autowired
    private PerformanceTargetService PerformanceTargetService;
    @Autowired
    private PerformanceElementService PerformanceElementService;
    @Autowired
    private PerformanceScoreService PerformanceScoreService;
    @Autowired
    private PerformanceEnvService performanceEnvService;
    @Autowired
    private AccessTokenService accessTokenService;
    @Autowired
    private ExcelAnalysis excelAnalysis;
    @Autowired
    private  PerformancePower performancePower;

    /**
     * @Author: Create by white
     * @Description: 用于获取媒体曝光或投诉的数据 并返回给前端
     * @Date: 2018-06-29 19:57
     * @Params: [pageCurr, pageSize, years, quarterly]
     * @Return: java.lang.Object
     * @Throws:
     */
    @ResponseBody
    @RequestMapping(value = "/NegativeEffective", method = {RequestMethod.GET, RequestMethod.POST})
    public Object showTarget(@RequestParam(value = "pageCurr") int pageCurr,
                             @RequestParam(value = "pageSize") int pageSize,
                             @RequestParam(value = "years") int years,
                             @RequestParam(value = "quarterly") String quarterly) {
        //用于返回到前端的map
        Map<String, Object> map = new HashMap<>();
        //创建list 用于存放数据库中获取到的数据
        List<PerformanceScore> scoreList = new ArrayList<>();
        long elementId = 1015;//一级id 媒体曝光
        long elementId1 = 1015001;//二级id 未按标准流程妥善处理
        long elementId2 = 1015002;//二级id 地方媒体报道事件
        long elementId3 = 1015003;//二级id 中央媒体报道事件
        long elementId4 = 1015004;//二级id 广泛媒体报道事件
        //构造查询条件score
        PerformanceScore score = new PerformanceScore();
        //创建list用于存放数据给前端
        List<NegativeEffective> negativeEffectiveList = new LinkedList<>();
        //totalPage用于返回总页数
        int totalPage = 0;
        //创建区域相关对象，用于获取区域名
        PerformanceEnv performanceEnv = new PerformanceEnv();

        //设置查询条件
        score.setQuarterly(quarterly);
        score.setYear(years);
        score.setPageCur((pageCurr - 1) * pageSize);
        score.setPageSize(pageSize);
        score.setElementId(elementId);
        try {
            //获取总的页数
            PerformanceScore totalPageScore = PerformanceScoreService.getTotalPage(score);
            //判断获取的页数是否是整数 是的话直接返回 否的话加1返回
            if (totalPageScore != null) {
                totalPage = totalPageScore.getTotalPage();
//                totalPage = (totalPageScore.getTotalPage() % pageSize == 0) ? totalPageScore.getTotalPage() / pageSize : totalPageScore.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(years);//年
            performanceScore.setQuarterly(quarterly);//季度
            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++) {
                    PerformanceScore score1 = new PerformanceScore();
                    NegativeEffective negativeEffective = new NegativeEffective();
                    negativeEffective.setHierarchyId(envList.get(i).getHierarchyId());
                    negativeEffective.setSecond_organization(envList.get(i).getHierarchyName());
                    negativeEffective.setThird_organization(envList.get(i).getHierarchyName());
                    negativeEffective.setQuarter(quarterly);
                    negativeEffective.setElementId(elementId);
                    negativeEffective.setYear(years);
                    //查找分数并插入分数，即加减分
                    score.setElementId(elementId);//构造查询的指标id
                    score.setQuarterly(quarterly);//设置季度
                    score.setYear(years);//设置年份
                    score.setHierarchyId(envList.get(i).getHierarchyId());//设置区域id
                    score1 = PerformanceScoreService.getscoreByHierarchyId(score);
                    if (score1 != null) {
                        negativeEffective.setPlus_OR_Less(String.valueOf(score1.getScore()));
                    }

                    //查找 ‘未按标准流程妥善处理’ 指标项 并插入到数据库
                    score.setElementId(elementId1);
                    score.setHierarchyId(envList.get(i).getHierarchyId());
                    score1 = PerformanceScoreService.getscoreByHierarchyId(score);
                    if (score1 != null) {
                        negativeEffective.setOutStandard(String.valueOf(score1.getComplete()));
                    }

                    //查找 ‘地方媒体报道事件’ 指标项并返回到前端
                    score.setElementId(elementId2);
                    score.setHierarchyId(envList.get(i).getHierarchyId());
                    score1 = PerformanceScoreService.getscoreByHierarchyId(score);
                    if (score1 != null) {
                        negativeEffective.setLocation(String.valueOf(score1.getComplete()));
                    }

                    //查找 ‘中央媒体报道事件’ 指标项并返回到前端
                    score.setElementId(elementId3);
                    score.setHierarchyId(envList.get(i).getHierarchyId());
                    score1 = PerformanceScoreService.getscoreByHierarchyId(score);
                    if (score1 != null) {
                        negativeEffective.setCenter(String.valueOf(score1.getComplete()));
                    }

                    //查找 ‘广泛媒体报道事件’ 指标项并返回到前端
                    score.setElementId(elementId4);
                    score.setHierarchyId(envList.get(i).getHierarchyId());
                    score1 = PerformanceScoreService.getscoreByHierarchyId(score);
                    if (score1 != null) {
                        negativeEffective.setSpread(String.valueOf(score1.getComplete()));
                    }
                    //拼接到的negativeEffective放入到list中
                    negativeEffectiveList.add(negativeEffective);
                }
                map.put("list", negativeEffectiveList);
                map.put("totalPage", totalPage);
                map.put("vacancy", vacancy);
                map.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
            }
            return Response.response(map);
        } catch (Exception e) {
            //捕获异常
            //返回前台服务异常
            e.printStackTrace();
            return Response.responseFail("服务出项异常");
        }
    }

    /**
     * @Author: Create by white
     * @Description: 用于媒体曝光自动计算
     * @Date: 2018-06-29 21:10
     * @Params: [values]
     * @Return: java.lang.Object
     * @Throws:
     */
    @ResponseBody
    @RequestMapping(value = "/CountValue", method = {RequestMethod.GET, RequestMethod.POST})
    public Object countValue(@RequestBody List<NegativeEffective> values) {
        //用于返回到前端的map
        HashMap<String, Object> map = new HashMap<>();
        long elementId = 1015;//一级id 即媒体曝光或群诉
        long elementId1 = 1015001;//二级id  未按标准流程妥善处理
        long elementId2 = 1015002;//二级id  地方媒体报道事件
        long elementId3 = 1015003;//二级id  中央媒体报道事件
        long elementId4 = 1015004;//二级id  广泛媒体报道事件
        //加减分，未按标准流程妥善处理，地方媒体报道事件，中央媒体报道事件，广泛媒体报道事件
        //创建score 用于构造查询的条件
        PerformanceScore score = new PerformanceScore();
        //创建多个score,用于判断数据库是否有记录
        PerformanceScore plusOrLessScore = new PerformanceScore();
        PerformanceScore outStandardScore = new PerformanceScore();
        PerformanceScore locationScore = new PerformanceScore();
        PerformanceScore centerScore = new PerformanceScore();
        PerformanceScore spreadScore = new PerformanceScore();

        PerformanceScore plusOrLessScore1 = new PerformanceScore();
        PerformanceScore outStandardScore1 = new PerformanceScore();
        PerformanceScore locationScore1 = new PerformanceScore();
        PerformanceScore centerScore1 = new PerformanceScore();
        PerformanceScore spreadScore1 = new PerformanceScore();

        try {

            for (int i = 0; i < values.size(); i++) {
                int plus_or_less = -1, outStandard = -1, location = -1, center = -1, spread = -1;

//                NegativeEffective negativeEffective = new NegativeEffective();
                plus_or_less = 0;
                if (values.get(i).getOutStandard() != null) {
                    try {
                        outStandard = Integer.valueOf(values.get(i).getOutStandard());
                    } catch (NumberFormatException e) {
                        logger.error("=====NegativeeffectiveController.countValue=====outStandard:" + values.get(i).getOutStandard());
                    }
                }
                if (values.get(i).getLocation() != null) {
                    try {
                        location = Integer.valueOf(values.get(i).getLocation());
                    } catch (NumberFormatException e) {
                        logger.error("=====NegativeeffectiveController.countValue=====location:" + values.get(i).getLocation());
                    }
                }
                if (values.get(i).getCenter() != null) {
                    try {
                        center = Integer.valueOf(values.get(i).getCenter());
                    } catch (NumberFormatException e) {
                        logger.error("=====NegativeeffectiveController.countValue=====center:" + values.get(i).getCenter());
                    }
                }
                if (values.get(i).getSpread() != null) {
                    try {
                        spread = Integer.valueOf(values.get(i).getSpread());
                    } catch (NumberFormatException e) {
                        logger.error("=====NegativeeffectiveController.countValue=====spread:" + values.get(i).getSpread());
                    }
                }
                if (outStandard != -1) {
                    plus_or_less = outStandard * -3;
                }
                if (location != -1) {
                    plus_or_less = plus_or_less + location * -1;
                }
                if (center != -1) {
                    plus_or_less = plus_or_less + center * -2;
                }
                if (spread != -1) {
                    plus_or_less = plus_or_less + spread * -10;
                }
                values.get(i).setPlus_OR_Less(String.valueOf(plus_or_less));

                //查看分数是否为空 有则更新 否则插入
                plusOrLessScore.setElementId(elementId);
                plusOrLessScore.setHierarchyId(values.get(i).getHierarchyId());
                plusOrLessScore.setYear(values.get(i).getYear());
                plusOrLessScore.setQuarterly(values.get(i).getQuarter());
                plusOrLessScore.setScore(Float.valueOf(values.get(i).getPlus_OR_Less()));
                plusOrLessScore1 = PerformanceScoreService.getNewScore(plusOrLessScore);
                if (plusOrLessScore1 != null) {
                    PerformanceScoreService.UpdateNewScore(plusOrLessScore);
                } else {
                    PerformanceScoreService.insertScoreSelective(plusOrLessScore);
                }

                //查看 ‘未按标准流程妥善处理’ 是否存在 有则更新 没有则插入
                if (outStandard != -1) {
                    outStandardScore.setElementId(elementId1);
                    outStandardScore.setYear(values.get(i).getYear());
                    outStandardScore.setQuarterly(values.get(i).getQuarter());
                    outStandardScore.setHierarchyId(values.get(i).getHierarchyId());
                    outStandardScore.setComplete(outStandard);
                    outStandardScore1 = PerformanceScoreService.getNewScore(outStandardScore);
                    if (outStandardScore1 != null) {
                        PerformanceScoreService.UpdateNewScore(outStandardScore);
                    } else {
                        PerformanceScoreService.insertScoreSelective(outStandardScore);
                    }
                }

                //查看 ‘地方媒体报道事件’ 是否存在 有则更新 没有则插入
                if (location != -1) {
                    locationScore.setElementId(elementId2);
                    locationScore.setYear(values.get(i).getYear());
                    locationScore.setQuarterly(values.get(i).getQuarter());
                    locationScore.setHierarchyId(values.get(i).getHierarchyId());
                    locationScore.setComplete(location);
                    locationScore1 = PerformanceScoreService.getNewScore(locationScore);
                    if (locationScore1 != null) {
                        PerformanceScoreService.UpdateNewScore(locationScore);
                    } else {
                        PerformanceScoreService.insertScoreSelective(locationScore);
                    }
                }

                //查看 ‘中央媒体报道事件’ 是否存在 有则更新 没有则插入
                if (center != -1) {
                    centerScore.setElementId(elementId3);
                    centerScore.setYear(values.get(i).getYear());
                    centerScore.setQuarterly(values.get(i).getQuarter());
                    centerScore.setHierarchyId(values.get(i).getHierarchyId());
                    centerScore.setComplete(center);
                    centerScore1 = PerformanceScoreService.getNewScore(centerScore);
                    if (centerScore1 != null) {
                        PerformanceScoreService.UpdateNewScore(centerScore);
                    } else {
                        PerformanceScoreService.insertScoreSelective(centerScore);
                    }
                }

                if (spread != -1) {
                    //查看 ‘广泛媒体报道事件’ 是否存在 有则更新 没有则插入
                    spreadScore.setElementId(elementId4);
                    spreadScore.setYear(values.get(i).getYear());
                    spreadScore.setQuarterly(values.get(i).getQuarter());
                    spreadScore.setHierarchyId(values.get(i).getHierarchyId());
                    spreadScore.setComplete(spread);
                    spreadScore1 = PerformanceScoreService.getNewScore(spreadScore);
                    if (spreadScore1 != null) {
                        PerformanceScoreService.UpdateNewScore(spreadScore);
                    } else {
                        PerformanceScoreService.insertScoreSelective(spreadScore);
                    }
                }
            }
            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) {
            //捕获到异常
            //将返回给前端为“服务出现异常”
            e.printStackTrace();
            return Response.responseFail("服务出现异常");
        }

    }

    /**
     * @Author: Create by white
     * @Description: 媒体曝光或群诉excel导入接口
     * @Date: 2018-06-30 19:40
     * @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.negativeEffectiveUplaod(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 = "1015";//一级id 媒体曝光
        return Response.response(performancePower.getUserPower(elementId,requestMap,request));
    }
}





