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

import java.util.*;

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.ExcelAnalysis;
import cn.com.countrygarden.bi.main.util.PerformancePower;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
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 cn.com.countrygarden.bi.main.util.Calculate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

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

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

    @Autowired
    private PerformanceTargetService performanceTargetService;

    @Autowired
    private PerformanceElementService performanceElementService;

    @Autowired
    private PerformanceEnvService PerformanceEnvService;

    @Autowired
    private PerformanceScoreService performanceScoreService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private ExcelAnalysis ea;

    @Autowired
    private  PerformancePower performancePower;

    @ResponseBody
    @RequestMapping(value = "/showTarget", method = {RequestMethod.POST, RequestMethod.GET})
    public Object showTarget(@RequestParam(value = "pageSize") int pageSize, @RequestParam(value = "pageCurr") int pageCurr, @RequestParam(value = "years") int years
            , @RequestParam(value = "quarterly") String quarterly) {
        //大客户满意度的编码
        long elementid = 1001;

        Map<String, Object> returnMap = new LinkedHashMap<String, Object>();
        List<BigCustomerSatisfaction> returnList = new ArrayList<BigCustomerSatisfaction>();

        //定义值用来存放目标值，避免新增的区域无目标值
        String hrspp_threshold=null;
        String hrspp_atLeast=null;
        String hrspp_scream=null;
        String hrspp_howl=null;

        PerformanceScore score = new PerformanceScore();
        PerformanceScore sValue = new PerformanceScore();
        PerformanceTarget target = new PerformanceTarget();

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

        //查询多少条数据是录入的
        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++) {
                BigCustomerSatisfaction b = new BigCustomerSatisfaction();

                b.setHierarchyId(envList.get(i).getHierarchyId());
                b.setSecond_organization(envList.get(i).getHierarchyName());
                b.setThird_organization(envList.get(i).getHierarchyName());
                b.setQuarter(quarterly);
                b.setYear(String.valueOf(years));

                String hierarchy_id = envList.get(i).getHierarchyId();

                score.setElementId(elementid);
                score.setHierarchyId(hierarchy_id);
                score.setYear(years);

                score.setQuarterly(quarterly);
                sValue = performanceScoreService.getscoreByHierarchyId(score);
                if (sValue != null) {
                    b.setAnnual(String.valueOf(sValue.getComplete()));
                } else {
                    b.setAnnual(null);
                }

                sValue = performanceScoreService.getscoreByHierarchyId(score);
                if (sValue != null) {
                    b.setIndividualScore(String.valueOf(sValue.getScore()));
                } else {
                    b.setIndividualScore(null);
                }

                //第一个季度
                score.setQuarterly("1");
                sValue = performanceScoreService.getscoreByHierarchyId(score);
                if (sValue != null) {
                    b.setS1(String.valueOf(sValue.getComplete()));
                } else {
                    b.setS1(null);
                }
                //第二个季度
                score.setQuarterly("2");
                sValue = performanceScoreService.getscoreByHierarchyId(score);
                if (sValue != null) {
                    b.setS2(String.valueOf(sValue.getComplete()));
                } else {
                    b.setS2(null);
                }
                //第三个季度
                score.setQuarterly("3");
                sValue = performanceScoreService.getscoreByHierarchyId(score);
                if (sValue != null) {
                    b.setS3(String.valueOf(sValue.getComplete()));
                } else {
                    b.setS3(null);
                }
                //第四个季度
                score.setQuarterly("4");
                sValue = performanceScoreService.getscoreByHierarchyId(score);
                if (sValue != null) {
                    b.setS4(String.valueOf(sValue.getComplete()));
                } else {
                    b.setS4(null);
                }


                target.setHierarchyId(hierarchy_id);
                target.setElementId(elementid);
                target.setYear(years);
                target.setQuarterly(quarterly);
                PerformanceTarget tValue = performanceTargetService.getByHierarchyId(target);
                if (tValue != null) {
                    b.setHrspp_threshold(tValue.getThresholdTarget());
                    b.setHrspp_atLeast(tValue.getAtLeastTarget());
                    b.setHrspp_scream(tValue.getScreamTarget());
                    b.setHrspp_howl(tValue.getHowlTarget());
                    //是否考核,1表示考核，0表示不考核
                    b.setIs_check(tValue.getIsCheck().equals("1") ? 1 : 0);
                    if(hrspp_threshold==null){
                        hrspp_threshold=tValue.getThresholdTarget();
                        hrspp_atLeast=tValue.getAtLeastTarget();
                        hrspp_scream=tValue.getScreamTarget();
                        hrspp_howl=tValue.getHowlTarget();
                    }
                }else{
                    b.setHrspp_threshold(hrspp_threshold);
                    b.setHrspp_atLeast(hrspp_atLeast);
                    b.setHrspp_scream(hrspp_scream);
                    b.setHrspp_howl(hrspp_howl);
                }
                returnList.add(b);
            }
            returnMap.put("list", returnList);
            returnMap.put("totalPage", count);
            returnMap.put("vacancy", vacancy);
            returnMap.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
        }
        return Response.response(returnMap);
    }

    @ResponseBody
    @RequestMapping(value = "/TotalCalculate", method = {RequestMethod.POST, RequestMethod.GET})
    public Object TotalCalculate(@RequestBody List<BigCustomerSatisfaction> values) {

        //大客户指标id
        Long elementId = 1001L;
        Integer year = Integer.parseInt(values.get(0).getYear());
        Integer quarter = Integer.parseInt(values.get(0).getQuarter());
        quarter = quarter > 4 ? 4 : quarter;   //半年度年度会是数组越界，对这个指标而言用不到半年度年度选项

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

        //传入对象
        PerformanceScore score = new PerformanceScore();
        PerformanceTarget target = new PerformanceTarget();
        //返回对象
        PerformanceScore rScore;
        PerformanceTarget rTarget;

        //遍历集合将对象存入数据库中
        for (BigCustomerSatisfaction value : values) {

            String s1 = value.getS1();
            String s2 = value.getS2();
            String s3 = value.getS3();
            String s4 = value.getS4();
            String[] completes = {s1, s2, s3, s4};
            String HierarchyId = value.getHierarchyId();

            //入库得分表
            score.setElementId(elementId);
            score.setHierarchyId(HierarchyId);
            score.setYear(year);

            for (int i = 0; i < completes.length; i++) {
                if (StringUtil.isBlankOrEmpty(completes[i])) {
                    completes[i] = "-1";
                }
                if (i <= quarter - 1) {  //使其输入的数据限定于选择的季度  eg:选择第一季度，只有s1数据有效；选择第二季度，只s1、s2数据有效
                    score.setQuarterly(String.valueOf(i + 1));
                    rScore = performanceScoreService.getscoreByHierarchyId(score);
                    completes[i] = String.valueOf(rScore == null ? "-1" : completes[i]);
                }else{
                    completes[i] = "-1";
                }
            }
            String Annual;

            if (completes[0].equals("-1") && completes[1].equals("-1") && completes[2].equals("-1") && completes[3].equals("-1")) {
                Annual = "-1";
            } else {
                Annual = Calculate.Year(Double.parseDouble(completes[0]), Double.parseDouble(completes[1]), Double.parseDouble(completes[2]), Double.parseDouble(completes[3]));
            }

            String Hrspp_threshold = value.getHrspp_threshold();
            if (Hrspp_threshold == null || "".equals(Hrspp_threshold)) {
                Hrspp_threshold = "-1";
            }
            String Hrspp_atLeast = value.getHrspp_atLeast();
            if (Hrspp_atLeast == null || "".equals(Hrspp_atLeast)) {
                Hrspp_atLeast = "-1";
            }

            String Hrspp_scream = value.getHrspp_scream();
            if (Hrspp_scream == null || "".equals(Hrspp_scream)) {
                Hrspp_scream = "-1";
            }
            String Hrspp_howl = value.getHrspp_howl();
            if (Hrspp_howl == null || "".equals(Hrspp_howl)) {
                Hrspp_howl = "-1";
            }

            String IndividualScore = "-1";

            if (!Annual.equals("-1")) {
                IndividualScore = Calculate.InsertionMethod(Double.parseDouble(Annual), Double.parseDouble(Hrspp_threshold), Double.parseDouble(Hrspp_atLeast), Double.parseDouble(Hrspp_scream), Double.parseDouble(Hrspp_howl), 1);
            }
            value.setAnnual(Annual);
            value.setIndividualScore(IndividualScore);


            if (value.getIs_check() == 0) {
                IndividualScore = "-1";
            }

            //入库得分表
            score.setElementId(elementId);
            score.setQuarterly(String.valueOf(quarter));
            score.setHierarchyId(HierarchyId);
            score.setYear(year);

            //季度得分
            rScore = performanceScoreService.getscoreByHierarchyId(score);
            if (rScore != null) {
                //如果值为非空，则更新数据
                rScore.setScore(Float.parseFloat(IndividualScore));
                rScore.setComplete(Float.parseFloat(completes[quarter - 1])); //选择第几季度就只能更新这个季度的完成值
                rScore.setYearlyScore(Float.parseFloat(Annual));
                performanceScoreService.updateScoreSelective(rScore);
            } else {
                //如果值为空，则插入数据
                score.setScore(Float.parseFloat(IndividualScore));
                score.setComplete(Float.parseFloat(completes[quarter - 1])); //选择第几季度就只能更新这个季度的完成值
                score.setYearlyScore(Float.parseFloat(Annual));
                performanceScoreService.insertScoreSelective(score);
            }


            //更新目标值
            target.setElementId(elementId);
            target.setQuarterly(String.valueOf(quarter));
            target.setHierarchyId(HierarchyId);
            target.setYear(year);

            rTarget = performanceTargetService.getNewByHierarchyId(target);
            if (rTarget != null) {
                rTarget.setThresholdTarget(String.valueOf(Hrspp_threshold));
                rTarget.setAtLeastTarget(String.valueOf(Hrspp_atLeast));
                rTarget.setScreamTarget(String.valueOf(Hrspp_scream));
                rTarget.setHowlTarget(String.valueOf(Hrspp_howl));
                rTarget.setIsCheck(String.valueOf(value.getIs_check()));
                rTarget.setFrequency("月度、季度");
                rTarget.setWeight(0.15);
                performanceTargetService.updateTargetSelective(rTarget);
            } else {
                target.setThresholdTarget(String.valueOf(Hrspp_threshold));
                target.setAtLeastTarget(String.valueOf(Hrspp_atLeast));
                target.setScreamTarget(String.valueOf(Hrspp_scream));
                target.setHowlTarget(String.valueOf(Hrspp_howl));
                target.setIsCheck(String.valueOf(value.getIs_check()));
                target.setFrequency("月度、季度");
                target.setWeight(0.15);
                performanceTargetService.insertTargetSelective(target);
            }
            value.setIndividualScore(IndividualScore);
        }

        performanceScoreService.saveQuartlyAverageScoreAndSumScore(year, quarter);
        resultMap.put("list", values);
        List<PerformanceEnv> envList = PerformanceEnvService.selectPerformanceOrgan();
        int count = envList.size();
        PerformanceScore performanceScore = new PerformanceScore();
        performanceScore.setYear(year);//年
        performanceScore.setQuarterly(quarter.toString());//季度
        performanceScore.setElementId(elementId);
        int vacancy = count - performanceScoreService.getTotalPage(performanceScore).getTotalPage();//空缺，还有多少个区域指标没填
        if (vacancy < 0) {
            vacancy = 0;
        }
        resultMap.put("vacancy", vacancy);//设置空缺数据
        List<String> vacancyHierarchyName = PerformanceEnvService.selectNotInName(performanceScore);
        resultMap.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称

        return Response.response(resultMap);
    }


    @ResponseBody
    @RequestMapping(value = "/upload", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result upload(@RequestParam(value = "year") int year, @RequestParam(value = "quarter") int quarter,
                         @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");
        }
        if (!fileName.contains("大客户")) {
            return Response.responseFail("请选择正确的文件！");
        }
        try {
            ea.BigCustomerSatisfactionUpload(1001L,multipartFile, year, quarter, token.getUserCode());
            performanceScoreService.saveQuartlyAverageScoreAndSumScore(year, quarter);
            return Response.response("导入成功");
        } catch (Exception e) {
            return Response.responseFail(e.getMessage());
        }
    }

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