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

/**
 * 城市指标—主营税前利润
 *
 * @author Max Date:2018/09/07
 * @version 1.0
 * @since 1.8
 */
@Controller
@RequestMapping("/principalProfit")
public class PrincipalProfitController {

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

    @Autowired
    private PerformanceTargetService performanceTargetService;

    @Autowired
    private PerformanceScoreService performanceScoreService;

    @Autowired
    private PerformanceElementService performanceElementService;

    @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) {

        long elementId = 1019;//主营税前利润

        Map<String, Object> elementMap = new LinkedHashMap<>();// 接收值
        //返回结果保存
        Map<String, Object> returnMap = new LinkedHashMap<>();// 返回值
        List<PrincipalProfit> returnList = new ArrayList<>();

        PerformanceTarget t = new PerformanceTarget();
        PerformanceScore s = new PerformanceScore();
        PerformanceTarget tValue = new PerformanceTarget();
        PerformanceScore sValue = new PerformanceScore();

        // 获得税前利润下级 的ID 和 指标的名
        PerformanceElement element = new PerformanceElement();
        element.setElementId(elementId);
        List<PerformanceElement> elementList = performanceElementService.getElementId(element);

        for (int i = 0; i < elementList.size(); i++) {
            if (elementList.get(i).getName().equals("综合税前利润")) {
                elementMap.put("综合税前利润", elementList.get(i).getElementId());
            }
            if (elementList.get(i).getName().equals("社区经营服务（N）税前利润")) {
                elementMap.put("社区经营服务（N）税前利润", elementList.get(i).getElementId());
            }
        }

        List<PerformanceCompany> envList = performanceCompanyService.selectPerformanceCompany();
        int count = envList.size();
        int start = (pageCurr - 1) * pageSize;
        int end = pageCurr * pageSize;

        envList = envList.subList(start < 0 ? 0 : start, end >= count ? count : end);

        //用于查询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();//空缺，还有多少个城市公司没填

        if (envList.size() != 0) {
            for (PerformanceCompany performanceCompany : envList) {

                PrincipalProfit principalProfit = new PrincipalProfit();// 税前利润实体bean
                principalProfit.setHierarchyId(performanceCompany.getHierarchyId());//区域id
                principalProfit.setYear(year);//年
                principalProfit.setQuarter(quarterly);//季度
                principalProfit.setSecond_organization(performanceCompany.getHierarchyName());// 项目区域
                principalProfit.setThird_organization(performanceCompany.getHierarchyName());// 项目区域

                //设置target和score相关的通用参数
                t.setHierarchyId(performanceCompany.getHierarchyId());
                t.setYear(year);

                s.setHierarchyId(performanceCompany.getHierarchyId());
                s.setYear(year);

                //---------------上半年 综合利润 HY---------------
                s.setElementId(Long.parseLong(elementMap.get("综合税前利润").toString()));
                if (Integer.parseInt(quarterly) > 2) {
                    t.setQuarterly("2");
                    s.setQuarterly("2");
                } else {
                    t.setQuarterly(quarterly);
                    s.setQuarterly(quarterly);
                }

                //得到score的数据
                sValue = performanceScoreService.getscoreByHierarchyId(s);
                if (sValue != null) {
                    principalProfit.setHyComplete(String.valueOf(sValue.getComplete()));//综合税前利润完成值
                    principalProfit.setHyScore(String.valueOf(sValue.getScore()));//综合税前利润细项得分
                }

                //五个目标值
                t.setElementId(Long.parseLong(elementMap.get("综合税前利润").toString()));
                tValue = performanceTargetService.getNewByHierarchyId(t);
                if (tValue != null) {
                    principalProfit.setHyThreshold(tValue.getThresholdTarget());//门槛
                    principalProfit.setHyAtLeast(tValue.getAtLeastTarget());//保底
                    principalProfit.setHyScream(tValue.getScreamTarget());//尖叫
                    principalProfit.setHyHowl(tValue.getHowlTarget());//嚎叫
                }

                //--------------上半年 税前利润 HYC--------------
                s.setElementId(Long.parseLong(elementMap.get("社区经营服务（N）税前利润").toString()));
                //得到score的数据
                sValue = performanceScoreService.getscoreByHierarchyId(s);
                if (sValue != null) {
                    principalProfit.setHycComplete(String.valueOf(sValue.getComplete()));
                    principalProfit.setHycScore(String.valueOf(sValue.getScore()));
                }

                //五个目标值
                t.setElementId(Long.parseLong(elementMap.get("社区经营服务（N）税前利润").toString()));
                tValue = performanceTargetService.getNewByHierarchyId(t);
                if (tValue != null) {
                    principalProfit.setHycThreshold(tValue.getThresholdTarget());
                    principalProfit.setHycAtLeast(tValue.getAtLeastTarget());
                    principalProfit.setHycScream(tValue.getScreamTarget());
                    principalProfit.setHycHowl(tValue.getHowlTarget());
                }

                //------------------------------------------------------------------------------------------------//
                //--------------全年 综合利润 AL--------------
                s.setElementId(Long.parseLong(elementMap.get("综合税前利润").toString()));
                s.setQuarterly(quarterly);
                t.setQuarterly(quarterly);

                //得到score的数据
                sValue = performanceScoreService.getscoreByHierarchyId(s);
                if (sValue != null) {
                    principalProfit.setAlComplete(String.valueOf(sValue.getComplete()));
                    principalProfit.setAlScore(String.valueOf(sValue.getScore()));
                }

                //五个目标值
                t.setElementId(Long.parseLong(elementMap.get("综合税前利润").toString()));
                tValue = performanceTargetService.getNewByHierarchyId(t);
                if (tValue != null) {
                    principalProfit.setAlThreshold(tValue.getThresholdTarget());
                    principalProfit.setAlAtLeast(tValue.getAtLeastTarget());
                    principalProfit.setAlScream(tValue.getScreamTarget());
                    principalProfit.setAlHowl(tValue.getHowlTarget());
                }

                //--------------全年 税前利润 ALC--------------
                s.setElementId(Long.parseLong(elementMap.get("社区经营服务（N）税前利润").toString()));
                //得到score的数据
                sValue = performanceScoreService.getscoreByHierarchyId(s);
                if (sValue != null) {
                    principalProfit.setAlcComplete(String.valueOf(sValue.getComplete()));
                    principalProfit.setAlcScore(String.valueOf(sValue.getScore()));
                }

                //五个目标值
                t.setElementId(Long.parseLong(elementMap.get("社区经营服务（N）税前利润").toString()));
                tValue = performanceTargetService.getNewByHierarchyId(t);
                if (tValue != null) {
                    principalProfit.setAlcThreshold(tValue.getThresholdTarget());
                    principalProfit.setAlcAtLeast(tValue.getAtLeastTarget());
                    principalProfit.setAlcScream(tValue.getScreamTarget());
                    principalProfit.setAlcHowl(tValue.getHowlTarget());
                }

                //-----------指标总得分---------
                s.setElementId(elementId);
                s.setQuarterly(quarterly);
                sValue = performanceScoreService.getscoreByHierarchyId(s);
                if (sValue != null) {
                    principalProfit.setIndividualscore(String.valueOf(sValue.getScore()));
                }

                /////////////////////////
                PerformanceTarget tft = new PerformanceTarget();
                tft.setYear(year);//年
                tft.setQuarterly(quarterly);//季度
                tft.setHierarchyId(performanceCompany.getHierarchyId());//区域
                tft.setElementId(elementId);
                PerformanceTarget tftValue = performanceTargetService.getNewByHierarchyId(tft);
                if (tftValue != null) {
                    principalProfit.setIsCheck(tftValue.getIsCheck().equals("1") ? "1" : "0");
                } else {
                    principalProfit.setIsCheck("0");
                }
                ///////////////////////

                returnList.add(principalProfit);
            }
            returnMap.put("list", returnList);
            returnMap.put("totalPage", count);
            returnMap.put("vacancy", vacancy);
            returnMap.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
        }
        return Response.response(returnMap);
    }


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

        PerformanceElement element = new PerformanceElement();// 社区经营服务下级 的ID 和

        // 指标的名称
        Map<String, Long> elementIdMap = new LinkedHashMap<>();
        Map<String, Object> resultMap = new LinkedHashMap<>();// 返回值

        // 获取一级税前利润的id
        List<PerformanceElement> list2 = new ArrayList<>();

        // 获取一级id的list
        long elementId = 1019;// 默认id，税前利润

        PerformanceScore score = new PerformanceScore();// 操作值
        PerformanceScore sValue = new PerformanceScore();
        PerformanceTarget target = new PerformanceTarget();
        PerformanceTarget tValue = new PerformanceTarget();

        if (principalProfitList.size() != 0) {
            // 得到一级ID
            element.setElementId(elementId);
            list2 = performanceElementService.getElementId(element);

            for (int i = 0; i < list2.size(); i++) {
                if (list2.get(i).getName().equals("综合税前利润")) {
                    elementIdMap.put("综合税前利润", list2.get(i).getElementId());
                }
                if (list2.get(i).getName().equals("社区经营服务（N）税前利润")) {
                    elementIdMap.put("社区经营服务（N）税前利润", list2.get(i).getElementId());
                }
            }

            for (PrincipalProfit principalProfit : principalProfitList) {

                String HierarchyId = principalProfit.getHierarchyId();
                String type = performanceCompanyService.getTypeByComId(HierarchyId);
                double weight = 0;
                switch (type){
                    case "单一业主项目":
                        weight = 0.1;
                        break;
                    case "多业主第一年":
                        weight = 0.1;
                        break;
                    case "多业主第二年":
                        weight = 0.1;
                        break;
                }

                int year = principalProfit.getYear();
                int quarter = Integer.parseInt(principalProfit.getQuarter());

                String[] thresholds = {principalProfit.getHyThreshold(), principalProfit.getAlThreshold(), principalProfit.getHycThreshold(), principalProfit.getAlcThreshold()};
                String[] atLasts = {principalProfit.getHyAtLeast(), principalProfit.getAlAtLeast(), principalProfit.getHycAtLeast(), principalProfit.getAlcAtLeast()};
                String[] screams = {principalProfit.getHyScream(), principalProfit.getAlScream(), principalProfit.getHycScream(), principalProfit.getAlcScream()};
                String[] howls = {principalProfit.getHyHowl(), principalProfit.getAlHowl(), principalProfit.getHycHowl(), principalProfit.getAlcHowl()};
                String[] completes = {principalProfit.getHyComplete(), principalProfit.getAlComplete(), principalProfit.getHycComplete(), principalProfit.getAlcComplete()};
                String[] scores = {"-1", "-1", "-1", "-1"};

                double complete = -1;
                double threshold = -1;
                double atLeast = -1;
                double scream = -1;
                double howl = -1;

                score.setHierarchyId(HierarchyId);
                score.setYear(year);

                target.setHierarchyId(HierarchyId);
                target.setYear(year);
                for (int i = 0; i < 4; i++) {
                    long subElementId = i <= 1 ? elementIdMap.get("综合税前利润") : elementIdMap.get("社区经营服务（N）税前利润");
                    int q = quarter;
                    if (i % 2 == 0) {       // 0 2 上半年
                        q = quarter > 2 ? 2 : quarter;
                    }

                    if (!StringUtil.isBlankOrEmpty(completes[i])) {
                        complete = Double.parseDouble(completes[i]);// 完成值
                    } else {
                        continue;
                    }
                    if (!StringUtil.isBlankOrEmpty(thresholds[i])) {
                        threshold = Double.parseDouble(thresholds[i]);// 门槛
                    }
                    if (!StringUtil.isBlankOrEmpty(atLasts[i])) {
                        atLeast = Double.parseDouble(atLasts[i]);// 保底
                    }
                    if (!StringUtil.isBlankOrEmpty(screams[i])) {
                        scream = Double.parseDouble(screams[i]);// 尖叫
                    }
                    if (!StringUtil.isBlankOrEmpty(howls[i])) {
                        howl = Double.parseDouble(howls[i]);// 嚎叫
                    }
                    //计算得分值存入数组中
                    scores[i] = Calculate.InsertionMethod(complete, -1, atLeast, scream, howl, 1);// 计算结果

                    score.setQuarterly(String.valueOf(q));
                    score.setElementId(subElementId);
                    sValue = performanceScoreService.getscoreByHierarchyId(score);//查询有没有这条记录
                    if (sValue != null) {
                        sValue.setScore(Float.parseFloat(scores[i])); //综合收缴率细项得分
                        sValue.setComplete((float) complete);//插入实际值：就是完成值
                        performanceScoreService.updateScoreSelective(sValue);
                    } else {
                        score.setScore(Float.parseFloat(scores[i])); //综合收缴率细项得分
                        score.setComplete((float) complete);//插入实际值：就是完成值
                        performanceScoreService.insertScoreSelective(score);
                    }

                    //更新目标值
                    target.setElementId(subElementId);
                    target.setQuarterly(String.valueOf(q));
                    tValue = performanceTargetService.getByHierarchyId(target);
                    if (tValue != null) {
                        tValue.setThresholdTarget(String.valueOf(threshold));  //门槛值
                        tValue.setAtLeastTarget(String.valueOf(atLeast));
                        tValue.setScreamTarget(String.valueOf(scream));
                        tValue.setHowlTarget(String.valueOf(howl));
                        performanceTargetService.updateTargetSelective(tValue);//更新操作
                    } else {
                        target.setThresholdTarget(String.valueOf(threshold));  //门槛值
                        target.setAtLeastTarget(String.valueOf(atLeast));
                        target.setScreamTarget(String.valueOf(scream));
                        target.setHowlTarget(String.valueOf(howl));
                        performanceTargetService.insertTargetSelective(target);//新增操作
                    }
                }

                double HY_score = Double.valueOf(scores[0]);
                double AL_score = Double.valueOf(scores[1]);
                double HYC_score = Double.valueOf(scores[2]);
                double ALC_score = Double.valueOf(scores[3]);
                String IndividualScore = "-1";

                principalProfit.setHyScore(String.valueOf(HY_score));
                principalProfit.setAlScore(String.valueOf(AL_score));
                principalProfit.setHycScore(String.valueOf(HYC_score));
                principalProfit.setAlcScore(String.valueOf(ALC_score));

                if (HY_score == -1 && AL_score == -1 && HYC_score == -1 && ALC_score == -1) {
                    IndividualScore = "-1";
                } else {
                    if (HYC_score == -1 && ALC_score == -1) {  //社区经营不考核
                        if (HY_score != -1) {   //上半年和下半年都有数据
                            HY_score *= 0.3;
                            AL_score *= 0.7;
                            HYC_score = ALC_score = 0.0;
                        } else {        //上半年不考核
                            AL_score *= 1;
                            HY_score = HYC_score = ALC_score = 0.0;
                        }
                    } else {            //社区经营考核
                        if (HY_score == -1 && HYC_score == -1) {        //上半年不考核
                            AL_score *= 0.7;
                            ALC_score *= 0.3;
                            HY_score = HYC_score = 0.0;
                        } else {        //上半年考核
                            HY_score *= 0.2;
                            AL_score *= 0.5;
                            HYC_score *= 0.1;
                            ALC_score *= 0.2;
                        }
                    }
                    IndividualScore = String.valueOf(HY_score + AL_score + HYC_score + ALC_score);
                }

                principalProfit.setIndividualscore(IndividualScore);

                score.setElementId(elementId);
                score.setQuarterly(String.valueOf(quarter));
                score.setYear(year);
                score.setHierarchyId(HierarchyId);
                score.setScore(-1);
                score.setComplete(-1);
                sValue = performanceScoreService.getscoreByHierarchyId(score);//查询有没有这条记录
                if (sValue != null) {
                    sValue.setScore(Float.parseFloat(IndividualScore));//插入的细项得分
                    performanceScoreService.updateScoreSelective(sValue);
                } else {
                    score.setScore(Float.parseFloat(IndividualScore));//插入的细项得分
                    performanceScoreService.insertScoreSelective(score);
                }
                target.setElementId(elementId);
                target.setQuarterly(principalProfit.getQuarter());
                target.setYear(year);
                target.setHierarchyId(HierarchyId);

                target.setThresholdTarget(null);
                target.setAtLeastTarget(null);
                target.setScreamTarget(null);
                target.setHowlTarget(null);
                tValue = performanceTargetService.getNewByHierarchyId(target);
                if (tValue != null) {
                    tValue.setIsCheck(principalProfit.getIsCheck());
                    tValue.setWeight(weight);
                    performanceTargetService.updateTargetSelective(tValue);
                } else {
                    target.setWeight(weight);//设置权重
                    target.setIsCheck(principalProfit.getIsCheck());
                    performanceTargetService.insertTargetSelective(target);
                }
            }
            //将数据重新返回
            resultMap.put("list", principalProfitList);

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

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

            resultMap.put("vacancy", vacancy);//设置空缺数据
            resultMap.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
            return Response.response(resultMap);
        }
        // 未正常传入值过来
        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") 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.PrincipalProfitUpload(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 = "1019";
        return Response.response(performancePower.getUserPower(elementId, requestMap, request));
    }
}
