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.PerformanceEnv;
import cn.com.countrygarden.bi.main.model.performance.PerformanceScore;
import cn.com.countrygarden.bi.main.model.performance.PerformanceTarget;
import cn.com.countrygarden.bi.main.model.performance.ProfitScale;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceElementService;
import cn.com.countrygarden.bi.main.service.performance.PerformanceEnvService;
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.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 java.util.*;

/**
 * 非指标—利润规模
 * @author Max Date:2018/09/10
 * @version 1.0
 * @since 1.8
 */
@Controller
@RequestMapping("/profitScale")
public class ProfitScaleController {
    private Logger logger = LoggerFactory.getLogger(ProfitScaleController.class);

    @Autowired
    private PerformanceTargetService performanceTargetService;

    @Autowired
    private PerformanceScoreService performanceScoreService;

    @Autowired
    private PerformanceElementService performanceElementService;

    @Autowired
    private PerformanceEnvService performanceEnvService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private ExcelAnalysis excelAnalysis;

    @Autowired
    private PerformancePower performancePower;

    @ResponseBody
    @RequestMapping(value = "/show", method = {RequestMethod.POST, RequestMethod.GET})
    public Object showTarget(@RequestParam(value = "pageCurr") int pageCurr, @RequestParam(value = "pageSize") int pageSize, @RequestParam(value = "years") int year, @RequestParam(value = "quarterly") String quarterly){

        long elementId = 999;//利润规模

        //返回前端界面的数据
        List<ProfitScale> profitScales = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();

        //区域-分页
        List<PerformanceEnv> envList = performanceEnvService.selectPerformanceOrgan();
        int count = envList.size();
        int start = (pageCurr - 1) * pageSize;
        int end = pageCurr * pageSize;

        //查询多少条数据是录入的
        PerformanceScore performanceScore = new PerformanceScore();
        performanceScore.setYear(year);//年
        performanceScore.setQuarterly(quarterly);//季度
        performanceScore.setElementId(elementId);

        List<String> vacancyHierarchyName = performanceEnvService.selectNotInName(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++) {
                //装载充填数据
                ProfitScale profitScale=new ProfitScale();
                profitScale.setHierarchyId(envList.get(i).getHierarchyId());//组织id
                profitScale.setSecond_organization(envList.get(i).getHierarchyName());//二级组织
                profitScale.setThird_organization(envList.get(i).getHierarchyName());//三级组织
                profitScale.setYear(year);//设置年份
                profitScale.setQuarter(quarterly);//设置季度

                //查询利润规模
                PerformanceScore score = new PerformanceScore();
                score.setYear(year);//年
                score.setQuarterly(quarterly);//季度
                score.setHierarchyId(envList.get(i).getHierarchyId());//区域
                score.setElementId(elementId);//利润规模id
                PerformanceScore sValue = performanceScoreService.getscoreByHierarchyId(score);
                if (sValue != null) {
                    //设置利润规模
                    try {
                        profitScale.setProScale(String.valueOf(sValue.getScore()));
                    } catch (Exception e) {
                        profitScale.setProScale("0");
                    }
                }
                profitScales.add(profitScale);//装载数据
            }
            map.put("list", profitScales);
            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);
    }

    @ResponseBody
    @RequestMapping(value = "/count", method = {RequestMethod.POST, RequestMethod.GET})
    public Object TotalCalculate(@RequestBody List<ProfitScale> profitScales) {
        Map<String, Object> map = new HashMap<>();

        long elementId = 999;//利润规模

        //遍历前端传过来的数据
        for(ProfitScale profitScale:profitScales){
            PerformanceScore score = new PerformanceScore();
            //设置score查询条件，查看是否有记录，有则更新，无则插入
            score.setYear(profitScale.getYear());//年
            score.setQuarterly(profitScale.getQuarter());//季度
            score.setHierarchyId(profitScale.getHierarchyId());//区域
            score.setElementId(elementId);
            PerformanceScore sValue = performanceScoreService.getNewScore(score);//查询有没有这条记录
            //判断是否有重复，是就更新，否就新增
            if (sValue != null) {
                //利润规模
                try {
                    sValue.setScore(StringUtil.isNotEmpty(profitScale.getProScale())?Float.parseFloat(profitScale.getProScale()):0);
                } catch (NumberFormatException e) {
                    sValue.setScore(0);
                }
                sValue.setUpdateDate(new Date());//更新时间
                performanceScoreService.updateScoreSelective(sValue);//更新
            } else {
                //利润规模
                try {
                    score.setScore(StringUtil.isNotEmpty(profitScale.getProScale())?Float.parseFloat(profitScale.getProScale()):0);
                } catch (NumberFormatException e) {
                    score.setScore(0);
                }
                score.setCreatedDate(new Date());//创建日期
                //插入
                performanceScoreService.insertScoreSelective(score);
            }

            //为了不影响其他业务，需要添加target数据
            PerformanceTarget target= new PerformanceTarget();
            target.setYear(profitScale.getYear());//年
            target.setQuarterly(profitScale.getQuarter());//季度
            target.setHierarchyId(profitScale.getHierarchyId());//区域
            target.setElementId(elementId);//指标
            PerformanceTarget tValue = performanceTargetService.getByHierarchyId(target);
            if(tValue!=null){//存在，则更新
                tValue.setUpdateDate(new Date());
                performanceTargetService.updateTargetSelective(tValue);//执行更新操作
            }else {
                target.setCreatedDate(new Date());
                performanceTargetService.insertTargetSelective(target);//执行新增操作
            }
        }

        map.put("list", profitScales);

        //设置空缺数据
        PerformanceScore performanceScore = new PerformanceScore();
        performanceScore.setYear(profitScales.get(0).getYear());//年
        performanceScore.setQuarterly(profitScales.get(0).getQuarter());//季度
        performanceScore.setElementId(elementId);

        List<String> vacancyHierarchyName = performanceEnvService.selectNotInName(performanceScore);
        int vacancy=vacancyHierarchyName.size();

        map.put("vacancy", vacancy);//设置空缺数据
        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") 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 {
            excelAnalysis.profitScaleControllerUpload(multipartFile, year, quarter, token.getUserCode());
        } 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 = "999";
        return Response.response(performancePower.getUserPower(elementId, requestMap, request));
    }
}
