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

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
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.Calculate;
import cn.com.countrygarden.bi.main.util.ExcelAnalysis;
import cn.com.countrygarden.bi.main.util.PerformancePower;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
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 java.util.*;

//外拓收入第一个接口，显示数据
@Controller("OutreachRevenueController")
@RequestMapping("/OutreachRevenueController")
public class OutreachRevenueController {

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

    @Autowired
    private PerformanceTargetService performanceTargetService;

    @Autowired
    private PerformanceScoreService performanceScoreService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private PerformanceEnvService performanceEnvService;

    @Autowired
    private ExcelAnalysis ea;

    @Autowired
    private  PerformancePower performancePower;

    /*
        重构查询接口
        @author Max 陈彩君 Date:2018/7/2
     */
    @ResponseBody
    @RequestMapping(value = "/showOut", method = {RequestMethod.POST, RequestMethod.GET})
    public Object showOut(@RequestParam(value = "pageSize") int pageSize, @RequestParam(value = "pageCurr") int pageCurr, @RequestParam(value = "years") int year, @RequestParam(value = "quarterly") int quarterly) {

        Map<String, Object> map = new HashMap<>();
        long elementId = 1007;//外拓收入的id

        List<OutreachRevenue> outreachRevenueList = new ArrayList<>();

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

        envList = envList.subList(start < 0 ? 0 : start, end >= count ? count : end);//取开始和结束范围内的值

        String thisQuarter = String.valueOf(quarterly);//季度值

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

        if (envList.size() != 0) {
            for (int i = 0; i < envList.size(); i++) {
                OutreachRevenue o = new OutreachRevenue();
                o.setHierarchyId(envList.get(i).getHierarchyId());//组织id
                o.setSecond_organization(envList.get(i).getHierarchyName());//二级组织
                o.setThird_organization(envList.get(i).getHierarchyName());//三级组织
                o.setElementId((int) elementId);//设置elementid
                o.setYear(String.valueOf(year));//设置年份
                o.setQuarter(thisQuarter);//设置季度值

                //target表里的相关记录
                PerformanceTarget t = new PerformanceTarget();
                t.setYear(year);//年
                //t.setQuarterly("6");//季度
                t.setQuarterly(thisQuarter);//季度
                t.setHierarchyId(envList.get(i).getHierarchyId());//区域
                t.setElementId(elementId);//外拓收入的id
                PerformanceTarget tValue = performanceTargetService.getNewByHierarchyId(t);
                if (tValue != null) {
                    o.setThresholdTarget(tValue.getThresholdTarget());//门槛
                    o.setAtLeastTarget(tValue.getAtLeastTarget());//保底
                    o.setScreamTarget(tValue.getScreamTarget());//尖叫
                    o.setHowlTarget(tValue.getHowlTarget());//嚎叫
                    //是否考核,1表示考核，0表示不考核
                    if (StringUtil.isEmpty(tValue.getIsCheck())) {
                        o.setIs_check(0);
                    } else if (tValue.getIsCheck().equals("1")) {
                        o.setIs_check(1);
                    } else {
                        o.setIs_check(0);
                    }
                }

                //score表里的相关记录
                PerformanceScore scores = new PerformanceScore();
                scores.setYear(year);//年
                //scores.setQuarterly("6");//季度
                scores.setQuarterly(thisQuarter);//季度
                scores.setHierarchyId(envList.get(i).getHierarchyId());//区域
                scores.setElementId(elementId);//外拓收入的id
                PerformanceScore score = performanceScoreService.getscoreByHierarchyId(scores);
                if (score != null) {
                    o.setRealIncome(String.valueOf(score.getComplete()));//把完成值放入实际值，实际值是入库后才获得的
                    o.setIndividualScore(String.valueOf(score.getScore()));//单项指标得分，是计算后入库才获得
                }
                outreachRevenueList.add(o);
            }
            map.put("list", outreachRevenueList);//数据返回
            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);
    }

    /*
        修改score更新和五个目标值更新
        @author Max 陈彩君 Date:2018/06/28
     */
    @ResponseBody
    @RequestMapping(value = "/OutreachRevenueCal", method = {RequestMethod.POST, RequestMethod.GET})
    public Object TotalCalculate(@RequestBody List<OutreachRevenue> OutreachRevenues) {
        Map<String, Object> map = new HashMap<>();
        long elementId = 1007;//外拓收入的id 写死

        try {
            for (OutreachRevenue outreachRevenue : OutreachRevenues) {
                //目标值
                double realIncome = 0;         //实际收入
                double thresholdTarget = 0;  //门槛值目标值
                double atLeastTarget = 0;  //保底目标值
                double screamTarget = 0;  //尖叫目标值
                double howlTarget = 0;  //嚎叫目标值
                String IndividualScore;      // 指标单项得分
                PerformanceScore score = new PerformanceScore();
                //外拓收入实际值(万元)
                if ((!outreachRevenue.getRealIncome().equals("")) && outreachRevenue.getRealIncome() != null) {
                    try {
                        realIncome = Double.parseDouble(outreachRevenue.getRealIncome());
                    } catch (Exception e) {
                        logger.error("======OutreachRevenueController.TotalCalculate======realIncome:" + outreachRevenue.getRealIncome());
                    }
                }
                //门槛值
                if ((!outreachRevenue.getThresholdTarget().equals("")) && outreachRevenue.getThresholdTarget() != null) {
                    try {
                        thresholdTarget = Double.parseDouble(outreachRevenue.getThresholdTarget());
                    } catch (Exception e) {
                        logger.error("======OutreachRevenueController.TotalCalculate======thresholdTarget:" + outreachRevenue.getThresholdTarget());
                    }
                }
                //保底值
                if ((!outreachRevenue.getAtLeastTarget().equals("")) && outreachRevenue.getAtLeastTarget() != null) {
                    try {
                        atLeastTarget = Double.parseDouble(outreachRevenue.getAtLeastTarget());
                    } catch (Exception e) {
                        logger.error("======OutreachRevenueController.TotalCalculate======atLeastTarget:" + outreachRevenue.getAtLeastTarget());
                    }
                }
                //尖叫值
                if ((!outreachRevenue.getScreamTarget().equals("")) && outreachRevenue.getScreamTarget() != null) {
                    try {
                        screamTarget = Double.parseDouble(outreachRevenue.getScreamTarget());
                    } catch (Exception e) {
                        logger.error("======OutreachRevenueController.TotalCalculate======screamTarget:" + outreachRevenue.getScreamTarget());
                    }
                }
                //嚎叫值
                if ((!outreachRevenue.getHowlTarget().equals("")) && outreachRevenue.getHowlTarget() != null) {
                    try {
                        howlTarget = Double.parseDouble(outreachRevenue.getHowlTarget());
                    } catch (Exception e) {
                        logger.error("======OutreachRevenueController.TotalCalculate======howlTarget:" + outreachRevenue.getHowlTarget());
                    }
                }
                //计算指标单项得分
                IndividualScore = Calculate.InsertionMethod(realIncome, atLeastTarget, thresholdTarget, screamTarget, howlTarget, 1);
                outreachRevenue.setIndividualScore(IndividualScore);

                ///////////////////////////////////////////////////////////////////
                score.setScore(Float.parseFloat(IndividualScore));//插入的单项得分
                score.setComplete((float) realIncome);//插入实际值：就是完成值
                score.setYear(Integer.parseInt(outreachRevenue.getYear()));//按年度
                //score.setQuarterly("6");//外拓是根据年度考核的
                score.setQuarterly(outreachRevenue.getQuarter());//季度值
                score.setHierarchyId(outreachRevenue.getHierarchyId());//按区域
                score.setElementId(elementId);//按这个指标插入
                PerformanceScore score1 = performanceScoreService.getscoreByHierarchyId(score);////查询有没有这条记录

                //判断是否重复是就更新否就插入
                if (score1 == null) {
                    score.setCreatedDate(new Date());//创建日期
                    //插入
                    performanceScoreService.insertScoreSelective(score);
                } else {
                    performanceScoreService.updateScoreSelective(score);
                }

                //得到唯一目标值
                PerformanceTarget performanceTarget = new PerformanceTarget();
                performanceTarget.setYear(Integer.parseInt(outreachRevenue.getYear()));//按年度
                //performanceTarget.setQuarterly("6");//按照年度
                performanceTarget.setQuarterly(outreachRevenue.getQuarter());//按照季度
                performanceTarget.setHierarchyId(outreachRevenue.getHierarchyId());//按区域
                performanceTarget.setElementId(elementId);//按指标
                //得到target表中唯一记录——根据上面四个值
                PerformanceTarget selectTarget = performanceTargetService.getNewByHierarchyId(performanceTarget);
                if (selectTarget != null) {
                    //更新4个目标值
                    selectTarget.setThresholdTarget(String.valueOf(thresholdTarget));//门槛值目标值
                    selectTarget.setAtLeastTarget(String.valueOf(atLeastTarget));//保底目标值
                    selectTarget.setScreamTarget(String.valueOf(screamTarget));//尖叫目标值
                    selectTarget.setHowlTarget(String.valueOf(howlTarget));//嚎叫目标值
                    //执行更新操作
                    performanceTargetService.updateTargetByTargetId(selectTarget);
                } else {
                    //插入4个目标值
                    performanceTarget.setThresholdTarget(String.valueOf(thresholdTarget));//门槛值目标值
                    performanceTarget.setAtLeastTarget(String.valueOf(atLeastTarget));//保底目标值
                    performanceTarget.setScreamTarget(String.valueOf(screamTarget));//尖叫目标值
                    performanceTarget.setHowlTarget(String.valueOf(howlTarget));//嚎叫目标值
                    performanceTarget.setCreatedDate(new Date());
                    //设置权重
                    performanceTarget.setWeight(0.1);
                    performanceTargetService.insertTargetSelective(performanceTarget);
                }
            }
            map.put("list", OutreachRevenues);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<PerformanceEnv> envList = performanceEnvService.selectPerformanceOrgan();
        int count = envList.size();
        PerformanceScore performanceScore = new PerformanceScore();
        performanceScore.setYear(Integer.parseInt(OutreachRevenues.get(0).getYear()));//年
        performanceScore.setQuarterly(OutreachRevenues.get(0).getQuarter());//季度
        performanceScore.setElementId(elementId);
        int vacancy = count - performanceScoreService.getTotalPage(performanceScore).getTotalPage();//空缺，还有多少个区域指标没填
        if (vacancy < 0) {
            vacancy = 0;
        }
        performanceScoreService.saveQuartlyAverageScoreAndSumScore(Integer.parseInt(OutreachRevenues.get(0).getYear()), Integer.parseInt(OutreachRevenues.get(0).getQuarter()));
        map.put("vacancy", vacancy);//设置空缺数据
        List<String> vacancyHierarchyName = performanceEnvService.selectNotInName(performanceScore);
        map.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
        return Response.response(map);
    }

    @ResponseBody
    @RequestMapping(value = "/upload", produces = "application/json;charset=utf-8")
    public Result upload(@RequestParam(value = "year") int year, @RequestParam(value = "quarter") int quarter,
                         @RequestParam(value = "name") String name,
                         @RequestParam(value = "uploadfile") MultipartFile multipartFile,
                         HttpServletRequest request) 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 {
            //ea.outreachRevenueUpload(multipartFile, year, quarter, "0000");
            ea.outreachRevenueUpload(multipartFile, year, quarter, token.getUserCode());
            performanceScoreService.saveQuartlyAverageScoreAndSumScore(year, quarter);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail(e.getMessage());
        }
        return Response.response("导入成功");
    }

    /**
     * 查询和更新解锁状态，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 = "1007";//外拓收入的id
        return Response.response(performancePower.getUserPower(elementId,requestMap,request));
    }
}