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

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.performance.PerformanceArea;
import cn.com.countrygarden.bi.main.model.performance.PerformanceCompany;
import cn.com.countrygarden.bi.main.model.performance.PerformanceMonthly;
import cn.com.countrygarden.bi.main.model.performance.monthly.AllMonth;
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.PerformanceMonthlyService;
import cn.com.countrygarden.bi.main.service.performance.common.PerformanceAreaService;
import cn.com.countrygarden.bi.main.service.performance.common.PerformanceRecordService;
import cn.com.countrygarden.bi.main.util.Arith;
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 javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 城市公司月度绩效接口
 */
@Controller("CompanyMonthlyPerformanceController")
@RequestMapping("/CompanyMonthlyPerformanceController")
public class CompanyMonthlyPerformanceController {

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


    @Autowired
    AccessTokenService accessTokenService;

    @Autowired
    PerformanceRecordService performanceRecordService;

    @Autowired
    PerformanceAreaService performanceAreaService;

    @Autowired
    PerformanceMonthlyService performanceMonthlyService;

    @Autowired
    PerformancePower performancePower;

    @Autowired
    ExcelAnalysis ea;

    @RequestMapping(value = "/showTarget", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object showTarget(@RequestParam(value = "year") int year,@RequestParam(value = "month") int month,
                             @RequestParam(value = "elementId") long elementId,
                             @RequestParam(value = "pageSize") int pageSize, @RequestParam(value = "pageCurr") int pageCurr){

        Map<String,Object> returnMap = new HashMap<>();//用于返回的map
        List<AllMonth> returnList = new ArrayList<>();//返回的实体类集合

        try {
            //查询所有空缺的公司数量和名称
            List<String> vacancyHierarchyName = performanceRecordService.getMonthlyVacancyAreas(elementId,year, month,"2");
            int vacancy = vacancyHierarchyName.size();

            //查询所有有效的城市公司
            List<PerformanceArea> comList = performanceAreaService.getAllAreasByType("2");
            int count = comList.size();
            int start = (pageCurr - 1) * pageSize;
            int end = pageCurr * pageSize;

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

            if (comList.size() != 0) {
                for (int i = 0; i < comList.size(); i++) {
                    AllMonth allMonth = new AllMonth();

                    allMonth.setYear(year);
                    allMonth.setMonth(month);
                    allMonth.setElementId(elementId);

                    String hierarchyId = comList.get(i).getHierachyId();
                    String hierarchyName = comList.get(i).getHierachyName();

                    allMonth.setHierarchyId(hierarchyId);
                    allMonth.setHierarchyName(hierarchyName);
                    allMonth.setSecond_organization(hierarchyName);
                    allMonth.setThird_organization(hierarchyName);

                    PerformanceMonthly pm = new PerformanceMonthly(year, month, elementId, hierarchyId);
                    PerformanceMonthly rpm = performanceMonthlyService.getSelect(pm);
                    if (rpm != null) {
                        allMonth.setComplete(rpm.getComplete());
                        allMonth.setAnnualTarget(rpm.getAnnualTarget());
                        allMonth.setCompleteRate(rpm.getCompleteRate());
                    }

                    returnList.add(allMonth);
                }
                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(returnMap);
    }

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

        Map<String,Object> returnMap = new HashMap<>();//用户返回的map
        List<AllMonth> returnList = new ArrayList<>();

        int year = values.get(0).getYear();//年份
        int month = values.get(0).getMonth();//月份
        long elementId = values.get(0).getElementId();//指标编号

        for(AllMonth am : values){//遍历集合

            String hierarchyId = am.getHierarchyId();//城市公司id

            double complete = -1; //完成值
            double annualTarget = -1; // 年度目标值
            double completeRate = -1; //完成率

            if(!StringUtil.isBlankOrEmpty(am.getComplete())){
                complete = Double.parseDouble(am.getComplete());
                if(complete < 0 && complete != -1){
                    String errMsg = "完成值不能小于0!";
                    return Response.responseFail(errMsg);
                }
            }

            if(!StringUtil.isBlankOrEmpty(am.getAnnualTarget())){
                annualTarget = Double.parseDouble(am.getAnnualTarget());
                if(annualTarget < 0 && annualTarget != -1){
                    String errMsg = "年度目标值不能小于0!";
                    return Response.responseFail(errMsg);
                }
            }

            //计算完成率
            if(complete != -1 && annualTarget != -1){
                completeRate = Arith.div(complete,annualTarget,6);
            }

            //传入的对象
            PerformanceMonthly pm = new PerformanceMonthly(year,month,elementId,hierarchyId);

            PerformanceMonthly rpm = performanceMonthlyService.getSelect(pm);
            if(rpm == null){//新增
                pm.setComplete(String.valueOf(complete));
                pm.setAnnualTarget(String.valueOf(annualTarget));
                pm.setCompleteRate(String.valueOf(completeRate));
                pm.setCreatedDate(new Date());
                performanceMonthlyService.insertSelective(pm);
            }else{//更新
                rpm.setComplete(String.valueOf(complete));
                rpm.setAnnualTarget(String.valueOf(annualTarget));
                rpm.setCompleteRate(String.valueOf(completeRate));
                rpm.setUpdateDate(new Date());
                performanceMonthlyService.updateByPrimaryKeySelective(rpm);
            }

            //回传完成率
            am.setCompleteRate(String.valueOf(completeRate));

            returnList.add(am);
        }

        performanceMonthlyService.saveMonthAverageAndRank(elementId,year,month);

        //查询所有空缺的公司数量和名称
        List<String> vacancyHierarchyName = performanceRecordService.getMonthlyVacancyAreas(elementId,year,month,"2");
        int vacancy = vacancyHierarchyName.size();

        returnMap.put("list",returnList);
        returnMap.put("vacancy", vacancy);
        returnMap.put("vacancyHierarchyName", vacancyHierarchyName);//空缺的城市公司名称

        return Response.response(returnMap);
    }

    @RequestMapping(value ="/judgeLock",method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object judgeLock(@RequestBody Map<String, Object> requestMap, HttpServletRequest request){
        return Response.response(performancePower.getUserPowerMonthly(requestMap, request));
    }

    @RequestMapping(value = "/upload",method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object upload(@RequestParam(value = "year") int year, @RequestParam(value = "month") int month,
                         @RequestParam(value = "name") String name,@RequestParam(value = "elementId") long elementId,
                         @RequestParam(value = "uploadfile", required = true) MultipartFile multipartFile,
                         HttpServletRequest request, HttpServletResponse response){
        //判断账号是否存在
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        if(token == null){
            return Response.responseFail("账号不存在!");
        }
        //判断上传的文件是否存在
        if(multipartFile == null){
            return Response.responseFail("请选择需要上传的文件!");
        }else if(name == null){
            return Response.responseFail("请输入文件名");
        }
        //强制转换类型为CommonsMultipartFile实现类
        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
        if(commonsMultipartFile.isEmpty()){//判断size变量的长度
            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.monthlyPerformanceUpload(multipartFile,elementId,year,month,token.getUserCode());
            performanceMonthlyService.saveMonthAverageAndRank(elementId,year,month);
            return Response.response("导入成功");
        }catch (Exception e){
            LOGGER.info(e.getMessage());
            return Response.responseFail("导入失败! "+e.getMessage());
        }
    }
}


