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.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.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("CommunityITTransforController")
@RequestMapping("/CommunityITTransforController")
public class CommunityITTransforController {

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

    @Autowired
    private PerformanceTargetService performanceTargetService;

    @Autowired
    private PerformanceScoreService performanceScoreService;

    @Autowired
    private PerformanceEnvService performanceEnvService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private ExcelAnalysis ea;

    @Autowired
    private  PerformancePower performancePower;

    /*
       基本全部重写
       @author Max Date:2018/06/28
    */
    @ResponseBody
    @RequestMapping(value = "/CommunityITTransfor", method = {RequestMethod.POST, RequestMethod.GET})
    public Object showTarget(@RequestParam(value = "pageCurr") int pageCurr, @RequestParam(value = "pageSize") int pageSize, @RequestParam(value = "years") int years, @RequestParam(value = "quarterly") int quarterly) {
        Map<String, Object> map = new HashMap<>();

        long elementIdSqznh = 1010;//社区智能化改造id
        long elementIdSqlr = 1010001;//税前利润达标id
        long elementIdSzxwc = 1010002;//双执行完成项目数id
        long elementIdSswc = 1010003;//iRBA实施完成项目数id

        List<CommunityITTransfor> communityITTransforList = new ArrayList<>();

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

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

        //查询多少条数据是录入的
        PerformanceScore performanceScore = new PerformanceScore();
        performanceScore.setYear(years);//年
        performanceScore.setQuarterly(thisQuarter);//季度
        performanceScore.setElementId(elementIdSqznh);
        int vacancy = count - performanceScoreService.getTotalPage(performanceScore).getTotalPage();//空缺，还有多少个区域指标没填
        if (vacancy < 0) {
            vacancy = 0;
        }
        List<String> vacancyHierarchyName = performanceEnvService.selectNotInName(performanceScore);

        envList = envList.subList(start < 0 ? 0 : start, end >= count ? count : end);//取开始和结束范围内的值

        if (envList.size() != 0) {
            for (int i = 0; i < envList.size(); i++) {
                CommunityITTransfor communityITTransfor = new CommunityITTransfor();
                communityITTransfor.setHierarchyId(envList.get(i).getHierarchyId());//组织id
                communityITTransfor.setSecond_organization(envList.get(i).getHierarchyName());//二级组织
                communityITTransfor.setThird_organization(envList.get(i).getHierarchyName());//三级组织
                communityITTransfor.setYear(years);//设置年份
                communityITTransfor.setQuarter(thisQuarter);//设置季度

                //------------税前利润达标
                //score表里的相关记录
                PerformanceScore scoresSqlr = new PerformanceScore();
                scoresSqlr.setYear(years);//年
                //scoresSqlr.setQuarterly("6");//季度
                scoresSqlr.setQuarterly(thisQuarter);//季度
                scoresSqlr.setHierarchyId(envList.get(i).getHierarchyId());//区域
                scoresSqlr.setElementId(elementIdSqlr);//税前利润达标id
                PerformanceScore scoreSqlr = performanceScoreService.getscoreByHierarchyId(scoresSqlr);
                if (scoreSqlr != null) {
                    //税前利润达标
                    if (scoreSqlr.getComplete() == 1) {
                        communityITTransfor.setIs_Standard("是");
                        //communityITTransfor.setIs_Standard("1");
                    } else {
                        communityITTransfor.setIs_Standard("否");
                        //communityITTransfor.setIs_Standard("0");
                    }
                }

                //------------双执行
                //target表里的相关记录
                PerformanceTarget tSzxwc = new PerformanceTarget();
                tSzxwc.setYear(years);//年
                //tSzxwc.setQuarterly("6");//季度
                tSzxwc.setQuarterly(thisQuarter);//季度
                tSzxwc.setHierarchyId(envList.get(i).getHierarchyId());//区域
                tSzxwc.setElementId(elementIdSzxwc);//双执行完成项目数id
                PerformanceTarget tValueSzxwc = performanceTargetService.getByHierarchyId(tSzxwc);
                if (tValueSzxwc != null) {
                    communityITTransfor.setComple_Value(tValueSzxwc.getHowlTarget());//双执行完成目标值
                }

                //score表里的相关记录
                PerformanceScore sSzxwc = new PerformanceScore();
                sSzxwc.setYear(years);//年
                //sSzxwc.setQuarterly("6");//季度
                sSzxwc.setQuarterly(thisQuarter);//季度
                sSzxwc.setHierarchyId(envList.get(i).getHierarchyId());//区域
                sSzxwc.setElementId(elementIdSzxwc);//双执行完成项目数id
                PerformanceScore scoreSzxwc = performanceScoreService.getscoreByHierarchyId(sSzxwc);
                if (scoreSzxwc != null) {
                    communityITTransfor.setPriject_Count(scoreSzxwc.getComplete());//双执行完成项目数
                    communityITTransfor.setComple_Rate(scoreSzxwc.getScore());//双执行完成率
                }

                //------------iRBA
                //target表里的相关记录
                PerformanceTarget tSswc = new PerformanceTarget();
                tSswc.setYear(years);//年
                //tSswc.setQuarterly("6");//季度
                tSswc.setQuarterly(thisQuarter);//季度
                tSswc.setHierarchyId(envList.get(i).getHierarchyId());//区域
                tSswc.setElementId(elementIdSswc);//双执行完成项目数id
                PerformanceTarget tValuetSswc = performanceTargetService.getByHierarchyId(tSswc);
                if (tValuetSswc != null) {
                    try {
                        communityITTransfor.setiRBA_Count(Float.valueOf(tValuetSswc.getHowlTarget()));//双执行完成目标值
                    } catch (NumberFormatException e) {
                        communityITTransfor.setiRBA_Count(null);//双执行完成目标值
                    }
                }

                //----------------社区智能改造
                //score表里的相关记录
                PerformanceScore sSqznh = new PerformanceScore();
                sSqznh.setYear(years);//年
                //sSqznh.setQuarterly("6");//季度
                sSqznh.setQuarterly(thisQuarter);//季度
                sSqznh.setHierarchyId(envList.get(i).getHierarchyId());//区域
                sSqznh.setElementId(elementIdSqznh);//社区智能化改造id
                PerformanceScore scoreSqznh = performanceScoreService.getscoreByHierarchyId(sSqznh);
                if (scoreSqznh != null) {
                    communityITTransfor.setPlus_OR_Less(scoreSqznh.getScore());//双执行完成率
                }
                communityITTransforList.add(communityITTransfor);
            }
            map.put("list", communityITTransforList);
            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);
    }

    /*
        全部重写
        @author Max Date:2018/06/28
    */
    //社区智能计算
    @ResponseBody
    @RequestMapping(value = "/CountValue", method = {RequestMethod.POST, RequestMethod.GET})
    public Object TotalCalculate(@RequestBody List<CommunityITTransfor> values) {
        Map<String, Object> map = new HashMap<>();
        long elementIdSqznh = 1010;//社区智能化改造id
        long elementIdSqlr = 1010001;//税前利润达标id
        long elementIdSzxwc = 1010002;//双执行完成项目数id
        long elementIdSswc = 1010003;//iRBA实施完成项目数id

        try {
            for (CommunityITTransfor value : values) {
                //List<PerformanceScore> scores = new ArrayList<>();
                PerformanceScore scoreSqznh = new PerformanceScore();
                PerformanceScore scoreSqlr = new PerformanceScore();
                PerformanceScore scoreSzxwc = new PerformanceScore();
                PerformanceScore scoreSswc = new PerformanceScore();
                //税前利润达标 是或者否,更新数据库分别为1和0
                if (!StringUtil.isBlankOrEmpty(value.getIs_Standard())) {
                    if ("1".equals(value.getIs_Standard())) {
                        scoreSqlr.setComplete(1);
                    } else {
                        scoreSqlr.setComplete(0);
                    }
                    //设置score查询条件，查看是否又记录，有则更新，无则插入
                    scoreSqlr.setYear(value.getYear());
                    scoreSqlr.setQuarterly(value.getQuarter());//设置季度
                    scoreSqlr.setHierarchyId(value.getHierarchyId());
                    scoreSqlr.setElementId(elementIdSqlr);

                    PerformanceScore score = performanceScoreService.getscoreByHierarchyId(scoreSqlr);//查询有没有这条记录
                    //判断是否重复是就更新否就插入
                    if (score == null) {
                        scoreSqlr.setCreatedDate(new Date());//创建日期
                        //插入
                        performanceScoreService.insertScoreSelective(scoreSqlr);
                    } else {
                        performanceScoreService.updateScoreSelective(scoreSqlr);
                    }
                }

                //---------双执行
                //设置score查询条件，查看是否又记录，有则更新，无则插入
                scoreSzxwc.setYear(value.getYear());
                //scoreSzxwc.setQuarterly("6");
                scoreSzxwc.setQuarterly(value.getQuarter());//设置季度
                scoreSzxwc.setHierarchyId(value.getHierarchyId());
                scoreSzxwc.setElementId(elementIdSzxwc);
                //双执行完成项目数
                if (value.getPriject_Count() != null) {
                    scoreSzxwc.setComplete(value.getPriject_Count());
                }
                //双执行完成率
//                if (values.get(i).getComple_Rate() != null) {
//                    scoreSzxwc.setScore(values.get(i).getComple_Rate());
//                }
                //计算双执行完成率
                double szxwcl = -1;
                if (value.getPriject_Count() != null
                        && value.getComple_Value() != null && (!"".equals(value.getComple_Value()))) {
                    try {
                        double prijectC = value.getPriject_Count().doubleValue();
                        double compleV = Double.parseDouble(value.getComple_Value());
                        //计算保留两位小数
                        szxwcl = Arith.div(prijectC, compleV, 2);
                        if (szxwcl > 1) {//如果大于100%，则等于1
                            szxwcl = 1;
                        }
                        value.setComple_Rate((float) szxwcl);//返回给前端
                    } catch (Exception e) {
                        logger.error("=====CommunityITTrasforController.TotalCalculate=====exception for prijectC:"
                                + value.getPriject_Count() + ",compleV:" + value.getComple_Value());
                    }
                }
                //双执行完成率
                if (szxwcl != -1) {
                    scoreSzxwc.setScore((float) szxwcl);
                }
                PerformanceScore scoreSzxwc2 = performanceScoreService.getNewScore(scoreSzxwc);//查询有没有这条记录
                //判断是否重复是就更新否就插入
                if (scoreSzxwc2 == null) {
                    scoreSzxwc.setCreatedDate(new Date());//创建日期
                    performanceScoreService.insertScoreSelective(scoreSzxwc);
                } else {
                    performanceScoreService.UpdateNewScore(scoreSzxwc);
                }

                //双执行完成目标值
                if (value.getComple_Value() != null && (!"".equals(value.getComple_Value()))) {
                    PerformanceTarget targetSzxwc = new PerformanceTarget();
                    targetSzxwc.setYear(value.getYear());
                    //targetSzxwc.setQuarterly("6");
                    targetSzxwc.setQuarterly(value.getQuarter());//设置季度
                    targetSzxwc.setHierarchyId(value.getHierarchyId());
                    targetSzxwc.setElementId(elementIdSzxwc);
                    //得到target表中唯一记录——根据上面四个值
                    PerformanceTarget selectTarget = performanceTargetService.getByHierarchyId(targetSzxwc);
                    if (selectTarget != null) {
                        //更新howlTarget的值
                        selectTarget.setHowlTarget(value.getComple_Value());
                        //执行更新操作
                        performanceTargetService.updateTargetByTargetId(selectTarget);

                    } else {
                        targetSzxwc.setHowlTarget(value.getComple_Value());
                        targetSzxwc.setCreatedDate(new Date());
                        //执行插入操作
                        performanceTargetService.insertTargetSelective(targetSzxwc);
                    }
                }

                //iRBA实施完成项目数
                if (value.getiRBA_Count() != null) {
                    PerformanceTarget targetSswc = new PerformanceTarget();
                    targetSswc.setYear(value.getYear());
                    //targetSswc.setQuarterly("6");
                    targetSswc.setQuarterly(value.getQuarter());//设置季度
                    targetSswc.setHierarchyId(value.getHierarchyId());
                    targetSswc.setElementId(elementIdSswc);
                    //得到target表中唯一记录——根据上面四个值
                    PerformanceTarget tValueSswc = performanceTargetService.getByHierarchyId(targetSswc);
                    if (tValueSswc != null) {
                        //更新howlTarget的值
                        tValueSswc.setHowlTarget(String.valueOf(value.getiRBA_Count()));
                        //执行更新操作
                        performanceTargetService.updateTargetByTargetId(tValueSswc);

                    } else {
                        targetSswc.setHowlTarget(String.valueOf(value.getiRBA_Count()));
                        targetSswc.setCreatedDate(new Date());
                        //执行插入操作
                        performanceTargetService.insertTargetSelective(targetSswc);
                    }
                }

                //计算
                //计算规则：
                /*
                区域智能安防改造加分：
                （a）物业区域智能安保系统改造“双执行”完成率＝100%，区域智能安防改造加分＝3；
                （b）物业区域智能安保系统改造“双执行”完成率＜100%，区域智能安防改造加分＝0；
                区域 iRBA 改造加分＝区域下辖涉及 iRBA 改造项目如期完成项目数×0.5，本项加分不超过 1 分。
                 */
                float temp_plus_or_less = -1;//加减分
                //先判断税前利润达标
                if ("1".equals(value.getIs_Standard())||"是".equals(value.getIs_Standard())) {
                    temp_plus_or_less = 0;//重新初始化为0
                    if (szxwcl >= 1) {
                        temp_plus_or_less += 3;//加三分
                    }
//                    if (!values.get(i).getComple_Value().equals("") && values.get(i).getComple_Value() != null && values.get(i).getPriject_Count() != null) {
//                        if (values.get(i).getPriject_Count() / Float.parseFloat(values.get(i).getComple_Value()) >= 1) {
//                            temp_plus_or_less += 3;//加三分
//                        }
//                    }
                    if (value.getiRBA_Count() != null) {
                        if (value.getiRBA_Count() * 0.5 > 1) {
                            temp_plus_or_less += 1;
                        } else {
                            temp_plus_or_less += (value.getiRBA_Count() * 0.5);
                        }
                    }
                }
                if (temp_plus_or_less != -1) {
                    //修改要返回前端的值
                    value.setPlus_OR_Less(temp_plus_or_less);
                    scoreSqznh.setScore(temp_plus_or_less);//设置score
                } else {
                    //修改要返回前端的值
                    value.setPlus_OR_Less(null);
                    scoreSqznh.setScore(0);//设置score
                }

                //设置score查询条件，查看是否又记录，有则更新，无则插入
                scoreSqznh.setYear(value.getYear());
                //scoreSqznh.setQuarterly("6");
                scoreSqznh.setQuarterly(value.getQuarter());//设置季度
                scoreSqznh.setHierarchyId(value.getHierarchyId());
                scoreSqznh.setElementId(elementIdSqznh);
                PerformanceScore score = performanceScoreService.getNewScore(scoreSqznh);//查询有没有这条记录
                //判断是否重复是就更新否就插入
                if (score == null) {
                    scoreSqznh.setCreatedDate(new Date());//创建日期
                    //插入
                    performanceScoreService.insertScoreSelective(scoreSqznh);
                } else {
                    performanceScoreService.UpdateNewScore(scoreSqznh);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        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(elementIdSqznh);
        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") 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.communityITTransforUpload(multipartFile, year, quarter, "00000");
            ea.communityITTransforUpload(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 = "1010";//社区智能化改造id
        return Response.response(performancePower.getUserPower(elementId,requestMap,request));
    }
}