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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

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
 */
@Controller("SmallownersSatisfactionController")
@RequestMapping("/SmallownersSatisfactionController")
public class SmallownersSatisfactionController {

    @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 = 1002;
        Map<String, Object> returnMap = new LinkedHashMap<String, Object>();
        Map<String, Object> elementMap = new LinkedHashMap<String, Object>();


        PerformanceTarget t = new PerformanceTarget();      //参数bean
        PerformanceScore s = new PerformanceScore();
        PerformanceScore sValue = new PerformanceScore();   //pojo
        PerformanceTarget tValue = new PerformanceTarget();

        List<SmallownersSatisfaction> returnList = new ArrayList<SmallownersSatisfaction>();

        PerformanceElement element = new PerformanceElement();
        element.setElementId(elementid);
        //获得小业主下级 的ID 和 指标的名
        List<PerformanceElement> list = PerformanceElementService.getElementId(element);
        for (PerformanceElement aList : list) {
            //secondIds=new int[list2.size()];
            //secondIds[i]=Integer.parseInt(list2.get(i).getElementId().toString());
            if (aList.getName().equals("综合满意率")) {
                elementMap.put("综合满意率", aList.getElementId());
            }
            if (aList.getName().equals("管家服务满意率")) {
                elementMap.put("管家服务满意率", aList.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) {
            for (PerformanceEnv performanceEnv : envList) {
                SmallownersSatisfaction so = new SmallownersSatisfaction();

                String hierarchy_id = performanceEnv.getHierarchyId();

                so.setHierarchyId(hierarchy_id);
                //二、三级组织等
                so.setSecond_organization(performanceEnv.getHierarchyName());
                so.setThird_organization(performanceEnv.getHierarchyName());
                //设置显示格式
                so.setUnit(1);//单位（0-分，1-百分比，2-元，3-万元，4-平方米/人）


                t.setElementId(Long.parseLong(elementMap.get("综合满意率").toString()));
                t.setHierarchyId(hierarchy_id);
                t.setYear(years);
                t.setQuarterly(quarterly);
                tValue = PerformanceTargetService.getNewByHierarchyId(t);

                //获取对应的门槛等值
                if (null != tValue) {
                    so.setCompre_threshold(tValue.getThresholdTarget());
                    so.setCompre_atLeast(tValue.getAtLeastTarget());
                    so.setCompre_scream(tValue.getScreamTarget());
                    so.setCompre_howl(tValue.getHowlTarget());
                }

                //综合满意率的完成值和得分值
                s.setElementId(Long.parseLong(elementMap.get("综合满意率").toString()));
                s.setHierarchyId(hierarchy_id);
                s.setYear(years);
                s.setQuarterly(quarterly);
                sValue = PerformanceScoreService.getscoreByHierarchyId(s);

                if (sValue != null) {
                    so.setCompre_score(String.valueOf(sValue.getScore()));
                    so.setCompre_investigation(String.valueOf(sValue.getComplete()));
                } else {
                    so.setCompre_score(null);
                    so.setCompre_investigation(null);
                }

                t.setElementId(Long.parseLong(elementMap.get("管家服务满意率").toString()));
                t.setHierarchyId(hierarchy_id);
                t.setYear(years);
                t.setQuarterly(quarterly);
                tValue = PerformanceTargetService.getByHierarchyId(t);
                if (tValue != null) {
                    so.setButler_investigation(null);
                    so.setButler_threshold(tValue.getThresholdTarget());
                    so.setButler_atLeast(tValue.getAtLeastTarget());
                    so.setButler_scream(tValue.getScreamTarget());
                    so.setButler_howl(tValue.getHowlTarget());
                } else {
                    so.setButler_investigation(null);
                    so.setButler_threshold(null);
                    so.setButler_atLeast(null);
                    so.setButler_scream(null);
                    so.setButler_howl(null);
                }
                s.setElementId(Long.parseLong(elementMap.get("管家服务满意率").toString()));
                s.setHierarchyId(hierarchy_id);
                s.setYear(years);
                s.setQuarterly(quarterly);
                sValue = PerformanceScoreService.getscoreByHierarchyId(s);
                if (sValue != null) {
                    so.setButler_score(String.valueOf(sValue.getScore()));
                    so.setButler_investigation(String.valueOf(sValue.getComplete()));
                } else {
                    so.setButler_score(null);
                    so.setButler_investigation(null);
                }
                //小业主满意率
                s.setElementId(elementid);
                sValue = PerformanceScoreService.getscoreByHierarchyId(s);
                if (sValue != null) {
                    so.setIndividualScore(String.valueOf(sValue.getScore()));

                } else {
                    so.setIndividualScore(null);
                }
                //是否考核
                //so.setIs_check(1);
                /////////////////////////
                t.setElementId(elementid);
                tValue = PerformanceTargetService.getByHierarchyId(t);
                if (tValue != null) {
                    so.setIs_check(tValue.getIsCheck().equals("1") ? 1 : 0);
                } else {
                    so.setIs_check(1);
                }
                ///////////////////////
                so.setQuarter(quarterly);
                so.setYear(String.valueOf(years));
                returnList.add(so);
            }
            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<SmallownersSatisfaction> values) {
        List<SmallownersSatisfaction> result = new ArrayList<SmallownersSatisfaction>();
        Map<String, Object> map = new HashMap<String, Object>();

        long elementId;
        PerformanceScore score = new PerformanceScore();
        PerformanceScore sValue = new PerformanceScore();
        PerformanceTarget target = new PerformanceTarget();
        PerformanceTarget tValue = new PerformanceTarget();

        for (SmallownersSatisfaction smallownersSatisfaction : values) {
            String hierarchyId = smallownersSatisfaction.getHierarchyId();
            String year = smallownersSatisfaction.getYear();
            String quarter = smallownersSatisfaction.getQuarter();

            //综合管家
            String Compre_investigation = smallownersSatisfaction.getCompre_investigation();
            String Compre_threshold = smallownersSatisfaction.getCompre_threshold();
            String Compre_atLeast = smallownersSatisfaction.getCompre_atLeast();
            String Compre_scream = smallownersSatisfaction.getCompre_scream();
            String Compre_howl = smallownersSatisfaction.getCompre_howl();

            double weight = 1;
            String Compre_score = "-1";

            if (!StringUtil.isBlankOrEmpty(Compre_investigation)) {
                try {
                    Compre_score = Calculate.InsertionMethod(Double.parseDouble(Compre_investigation), Double.parseDouble(Compre_threshold), Double.parseDouble(Compre_atLeast), Double.parseDouble(Compre_scream), Double.parseDouble(Compre_howl), weight);
                } catch (NumberFormatException e) {
                }
            }
            if (smallownersSatisfaction.getIs_check() == 0){
                Compre_score = "-1";
            }
            smallownersSatisfaction.setCompre_score(Compre_score);
            //综合满意率入库得分表
            elementId = 1002001;
            score.setElementId(elementId);
            score.setQuarterly(quarter);
            score.setHierarchyId(hierarchyId);
            score.setYear(Integer.parseInt(year));
            sValue = PerformanceScoreService.getscoreByHierarchyId(score);
            Compre_investigation = StringUtil.isBlankOrEmpty(Compre_investigation) ? "-1" : Compre_investigation;
            if (sValue != null) {
                sValue.setComplete(Float.parseFloat(Compre_investigation));
                sValue.setScore(Float.parseFloat(Compre_score));
                PerformanceScoreService.updateScoreSelective(sValue);
            } else {
                score.setComplete(Float.parseFloat(Compre_investigation));
                score.setScore(Float.parseFloat(Compre_score));
                PerformanceScoreService.insertScoreSelective(score);
            }
            //插入目标值
            //[start]
            target.setElementId(elementId);
            target.setHierarchyId(hierarchyId);
            target.setYear(Integer.valueOf(year));
            target.setQuarterly(quarter);

            tValue = PerformanceTargetService.getNewByHierarchyId(target);
            if (tValue != null) {
                tValue.setThresholdTarget(String.valueOf(Compre_threshold));
                tValue.setAtLeastTarget(String.valueOf(Compre_atLeast));
                tValue.setScreamTarget(String.valueOf(Compre_scream));
                tValue.setHowlTarget(String.valueOf(Compre_howl));
                PerformanceTargetService.updateTargetSelective(tValue);
            } else {
                target.setThresholdTarget(String.valueOf(Compre_threshold));
                target.setAtLeastTarget(String.valueOf(Compre_atLeast));
                target.setScreamTarget(String.valueOf(Compre_scream));
                target.setHowlTarget(String.valueOf(Compre_howl));
                PerformanceTargetService.insertTargetSelective(target);
            }
            //[end]


            //管家服务满意率
            elementId = 1002002;
            String Butler_investigation = smallownersSatisfaction.getButler_investigation();
            String Butler_threshold = smallownersSatisfaction.getButler_threshold();
            String Butler_atLeast = smallownersSatisfaction.getButler_atLeast();
            String Butler_scream = smallownersSatisfaction.getButler_scream();
            String Butler_howl = smallownersSatisfaction.getButler_howl();
            double weight1 = 1;
            String Butler_score = "-1";

            if (!StringUtil.isBlankOrEmpty(Butler_investigation)) {
                try {
                    Butler_score = Calculate.InsertionMethod(Double.parseDouble(Butler_investigation), Double.parseDouble(Butler_threshold), Double.parseDouble(Butler_atLeast), Double.parseDouble(Butler_scream), Double.parseDouble(Butler_howl), weight1);
                } catch (NumberFormatException e) {

                }
            }
            if (smallownersSatisfaction.getIs_check() == 0){
                Butler_score = "-1";
            }
            smallownersSatisfaction.setButler_score(Butler_score);
            //管家入库得分表
            score.setElementId(elementId);
            Butler_investigation = StringUtil.isBlankOrEmpty(Butler_investigation) ? "-1" : Butler_investigation;
            sValue = PerformanceScoreService.getscoreByHierarchyId(score);
            if (sValue != null) {
                sValue.setComplete(Float.parseFloat(Butler_investigation));
                sValue.setScore(Float.parseFloat(Butler_score));
                PerformanceScoreService.updateScoreSelective(sValue);
            } else {
                score.setComplete(Float.parseFloat(Butler_investigation));
                score.setScore(Float.parseFloat(Butler_score));
                PerformanceScoreService.insertScoreSelective(score);
            }

            //[start]

            target.setElementId(elementId);
            tValue = PerformanceTargetService.getByHierarchyId(target);

            if (tValue != null) {
                tValue.setThresholdTarget(String.valueOf(Butler_threshold));
                tValue.setAtLeastTarget(String.valueOf(Butler_atLeast));
                tValue.setScreamTarget(String.valueOf(Butler_scream));
                tValue.setHowlTarget(String.valueOf(Butler_howl));
                PerformanceTargetService.updateTargetSelective(tValue);
            } else {
                target.setThresholdTarget(String.valueOf(Butler_threshold));
                target.setAtLeastTarget(String.valueOf(Butler_atLeast));
                target.setScreamTarget(String.valueOf(Butler_scream));
                target.setHowlTarget(String.valueOf(Butler_howl));
                PerformanceTargetService.insertTargetSelective(target);
            }
            //[end]


            //小业主满意率的指标单项得分
            float IndividualScore = -1;

            if (Compre_score.equals("-1") && Butler_score.equals("-1")) {
                IndividualScore = -1;
            }
            if (!Compre_score.equals("-1") && Butler_score.equals("-1")) {
                IndividualScore = Float.parseFloat(Compre_score);
            } else {
                IndividualScore = (float) (Float.parseFloat(Compre_score) * 0.8 + Float.parseFloat(Butler_score) * 0.2);
            }

            if (smallownersSatisfaction.getIs_check() == 0){
                IndividualScore = -1;
            }
            smallownersSatisfaction.setIndividualScore(String.valueOf(IndividualScore));
            elementId = 1002;
            score.setElementId(elementId);
            score.setScore(-1);
            score.setComplete(-1);
            sValue = PerformanceScoreService.getscoreByHierarchyId(score);
            if (sValue != null) {
                sValue.setScore(IndividualScore);
                PerformanceScoreService.updateScoreSelective(sValue);
            } else {
                score.setScore(IndividualScore);
                PerformanceScoreService.insertScoreSelective(score);
            }
            //指标考核
            target.setElementId(elementId);
            target.setThresholdTarget(null);
            target.setAtLeastTarget(null);
            target.setScreamTarget(null);
            target.setHowlTarget(null);
            tValue = PerformanceTargetService.getNewByHierarchyId(target);
            if (tValue != null) {
                tValue.setIsCheck(String.valueOf(smallownersSatisfaction.getIs_check()));
                PerformanceTargetService.updateTargetSelective(tValue);
            } else {
                target.setWeight(0.25);
                target.setIsCheck(String.valueOf(smallownersSatisfaction.getIs_check()));
                PerformanceTargetService.insertTargetSelective(target);
            }

            result.add(smallownersSatisfaction);
        }

        PerformanceScoreService.saveQuartlyAverageScoreAndSumScore(Integer.parseInt(values.get(0).getYear()), Integer.parseInt(values.get(0).getQuarter()));
        map.put("list", result);
        Long element_id = 1002L;
        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(element_id);
        int vacancy = count - PerformanceScoreService.getTotalPage(performanceScore).getTotalPage();//空缺，还有多少个区域指标没填
        if(vacancy<0){
            vacancy=0;
        }
        map.put("vacancy", vacancy);//设置空缺数据
        List<String> vacancyHierarchyName = PerformanceEnvService.selectNotInName(performanceScore);
        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", 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.SmallownersSatisfactionUpload(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 = "1002";//小业主的编码
        return Response.response(performancePower.getUserPower(elementId,requestMap,request));
    }
}
