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

import java.util.*;

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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
//人均管理面积

@Controller("PermanagementareaController")
@RequestMapping("/PermanagementareaController")
public class PermanagementareaController {

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

    @Autowired
    private PerformanceEnvService performanceEnvService;

    @Autowired
    private PerformanceTargetService performanceTargetService;

    @Autowired
    private PerformanceScoreService performanceScoreService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private ExcelAnalysis ea;

    @Autowired
    private  PerformancePower performancePower;

    /*
        修改实际值取值错误和空值报错异常
        @author Max 陈彩君 Date:2018/06/29
     */
    @ResponseBody
    @RequestMapping(value = "/Permanagementarea", 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") int quarterly) {
        Map<String, Object> map = new LinkedHashMap<>();// 返回值
        long elementId = 1008;// 人均管理面积id

        List<PerManagementArea> perManagementAreaList = new ArrayList<>();

        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);//取开始和结束范围内的值

        String thisQuarter = String.valueOf(quarterly);//季度值

        //查询多少条数据是录入的
        PerformanceScore performanceScore = new PerformanceScore();
        performanceScore.setYear(years);//年
        performanceScore.setQuarterly(thisQuarter);//季度
        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) {
                PerManagementArea perManagementArea = new PerManagementArea();
                perManagementArea.setHierarchyId(performanceEnv.getHierarchyId());//组织id
                perManagementArea.setSecond_organization(performanceEnv.getHierarchyName());//二级组织
                perManagementArea.setThird_organization(performanceEnv.getHierarchyName());//三级组织
                perManagementArea.setYear(years);//设置年份
                perManagementArea.setQuarter(thisQuarter);//设置季度

                //target表里的相关记录
                PerformanceTarget t = new PerformanceTarget();
                t.setYear(years);//年
                t.setQuarterly(thisQuarter);//季度
                t.setHierarchyId(performanceEnv.getHierarchyId());//区域
                t.setElementId(elementId);//元均产值id
                PerformanceTarget tValue = performanceTargetService.getByHierarchyId(t);
                if (tValue != null) {
                    //是否考核,1表示考核，0表示不考核
                    perManagementArea.setIs_check(tValue.getIsCheck().equals("1") ? 1 : 0);
                }

                //score表里的相关记录
                PerformanceScore scores = new PerformanceScore();
                scores.setYear(years);//年
                scores.setQuarterly(thisQuarter);//季度
                scores.setHierarchyId(performanceEnv.getHierarchyId());//区域
                scores.setElementId(elementId);//元均产值id
                PerformanceScore score = performanceScoreService.getscoreByHierarchyId(scores);
                if (score != null) {
                    perManagementArea.setArea_RealValue(String.valueOf(score.getComplete()));//实际值
                    perManagementArea.setIndividualScore(String.valueOf(score.getScore()));// 指标单项得分
                }
                perManagementAreaList.add(perManagementArea);
            }
            map.put("list", perManagementAreaList);
            map.put("totalPage", count);
            map.put("vacancy", vacancy);
        } else {
            map.put("list", null);
            map.put("totalPage", 0);
            map.put("vacancy", count);
        }
        map.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
        return Response.response(map);
    }

    /*
    修改score更新和五个目标值更新
    @author Max 陈彩君 Date:2018/06/28

    @Modified By:Geoffrey 孙鹏
    @Modified  该指标不计算分数，直接修改分数保存
     */
    // 人均管理计算
    @ResponseBody
    @RequestMapping(value = "/CountValue", method = {RequestMethod.POST, RequestMethod.GET})
    public Object TotalCalculate(@RequestBody List<PerManagementArea> values) {

        long elementid = 1008;// 人均管理
        try {
            for (PerManagementArea value : values) {
                PerformanceScore scores = new PerformanceScore();// 操作值
                String Completes = value.getArea_RealValue();
                String score = value.getIndividualScore();

                if (StringUtil.isBlankOrEmpty(Completes)) {
                    continue;
                }
                // 动态设值
                scores.setYear(value.getYear());// 年度
                scores.setQuarterly(value.getQuarter());//设置季度值
                scores.setHierarchyId(value.getHierarchyId());// 区域
                scores.setElementId(elementid);// 按指标

                PerformanceScore score1 = performanceScoreService.getscoreByHierarchyId(scores);//查询有没有这条记录
                if (score1 != null) {
                    score1.setScore(Float.parseFloat(score));
                    score1.setComplete(Float.parseFloat(Completes));
                    score1.setUpdateDate(new Date());//修改日期
                    performanceScoreService.updateScoreSelective(score1);
                } else {
                    scores.setScore(Float.parseFloat(score));
                    scores.setComplete(Float.parseFloat(Completes));
                    scores.setCreatedDate(new Date());//创建日期
                    performanceScoreService.insertScoreSelective(scores);
                }

                //得到唯一目标值
                PerformanceTarget performanceTarget = new PerformanceTarget();
                performanceTarget.setYear(value.getYear());//按年度
                performanceTarget.setQuarterly(value.getQuarter());//按季度
                performanceTarget.setHierarchyId(value.getHierarchyId());//按区域
                performanceTarget.setElementId(elementid);//按指标
                //得到target表中唯一记录——根据上面四个值
                PerformanceTarget selectTarget = performanceTargetService.getByHierarchyId(performanceTarget);
                if (selectTarget != null) {
                    selectTarget.setIsCheck(String.valueOf(value.getIs_check()));
                    selectTarget.setUpdateDate(new Date());
                    performanceTargetService.updateTargetSelective(selectTarget);
                } else {
                    performanceTarget.setIsCheck(String.valueOf(value.getIs_check()));
                    performanceTarget.setCreatedDate(new Date());
                    performanceTarget.setWeight(0.05);
                    performanceTargetService.insertTargetSelective(performanceTarget);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Response.response("计算失败，请重新确认数据！");
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("list", values);
        List<PerformanceEnv> envList = performanceEnvService.selectPerformanceOrgan();
        int count = envList.size();
        PerformanceScore performanceScore = new PerformanceScore();
        performanceScore.setYear(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(values.get(0).getYear(), Integer.parseInt(values.get(0).getQuarter()));
        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) 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 {
            //ea.permanagementareaUpload(multipartFile, year, quarter, "0000");
            ea.permanagementareaUpload(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 = "1008";// 人均管理面积id
        return Response.response(performancePower.getUserPower(elementId,requestMap,request));
    }
}