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

//=======税前利润

import java.util.*;

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.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.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("PretaxprofitController")
@RequestMapping("/PretaxprofitController")
public class PretaxprofitController {
    @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) {
        // 默认id，税前利润
        long elementid = 1005;

        Map<String, Object> returnMap = new LinkedHashMap<String, Object>();// 返回值
        Map<String, Object> elementMap = new LinkedHashMap<String, Object>();// 接收值
        List<ProfitBeforeTax> returnList = new ArrayList<ProfitBeforeTax>();

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


        try {
            // 获得税前利润下级 的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<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);

            //查询多少条数据是录入的
            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);

            if (envList.size() != 0) {

                //@Author:Geoffrey
                //[start]
                for (PerformanceEnv performanceEnv : envList) {

                    ProfitBeforeTax profitBeforeTax = new ProfitBeforeTax();// 税前利润实体bean
                    String hierarchyId = performanceEnv.getHierarchyId();

                    profitBeforeTax.setSecond_organization(performanceEnv.getHierarchyName());// 项目区域
                    profitBeforeTax.setThird_organization(performanceEnv.getHierarchyName());// 项目区域
                    profitBeforeTax.setHierarchyId(hierarchyId);
                    profitBeforeTax.setYear(String.valueOf(years));
                    profitBeforeTax.setQuarter(quarterly);

                    t.setHierarchyId(hierarchyId);
                    t.setYear(years);

                    s.setHierarchyId(hierarchyId);
                    s.setYear(years);


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

                    sValue = performanceScoreService.getscoreByHierarchyId(s);
                    if (sValue != null) {
                        profitBeforeTax.setHY_Complete_Value(String.valueOf(sValue.getComplete()));
                        profitBeforeTax.setHY_score(String.valueOf(sValue.getScore()));
                    }

                    t.setElementId(Long.parseLong(elementMap.get("综合税前利润").toString()));
                    tValue = performanceTargetService.getNewByHierarchyId(t);
                    if (tValue != null) {
                        profitBeforeTax.setHY_threshold(tValue.getThresholdTarget());
                        profitBeforeTax.setHY_atLeast(tValue.getAtLeastTarget());
                        profitBeforeTax.setHY_scream(tValue.getScreamTarget());
                        profitBeforeTax.setHY_howl(tValue.getHowlTarget());
                    }

                    // 上半年 税前利润 HYC
                    s.setElementId(Long.parseLong(elementMap.get("社区经营服务（N）税前利润").toString()));
                    sValue = performanceScoreService.getscoreByHierarchyId(s);

                    if (sValue != null) {
                        profitBeforeTax.setHYC_Complete_Value(String.valueOf(sValue.getComplete()));
                        profitBeforeTax.setHYC_score(String.valueOf(sValue.getScore()));
                    }

                    t.setElementId(Long.parseLong(elementMap.get("社区经营服务（N）税前利润").toString()));
                    tValue = performanceTargetService.getNewByHierarchyId(t);

                    if (tValue != null) {
                        profitBeforeTax.setHYC_threshold(tValue.getThresholdTarget());
                        profitBeforeTax.setHYC_atLeast(tValue.getAtLeastTarget());
                        profitBeforeTax.setHYC_scream(tValue.getScreamTarget());
                        profitBeforeTax.setHYC_howl(tValue.getHowlTarget());
                    }
//------------------------------------------------------------------------------------------------//
                    //全年 综合利润 AL
                    s.setElementId(Long.parseLong(elementMap.get("综合税前利润").toString()));

                    s.setQuarterly(quarterly);
                    t.setQuarterly(quarterly);

                    sValue = performanceScoreService.getscoreByHierarchyId(s);
                    if (sValue != null) {
                        profitBeforeTax.setAL_Complete_Value(String.valueOf(sValue.getComplete()));
                        profitBeforeTax.setAL_score(String.valueOf(sValue.getScore()));
                    }

                    t.setElementId(Long.parseLong(elementMap.get("综合税前利润").toString()));
                    tValue = performanceTargetService.getNewByHierarchyId(t);
                    if (tValue != null) {
                        profitBeforeTax.setAL_threshold(tValue.getThresholdTarget());
                        profitBeforeTax.setAL_atLeast(tValue.getAtLeastTarget());
                        profitBeforeTax.setAL_scream(tValue.getScreamTarget());
                        profitBeforeTax.setAL_howl(tValue.getHowlTarget());
                    }

                    // 全年 税前利润 ALC
                    s.setElementId(Long.parseLong(elementMap.get("社区经营服务（N）税前利润").toString()));
                    sValue = performanceScoreService.getscoreByHierarchyId(s);

                    if (sValue != null) {
                        profitBeforeTax.setALC_Complete_Value(String.valueOf(sValue.getComplete()));
                        profitBeforeTax.setALC_score(String.valueOf(sValue.getScore()));
                    }

                    t.setElementId(Long.parseLong(elementMap.get("社区经营服务（N）税前利润").toString()));
                    tValue = performanceTargetService.getNewByHierarchyId(t);

                    if (tValue != null) {
                        profitBeforeTax.setALC_threshold(tValue.getThresholdTarget());
                        profitBeforeTax.setALC_atLeast(tValue.getAtLeastTarget());
                        profitBeforeTax.setALC_scream(tValue.getScreamTarget());
                        profitBeforeTax.setALC_howl(tValue.getHowlTarget());
                    }

                    //指标总得分
                    s.setElementId(elementid);
                    s.setQuarterly(quarterly);
                    sValue = performanceScoreService.getscoreByHierarchyId(s);
                    if (sValue != null) {
                        profitBeforeTax.setIndividualScore(String.valueOf(sValue.getScore()));
                    }

                    /////////////////////////
                    PerformanceTarget tft = new PerformanceTarget();
                    tft.setYear(years);//年
                    tft.setQuarterly(quarterly);//季度
                    tft.setHierarchyId(hierarchyId);//区域
                    tft.setElementId(elementid);
                    PerformanceTarget tftValue = performanceTargetService.getNewByHierarchyId(tft);
                    if (tftValue != null) {
                        profitBeforeTax.setIs_check(tftValue.getIsCheck().equals("1") ? 1 : 0);
                    } else {
                        profitBeforeTax.setIs_check(1);
                    }
                    ///////////////////////

                    returnList.add(profitBeforeTax);
                }
                //[end]

                returnMap.put("list", returnList);
                returnMap.put("totalPage", count);
                returnMap.put("vacancy", vacancy);
                returnMap.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Response.response(returnMap);
    }

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

        PerformanceElement element = new PerformanceElement();// 社区经营服务下级 的ID 和
        // 指标的名称
        Map<String, Long> elementIdMap = new LinkedHashMap<>();
        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();// 返回值
        // 获取一级税前利润的id
        List<PerformanceElement> list2 = null;
        // 获取一级id的list
        long elementId = 1005;// 默认id，税前利润
        PerformanceScore score = new PerformanceScore();// 操作值
        PerformanceScore sValue = new PerformanceScore();
        PerformanceTarget target = new PerformanceTarget();
        PerformanceTarget tValue = new PerformanceTarget();
        if (values.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 (ProfitBeforeTax profitBeforeTax : values) {

                String HierarchyId = profitBeforeTax.getHierarchyId();
                int year = Integer.parseInt(profitBeforeTax.getYear());
                int quarter = Integer.parseInt(profitBeforeTax.getQuarter());

                String[] thresholds = {profitBeforeTax.getHY_threshold(), profitBeforeTax.getAL_threshold(), profitBeforeTax.getHYC_threshold(), profitBeforeTax.getALC_threshold()};
                String[] atLasts = {profitBeforeTax.getHY_atLeast(), profitBeforeTax.getAL_atLeast(), profitBeforeTax.getHYC_atLeast(), profitBeforeTax.getALC_atLeast()};
                String[] screams = {profitBeforeTax.getHY_scream(), profitBeforeTax.getAL_scream(), profitBeforeTax.getHYC_scream(), profitBeforeTax.getALC_scream()};
                String[] howls = {profitBeforeTax.getHY_howl(), profitBeforeTax.getAL_howl(), profitBeforeTax.getHYC_howl(), profitBeforeTax.getALC_howl()};
                String[] completes = {profitBeforeTax.getHY_Complete_Value(), profitBeforeTax.getAL_Complete_Value(), profitBeforeTax.getHYC_Complete_Value(), profitBeforeTax.getALC_Complete_Value()};
                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.setElementId(subElementId);
                    score.setQuarterly(String.valueOf(q));
                    sValue = performanceScoreService.getscoreByHierarchyId(score);//查询有没有这条记录
                    if (sValue != null) {
                        sValue.setComplete((float) complete);//插入实际值：就是完成值
                        sValue.setScore(Float.parseFloat(scores[i])); //综合收缴率细项得分
                        performanceScoreService.updateScoreSelective(sValue);
                    } else {
                        score.setComplete((float) complete);//插入实际值：就是完成值
                        score.setScore(Float.parseFloat(scores[i])); //综合收缴率细项得分
                        performanceScoreService.insertScoreSelective(score);
                    }

                    //更新目标值

                    target.setElementId(subElementId);
                    target.setQuarterly(String.valueOf(q));
                    tValue = performanceTargetService.getByHierarchyId(target);
                    if (tValue != null) {
                        tValue.setThresholdTarget(String.valueOf(atLeast));  //没有门槛值，门槛值跟保底值相等
                        tValue.setAtLeastTarget(String.valueOf(atLeast));
                        tValue.setScreamTarget(String.valueOf(scream));
                        tValue.setHowlTarget(String.valueOf(howl));
                        performanceTargetService.updateTargetSelective(tValue);
                    } else {
                        target.setThresholdTarget(String.valueOf(atLeast));  //没有门槛值，门槛值跟保底值相等
                        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";

                profitBeforeTax.setHY_score(String.valueOf(HY_score));
                profitBeforeTax.setAL_score(String.valueOf(AL_score));
                profitBeforeTax.setHYC_score(String.valueOf(HYC_score));
                profitBeforeTax.setALC_score(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);
                }

                profitBeforeTax.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(profitBeforeTax.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(String.valueOf(profitBeforeTax.getIs_check()));
                    performanceTargetService.updateTargetSelective(tValue);
                } else {
                    target.setWeight(0.1);
                    target.setIsCheck(String.valueOf(profitBeforeTax.getIs_check()));
                    performanceTargetService.insertTargetSelective(target);
                }


            }
            resultMap.put("list", values);
            List<PerformanceEnv> envList = performanceEnvService.selectPerformanceOrgan();
            int count = envList.size();
            PerformanceScore performanceScore = new PerformanceScore();
            performanceScore.setYear(Integer.parseInt(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(Integer.parseInt(values.get(0).getYear()), Integer.parseInt(values.get(0).getQuarter()));
            resultMap.put("vacancy", vacancy);//设置空缺数据
            List<String> vacancyHierarchyName = performanceEnvService.selectNotInName(performanceScore);
            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", 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.PretaxProfitUpload(multipartFile, year, quarter, "0000");
            ea.PretaxProfitUpload(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 = "1005";//税前利润
        return Response.response(performancePower.getUserPower(elementId,requestMap,request));
    }
}
