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 javax.servlet.http.HttpServletResponse;
import java.util.*;

/*
 * 城市公司-业主满意率指标
 */
@Controller("OwnersSatisfactionController")
@RequestMapping("/OwnersSatisfactionController")
public class OwnersSatisfactionController {

    Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PerformancePower performancePower;

    @Autowired
    private PerformanceCompanyService performanceCompanyService;

    @Autowired
    private PerformanceScoreService performanceScoreService;

    @Autowired
    private PerformanceTargetService performanceTargetService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private ExcelAnalysis ea;

    /**
     * 查询所有指标相关值
     * @param pageSize
     * @param pageCurr
     * @param years
     * @param quarterly
     * @return
     */
    @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 = 1016;

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

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

        try {
            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(years);//年
            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++) {
                    OwnersSatisfaction o = new OwnersSatisfaction();

                    o.setSecond_organization(envList.get(i).getHierarchyName());//二级区域
                    o.setThird_organization(envList.get(i).getHierarchyName());//三级区域
                    o.setHierarchyId(envList.get(i).getHierarchyId());//城市公司id
                    o.setYear(String.valueOf(years));//年份
                    o.setQuarter(quarterly);//季度

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

                    score.setHierarchyId(hierarchy_id);//城市公司Id
                    score.setElementId(elementId);
                    score.setYear(years);
                    score.setQuarterly(quarterly);
                    sValue = performanceScoreService.getscoreByHierarchyId(score);
                    if (sValue != null) {
                        o.setInvestigation(String.valueOf(sValue.getComplete()));
                        o.setIndividualScore(String.valueOf(sValue.getScore()));
                    }

                    target.setElementId(elementId);
                    target.setHierarchyId(hierarchy_id);
                    target.setYear(years);
                    target.setQuarterly(quarterly);
                    PerformanceTarget tValue = performanceTargetService.getByHierarchyId(target);
                    if (tValue != null) {
                        o.setThreshold(tValue.getThresholdTarget());
                        o.setAtLeast(tValue.getAtLeastTarget());
                        o.setScream(tValue.getScreamTarget());
                        o.setHowl(tValue.getHowlTarget());
                        o.setIs_check(tValue.getIsCheck().equals("1") ? 1 : 0);
                    }
                    returnList.add(o);
                }
                returnMap.put("list", returnList);
                returnMap.put("totalPage", count);
                returnMap.put("vacancy", vacancy);
                returnMap.put("vacancyHierarchyName", vacancyHierarchyName);
            }
        }catch (Exception e){
            LOGGER.info(e.getMessage());
            return Response.response(e.getMessage());
        }
        return Response.response(returnMap);
    }

    /**
     * 指标相关值计算
     * @param values
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/TotalCalculate", method = {RequestMethod.POST, RequestMethod.GET})
    public Object TotalCalculate(@RequestBody List<OwnersSatisfaction> values) {
        List<OwnersSatisfaction> returnList = new ArrayList<>();

        Map<String, Object> resultMap = new HashMap<>();
        long elementId = 1016L;

        double weight = 0;
        for (OwnersSatisfaction value : values) {

            String year = value.getYear();
            String hierarchyId = value.getHierarchyId();
            Integer quarter = Integer.parseInt(value.getQuarter());
            quarter = quarter > 4 ? 4 : quarter;
            String type = performanceCompanyService.getTypeByComId(hierarchyId);
            switch (type){
                case "单一业主项目":
                    weight = 0.3;
                    break;
                case "多业主第一年":
                    weight = 0.5;
                    break;
                case "多业主第二年":
                    weight = 0.4;
                    break;
            }

            String complete = value.getInvestigation();//完成值就是调查情况值
            if (complete == null || "".equals(complete)) {
                complete = "-1";
            }

            String threshold = value.getThreshold();
            if (threshold == null || "".equals(threshold))
                threshold = "-1";

            String atLeast = value.getAtLeast();
            if (atLeast == null || "".equals(atLeast))
                atLeast = "-1";

            //1.门槛值有&&保底值有 2.门槛值无且保底值有的情况 门槛值才是保底值的80%
            if ((!"-1".equals(threshold) && !"-1".equals(atLeast)) || ("-1".equals(threshold) && !"-1".equals(atLeast))) {
                double d = Float.parseFloat(atLeast) * 0.8;
                threshold = String.valueOf(d < 0 ? -1 : d);
            }

            String scream = value.getScream();
            if (scream == null || "".equals(scream))
                scream = "-1";

            String howl = value.getHowl();
            if (howl == null || "".equals(howl))
                howl = "-1";

            double default_weight = 1;
            String IndividualScore = "-1";
            if (!complete.equals("-1")) {
                IndividualScore = Calculate.InsertionMethod(Double.parseDouble(complete), Double.parseDouble(threshold), Double.parseDouble(atLeast), Double.parseDouble(scream), Double.parseDouble(howl), default_weight);
            }
            value.setIndividualScore(IndividualScore);

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

            try {
                //传参Score对象
                PerformanceScore score = new PerformanceScore();
                //入库得分表
                score.setElementId(elementId);
                score.setYear(Integer.parseInt(year));
                score.setHierarchyId(hierarchyId);
                score.setQuarterly(String.valueOf(quarter));

                //季度得分
                PerformanceScore sValue = performanceScoreService.getscoreByHierarchyId(score);
                if (sValue != null) {
                    //如果值为非空，则更新数据
                    sValue.setScore(Float.parseFloat(IndividualScore));
                    sValue.setComplete(Float.parseFloat(complete));
                    performanceScoreService.updateScoreSelective(sValue);
                } else {
                    //插入数据
                    score.setScore(Float.parseFloat(IndividualScore));
                    score.setComplete(Float.parseFloat(complete));
                    performanceScoreService.insertScore(score);
                }

                //传参Target对象
                PerformanceTarget target = new PerformanceTarget();
                //更新目标值
                target.setElementId(elementId);
                target.setQuarterly(String.valueOf(quarter));
                target.setHierarchyId(hierarchyId);
                target.setYear(Integer.parseInt(year));

                PerformanceTarget tValue = performanceTargetService.getNewByHierarchyId(target);
                if (tValue != null) {
                    tValue.setThresholdTarget(threshold);
                    tValue.setAtLeastTarget(atLeast);
                    tValue.setScreamTarget(scream);
                    tValue.setHowlTarget(howl);
                    tValue.setWeight(weight);
                    tValue.setIsCheck(String.valueOf(value.getIs_check()));
                    performanceTargetService.updateTargetSelective(tValue);
                } else {
                    target.setThresholdTarget(threshold);
                    target.setAtLeastTarget(atLeast);
                    target.setScreamTarget(scream);
                    target.setHowlTarget(howl);
                    target.setWeight(weight);
                    target.setIsCheck(String.valueOf(value.getIs_check()));
                    performanceTargetService.insertTargetSelective(target);
                }
                returnList.add(value);


                performanceScoreService.saveQuartlyAverageScoreAndSumScore(Integer.parseInt(values.get(0).getYear()), Integer.parseInt(values.get(0).getQuarter()));
                resultMap.put("list", returnList);

                PerformanceScore performanceScore = new PerformanceScore();
                performanceScore.setYear(Integer.parseInt(values.get(0).getYear()));//年
                performanceScore.setQuarterly(values.get(0).getQuarter());//季度
                performanceScore.setElementId(elementId);
                List<String> vacancyHierarchyName = performanceCompanyService.selectNotInNameCompany(performanceScore);
                int vacancy = vacancyHierarchyName.size();

                resultMap.put("vacancy", vacancy);//设置空缺数据
                resultMap.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
            } catch (Exception e) {
                LOGGER.info(e.getMessage());
            }
        }
        return Response.response(resultMap);
    }

    /**
     * 查询和更新解锁状态，handle=1表示查询，handle=2表示更新
     * @param requestMap
     * @param request
     * @return Object
     * @Author Wyman
     */
    @ResponseBody
    @RequestMapping(value = "/judgeLock")
    public Object judgeLock(@RequestBody Map<String, Object> requestMap, HttpServletRequest request){
        String elementId = "1016";
        return Response.response(this.performancePower.getUserPower(elementId,requestMap,request));
    }

    /**
     *  excel表格数据上传
     * @param year
     * @param quarter
     * @param name
     * @param multipartFile
     * @param request
     * @param response
     * @return
     * @throws ServiceException
     */
    @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.OwnersSatisfactionUpload(multipartFile, year, quarter, token.getUserCode());
            performanceScoreService.saveQuartlyAverageScoreAndSumScore(year, quarter);
            return Response.response("导入成功");
        } catch (Exception e) {
            return Response.responseFail(e.getMessage());
        }
    }
}
