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

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.PerformanceArea;
import cn.com.countrygarden.bi.main.model.performance.PerformanceEnv;
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.PerformanceEnvService;
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 java.util.*;

/**
 * 月度—区域
 *
 * @author Max Date:2018/09/18
 * @version 1.0
 * @since 1.8
 */
@Controller
@RequestMapping("/regionMonthly")
public class RegionMonthlyController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private PerformanceRecordService performanceRecordService;

    @Autowired
    private PerformanceAreaService performanceAreaService;

    @Autowired
    private PerformanceMonthlyService performanceMonthlyService;

    @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 = "elementId") long elementId, @RequestParam(value = "pageCurr") int pageCurr,
                             @RequestParam(value = "pageSize") int pageSize, @RequestParam(value = "year") int year, @RequestParam(value = "month") int month) {
        //设置内容返回对象
        Map<String, Object> map = new HashMap<>();
        List<AllMonth> allMonths = new ArrayList<>();

        //首先查询区域进行分页
        List<PerformanceArea> envList = performanceAreaService.getAllAreasByType("1");
        int count = envList.size();
        int start = (pageCurr - 1) * pageSize;
        int end = pageCurr * pageSize;

        //查询还有多少个区域是还没有填写的
        List<String> vacancyHierarchyName = performanceRecordService.getMonthlyVacancyAreas(elementId,year,month,"1");
        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++) {
                AllMonth allMonth = new AllMonth();
                //设置通过数据
                allMonth.setYear(year);//年
                allMonth.setMonth(month);//月
                allMonth.setElementId(elementId);//指标
                allMonth.setHierarchyId(envList.get(i).getHierachyId());//区域id
                allMonth.setHierarchyName(envList.get(i).getHierachyName());//区域名称
                allMonth.setSecond_organization(envList.get(i).getHierachyName());//二级组织
                allMonth.setThird_organization(envList.get(i).getHierachyName());//三级组织

                //查询Performancce_monthly数据
                PerformanceMonthly performanceMonthly = new PerformanceMonthly();
                performanceMonthly.setYear(year);//年
                performanceMonthly.setMonth(month);//月
                performanceMonthly.setHierarchyId(envList.get(i).getHierachyId());//区域
                performanceMonthly.setElementId(elementId);//指标
                PerformanceMonthly pValue = performanceMonthlyService.getSelect(performanceMonthly);//查询
                if (pValue != null) {
                    allMonth.setComplete(pValue.getComplete());//完成值
                    allMonth.setAnnualTarget(pValue.getAnnualTarget());//目标值
                    allMonth.setCompleteRate(pValue.getCompleteRate());//完成率
                }
                allMonths.add(allMonth);
            }
        }
        map.put("list", allMonths);
        map.put("totalPage", count);
        map.put("vacancy", vacancy);
        map.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称
        return Response.response(map);
    }

    //保存接口
    @ResponseBody
    @RequestMapping(value = "/count", method = {RequestMethod.POST, RequestMethod.GET})
    public Object TotalCalculate(@RequestBody List<AllMonth> allMonths) {

        //设置内容返回对象
        Map<String, Object> map = new HashMap<>();

        //遍历数据进行计算
        for (AllMonth allMonth : allMonths) {

            double compelete = -1;//完成值
            double annualTarget = -1;//目标值
            double completeRate = -1;//完成率

            //完成值
            if (StringUtil.isNotEmpty(allMonth.getComplete())) {
                try {
                    compelete = Double.parseDouble(allMonth.getComplete());
                } catch (NumberFormatException e) {
                    compelete = -1;
                }
            }

            //目标值
            if (StringUtil.isNotEmpty(allMonth.getAnnualTarget())) {
                try {
                    annualTarget = Double.parseDouble(allMonth.getAnnualTarget());
                } catch (NumberFormatException e) {
                    annualTarget = -1;
                }
            }

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

            //进入数据库
            //查询Performancce_monthly数据
            PerformanceMonthly performanceMonthly = new PerformanceMonthly();
            performanceMonthly.setYear(allMonth.getYear());//年
            performanceMonthly.setMonth(allMonth.getMonth());//月
            performanceMonthly.setHierarchyId(allMonth.getHierarchyId());//区域
            performanceMonthly.setElementId(allMonth.getElementId());//指标
            PerformanceMonthly pValue = performanceMonthlyService.getSelect(performanceMonthly);//查询
            if (pValue != null) {
                pValue.setComplete(String.valueOf(compelete));//完成值
                pValue.setAnnualTarget(String.valueOf(annualTarget));//目标值
                pValue.setCompleteRate(String.valueOf(completeRate));//完成率
                pValue.setUpdateDate(new Date());
                //执行更新操作
                performanceMonthlyService.updateByPrimaryKeySelective(pValue);
            } else {
                performanceMonthly.setComplete(String.valueOf(compelete));//完成值
                performanceMonthly.setAnnualTarget(String.valueOf(annualTarget));//目标值
                performanceMonthly.setCompleteRate(String.valueOf(completeRate));//完成率
                performanceMonthly.setCreatedDate(new Date());
                //执行插入操作
                performanceMonthlyService.insertSelective(performanceMonthly);
            }

            //最后将完成率set回去，返回给前台
            allMonth.setCompleteRate(String.valueOf(completeRate));
        }

        performanceMonthlyService.saveMonthAverageAndRank(allMonths.get(0).getElementId(),allMonths.get(0).getYear(),allMonths.get(0).getMonth());

        //查询还有多少个区域是还没有填写的
        List<String> vacancyHierarchyName = performanceRecordService.getMonthlyVacancyAreas(allMonths.get(0).getElementId(),allMonths.get(0).getYear(),allMonths.get(0).getMonth(),"1");
        int vacancy = vacancyHierarchyName.size();//空缺，还有多少个城市公司没填

        //内容返回
        map.put("list", allMonths);
        map.put("vacancy", vacancy);
        map.put("vacancyHierarchyName", vacancyHierarchyName);//无指标区域名称

        return Response.response(map);
    }

    //excel上传接口
    @ResponseBody
    @RequestMapping(value = "/upload", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result upload(@RequestParam(value = "elementId") long elementId,
                         @RequestParam(value = "year") int year, @RequestParam(value = "month") int month,
                         @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.regionMonthlyUpload(multipartFile, elementId, year, month, token.getUserCode());
            performanceMonthlyService.saveMonthAverageAndRank(elementId,year,month);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.responseFail("导入失败");
        }
        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) {
        return Response.response(performancePower.getUserPowerMonthly(requestMap, request));
    }
}
