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.PerformanceCompanyService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceScoreService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceTargetService;
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 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.*;

/**
 * 城市公司—社区经营税前利润
 *
 * @author Max Date:2018/09/06
 * @version 1.0
 * @since 1.8
 */
@Controller
@RequestMapping("/communityProfix")
public class CommunityProfixController {

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

    @Autowired
    private PerformanceTargetService performanceTargetService;

    @Autowired
    private PerformanceScoreService performanceScoreService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private ExcelAnalysis excelAnalysis;

    @Autowired
    private PerformancePower performancePower;

    @Autowired
    private PerformanceCompanyService performanceCompanyService;


    @ResponseBody
    @RequestMapping(value = "/show", method = {RequestMethod.POST, RequestMethod.GET})
    public Object showTarget(@RequestParam(value = "pageCurr") int pageCurr, @RequestParam(value = "pageSize") int pageSize, @RequestParam(value = "years") int year, @RequestParam(value = "quarterly") String quarterly) {
        //用于定义返回的结果
        List<CommunityProfix> CommunityProfixList = new ArrayList<>();
        Map<String, Object> resultMap = new HashMap<>();

        long elementId = 1020;//社区经营税前利润目标值

        //分页——得到城市公司
        List<PerformanceCompany> envList = performanceCompanyService.selectPerformanceCompany();
        int count = envList.size();
        int start = (pageCurr - 1) * pageSize;
        int end = pageCurr * pageSize;

        //用于查询score的参数
        PerformanceScore performanceScore = new PerformanceScore();
        performanceScore.setYear(year);//年
        performanceScore.setQuarterly(quarterly);//季度
        performanceScore.setElementId(elementId);//指标id

        //查询多少条数据是已经录入的
        List<String> vacancyHierarchyName = performanceCompanyService.selectNotInNameCompany(performanceScore);//得到空缺的城市公司名称
        int vacancy = vacancyHierarchyName.size();//空缺，还有多少个城市公司没填

        envList = envList.subList(start < 0 ? 0 : start, end >= count ? count : end);//取开始和结束范围内的值
        if (envList.size() != 0) {//有数据的情况
            for (int i = 0; i < envList.size(); i++) {
                CommunityProfix communityProfixTemp = new CommunityProfix();
                communityProfixTemp.setHierarchyId(envList.get(i).getHierarchyId());//组织id
                communityProfixTemp.setSecond_organization(envList.get(i).getHierarchyName());//二级组织
                communityProfixTemp.setThird_organization(envList.get(i).getHierarchyName());//三级组织
                communityProfixTemp.setYear(year);//设置年份
                communityProfixTemp.setQuarter(quarterly);//设置季度

                //---------完成值，指标单项得分---------
                PerformanceScore score = new PerformanceScore();
                score.setElementId(elementId);//指标id
                score.setYear(year);//年
                score.setQuarterly(quarterly);//季度
                score.setHierarchyId(envList.get(i).getHierarchyId());//城市公司

                PerformanceScore sValue = performanceScoreService.getscoreByHierarchyId(score);
                if (sValue != null) {
                    communityProfixTemp.setComplete(String.valueOf(sValue.getComplete()));//设置完成值
                    communityProfixTemp.setIndividualScore(String.valueOf(sValue.getScore()));//设置指标单项得分
                }

                //---------目标值---------
                PerformanceTarget target = new PerformanceTarget();
                target.setElementId(elementId);
                target.setYear(year);
                target.setQuarterly(quarterly);
                target.setHierarchyId(envList.get(i).getHierarchyId());
                PerformanceTarget tValue = performanceTargetService.getByHierarchyId(target);
                if (tValue != null) {
                    communityProfixTemp.setThresholdTarget(tValue.getThresholdTarget());//门槛值
                    communityProfixTemp.setAtLeastTarget(tValue.getAtLeastTarget());//保底
                    communityProfixTemp.setScreamTarget(tValue.getScreamTarget());//尖叫
                    communityProfixTemp.setHowlTarget(tValue.getHowlTarget());//嚎叫
                    communityProfixTemp.setIsCheck(tValue.getIsCheck());//是否考核
                }else{
                    communityProfixTemp.setIsCheck("0");//是否考核(无数据情况下，为了不让前端报错，返回0)
                }
                CommunityProfixList.add(communityProfixTemp);//存入List
            }
            resultMap.put("list", CommunityProfixList);
            resultMap.put("totalPage", count);
            resultMap.put("vacancy", vacancy);
        } else {//无数据的情况
            resultMap.put("list", CommunityProfixList);
            resultMap.put("totalPage", count);
            resultMap.put("vacancy", vacancy);
        }
        resultMap.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
        return Response.response(resultMap);
    }

    @ResponseBody
    @RequestMapping(value = "/count", method = {RequestMethod.POST, RequestMethod.GET})
    public Object TotalCalculate(@RequestBody List<CommunityProfix> communityProfixList) {
        Map<String, Object> map = new HashMap<>();
        long elementId = 1020;//社区经营税前利润目标值

        //遍历前端传过来的数据
        double weight = 0;
        for(CommunityProfix communityProfix:communityProfixList){

            String hierarchyId = communityProfix.getHierarchyId();
            String type = performanceCompanyService.getTypeByComId(hierarchyId);
            switch (type){
                case "单一业主项目":
                    weight = 0.3;
                    break;
                case "多业主第一年":
                    weight = 0.1;
                    break;
                case "多业主第二年":
                    weight = 0.2;
                    break;
            }

            //存入社区经营税前利润目标值
            PerformanceTarget target = new PerformanceTarget();
            target.setElementId(elementId);
            target.setYear(communityProfix.getYear());
            target.setQuarterly(communityProfix.getQuarter());//设置季度
            target.setHierarchyId(communityProfix.getHierarchyId());
            PerformanceTarget tValue = performanceTargetService.getByHierarchyId(target);
            if(tValue!=null){//存在，则更新
                tValue.setThresholdTarget(communityProfix.getThresholdTarget());//门槛值
                tValue.setAtLeastTarget(communityProfix.getAtLeastTarget());//保底
                tValue.setScreamTarget(communityProfix.getScreamTarget());//尖叫
                tValue.setHowlTarget(communityProfix.getHowlTarget());//嚎叫
                tValue.setIsCheck(communityProfix.getIsCheck());//是否考核
                tValue.setUpdateDate(new Date());
                tValue.setWeight(weight);
                //执行更新操作
                performanceTargetService.updateTargetSelective(tValue);
            }else {
                target.setThresholdTarget(communityProfix.getThresholdTarget());//门槛值
                target.setAtLeastTarget(communityProfix.getAtLeastTarget());//保底
                target.setScreamTarget(communityProfix.getScreamTarget());//尖叫
                target.setHowlTarget(communityProfix.getHowlTarget());//嚎叫
                target.setIsCheck(communityProfix.getIsCheck());//是否考核
                target.setWeight(weight);//设置权重
                target.setCreatedDate(new Date());
                //执行新增操作
                performanceTargetService.insertTargetSelective(target);
            }

            //完全值存储
            double complete=-1;//记录完成值
            double thresholdTarget=-1;
            double atLeastTarget=-1;
            double screamTarget=-1;
            double howlTarget=-1;
            //完成值
            if(communityProfix.getComplete()!=null){
                try {
                    complete=Double.parseDouble(communityProfix.getComplete());
                } catch (NumberFormatException e) {
                    logger.error("======communityProfixController=====complete number is error format");
                }
            }
            //门槛值
            if(communityProfix.getThresholdTarget()!=null){
                try {
                    thresholdTarget=Double.parseDouble(communityProfix.getThresholdTarget());
                } catch (NumberFormatException e) {
                    logger.error("======communityProfixController=====thresholdTarget number is error format");
                }
            }

            //保底
            if(communityProfix.getAtLeastTarget()!=null){
                try {
                    atLeastTarget=Double.parseDouble(communityProfix.getAtLeastTarget());
                } catch (NumberFormatException e) {
                    logger.error("======communityProfixController=====atLeastTarget number is error format");
                }
            }

            //尖叫
            if(communityProfix.getThresholdTarget()!=null){
                try {
                    screamTarget=Double.parseDouble(communityProfix.getComplete());
                } catch (NumberFormatException e) {
                    logger.error("======communityProfixController=====screamTarget number is error format");
                }
            }

            //嚎叫
            if(communityProfix.getHowlTarget()!=null){
                try {
                    howlTarget=Double.parseDouble(communityProfix.getHowlTarget());
                } catch (NumberFormatException e) {
                    logger.error("======communityProfixController=====complete number is error format");
                }
            }

            double individualScore=0.0;
            //计算指标单项得分
            if(complete!=-1&&thresholdTarget!=-1&&atLeastTarget!=-1&&screamTarget!=-1&&howlTarget!=-1){
                individualScore= Double.parseDouble(Calculate.InsertionMethod(complete,thresholdTarget,atLeastTarget,screamTarget,howlTarget,1));
            }

            //设置
            communityProfix.setIndividualScore(String.valueOf(individualScore));//设置指标单项得分

            //将调查情况+指标单项得分存入score表中
            PerformanceScore score=new PerformanceScore();
            score.setHierarchyId(communityProfix.getHierarchyId());
            score.setElementId(elementId);
            score.setYear(communityProfix.getYear());
            score.setQuarterly(communityProfix.getQuarter());

            PerformanceScore sValue = performanceScoreService.getscoreByHierarchyId(score);
            if(sValue!=null){
                sValue.setComplete((float)complete);//设置完成值
                sValue.setScore((float)individualScore);//设置指标单项得分
                sValue.setUpdateDate(new Date());
                performanceScoreService.updateScoreSelective(sValue);//执行更新操作
            }else{
                score.setComplete((float)complete);//设置完成值
                score.setScore((float)individualScore);//设置指标单项得分
                performanceScoreService.insertScoreSelective(score);//执行插入操作
            }
        }
        map.put("list", communityProfixList);//重新装载数据

        performanceScoreService.saveQuartlyAverageScoreAndSumScore(communityProfixList.get(0).getYear(), Integer.parseInt(communityProfixList.get(0).getQuarter()));

        //计算空缺的城市公司
        PerformanceScore performanceScore = new PerformanceScore();
        performanceScore.setYear(communityProfixList.get(0).getYear());//年
        performanceScore.setQuarterly(communityProfixList.get(0).getQuarter());//季度
        performanceScore.setElementId(elementId);
        //查询多少条数据是已经录入的
        List<String> vacancyHierarchyName = performanceCompanyService.selectNotInNameCompany(performanceScore);//得到空缺的城市公司名称
        int vacancy = vacancyHierarchyName.size();//空缺，还有多少个城市公司没填

        map.put("vacancy", vacancy);//设置空缺数据
        map.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
        return Response.response(map);
    }

    @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") MultipartFile multipartFile,
                         HttpServletRequest request) throws ServiceException {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        if (multipartFile == null) {
            throw new ServiceException("请选择需要上传的文件");
        } else if (name == null) {
            throw new ServiceException("请输入文件名");
        }
        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.communityProfixUpload(multipartFile, year, quarter, token.getUserCode());
            performanceScoreService.saveQuartlyAverageScoreAndSumScore(year, quarter);
        } catch (Exception e) {
            e.printStackTrace();
        }
        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 = "1020";
        return Response.response(performancePower.getUserPower(elementId, requestMap, request));
    }

}
