package cn.com.countrygarden.bi.main.service.performance.impl.indicators;

import cn.com.countrygarden.bi.main.model.performance.BurglaryIncident;
import cn.com.countrygarden.bi.main.model.performance.PerformanceArea;
import cn.com.countrygarden.bi.main.model.performance.PerformanceScore;
import cn.com.countrygarden.bi.main.model.performance.dto.PerformanceShowDataDto;
import cn.com.countrygarden.bi.main.model.performance.dto.RecordPerformanceDto;
import cn.com.countrygarden.bi.main.service.performance.indicators.AbstractIndicatorService;
import cn.com.countrygarden.bi.main.util.Arith;
import cn.com.countrygarden.bi.main.util.Calculate;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 入室盗窃案案发业务实现类
 *
 * @Author:Wyman
 * @Date:2018/11/3
 */
@Service
public class BurglaryServiceImpl<T> extends AbstractIndicatorService<T> {

    @Override
    public Object showData(long elementId, int year, int quarter, int pageCurr, int pageSize, String typeNo) {

        //展示的dto实体
        PerformanceShowDataDto result = this.setVacancyInfo(elementId,year,quarter,typeNo);

        //使用mybatis PageHelper类进行分页
        PageHelper.startPage(pageCurr,pageSize);
        List<PerformanceArea> organList = this.performanceAreaService.getAllAreasByType(typeNo);//查出来的分页记录数

        if(organList.size() != 0){

            //组装返回的数据
            List<BurglaryIncident> returnList = new ArrayList<>();

            PerformanceScore score;
            long recordId;

            long elementId2 = 1012001;//二级id 入室盗窃案案发数量
            long elementId3 = 1012002;//二级id 入室盗窃案导致人员伤亡案件数
            long elementId4 = 1012003;//二级id 期末接管户数
            long elementId5 = 1012004;//二级id 折算任期户数
            long elementId6 = 1012005;//二级id 入室盗窃案案发率

            for(PerformanceArea p : organList){

                String hierachyId = p.getHierachyId();

                BurglaryIncident burglaryIncident = new BurglaryIncident();
                burglaryIncident.setHierarchyId(hierachyId);
                burglaryIncident.setSecond_organization(p.getHierachyName());
                burglaryIncident.setThird_organization(p.getHierachyName());
                burglaryIncident.setQuarter(String.valueOf(quarter));
                burglaryIncident.setYear(String.valueOf(year));
                burglaryIncident.setHierarchyname(p.getHierachyName());

                //入室盗窃案案发数量
                recordId = performanceRecordService.getRecordId(elementId2,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null)
                    burglaryIncident.setBurglaryIncident_Count(String.valueOf(score.getComplete()));

                //入室盗窃案导致人员伤亡案件数
                recordId = performanceRecordService.getRecordId(elementId3,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null)
                    burglaryIncident.setHurt_OR_Dead(String.valueOf(score.getComplete()));

                //期末接管户数
                recordId = performanceRecordService.getRecordId(elementId4,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null)
                    burglaryIncident.setFinal_Count(String.valueOf(score.getComplete()));

                //折算任期户数
                recordId = performanceRecordService.getRecordId(elementId5,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null)
                    burglaryIncident.setCal_Count(String.valueOf(score.getComplete()));

                //入室盗窃案案发率
                recordId = performanceRecordService.getRecordId(elementId6,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if(score != null){
                    float rate = score.getComplete();
                    DecimalFormat df = new DecimalFormat();
                    String style = "0.00000";//要显示的格式
                    df.applyPattern(style);// 将格式应用于格式化器
                    burglaryIncident.setRate(df.format(rate));
                }

                //插入得分
                recordId = performanceRecordService.getRecordId(elementId,year,quarter,hierachyId);
                score = performanceRecordService.getScore(recordId);
                if (score != null)
                    burglaryIncident.setPlus_OR_Less(String.valueOf(score.getScore()));
                returnList.add(burglaryIncident);
            }
            result.setDataList(returnList);
        }
            return result;
    }

    @Override
    public Object saveData(long elementId, int year, int quarter, List<Object> values) {

        long elementId2 = 1012001;//二级id 入室盗窃案案发数量
        long elementId3 = 1012002;//二级id 入室盗窃案导致人员伤亡案件数
        long elementId4 = 1012003;//二级id 期末接管户数
        long elementId5 = 1012004;//二级id 折算任期户数
        long elementId6 = 1012005;//二级id 入室盗窃案案发率
        //入室盗窃案案发
        double BurglaryIncident_Count;//入室盗窃案案发数量
        double Hurt_OR_Dead; //入室盗窃案导致人员伤亡案件数
        double final_Count;   //期末接管户数
        double rate; //入室盗窃案案发率
        double cal_Count;//折算任期户数
        double plus_OR_Less; // 加减分


        String jsonString = JSONObject.toJSONString(values);

        List<BurglaryIncident> list = JSON.parseObject(jsonString,new TypeReference<List<BurglaryIncident>>(){});

        //遍历集合将对象存入数据库中
        for(int i = 0; i < list.size(); i++){

            BurglaryIncident incident = list.get(i);
            String hierachyId = incident.getHierarchyId();
            BurglaryIncident_Count = Double.valueOf(incident.getBurglaryIncident_Count() == null ? "0.0" : incident.getBurglaryIncident_Count());//入室盗窃案案发数量
            Hurt_OR_Dead = Double.valueOf( incident.getHurt_OR_Dead() == null ? "0.0" : incident.getHurt_OR_Dead());//入室盗窃案导致人员伤亡案件数
            final_Count = Double.valueOf( incident.getFinal_Count() == null ? "0.0" : incident.getFinal_Count());//期末接管户数
            cal_Count = Double.valueOf( incident.getCal_Count() == null ? "0.0" : incident.getCal_Count());//折算任期户数
            plus_OR_Less = Calculate.CalBurglary(BurglaryIncident_Count, Hurt_OR_Dead, cal_Count);//加减法
            rate = new BigDecimal(cal_Count == 0 ? 0 : Arith.div(BurglaryIncident_Count , cal_Count)).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();//计算案发率
            incident.setPlus_OR_Less(String.valueOf(plus_OR_Less));
            //设置案发率返回值
            incident.setRate(String.valueOf(rate));
            ////////////以下进入入库和放重复update操作,入库的内容有 案发数目，伤亡数
            ///////////////////////案发数
            RecordPerformanceDto performanceDto = new RecordPerformanceDto();
            performanceDto.setElementId(elementId2);
            performanceDto.setYear(year);
            performanceDto.setQuarter(quarter);
            performanceDto.setHierachyId(hierachyId);
            performanceDto.setComplete((float) BurglaryIncident_Count);
            performanceRecordService.performanceRecord(performanceDto);
            ///////////////////2.死
            performanceDto.setElementId(elementId3);
            performanceDto.setComplete((float) Hurt_OR_Dead);
            performanceRecordService.performanceRecord(performanceDto);
            ///////////////////3.期末接管户数
            performanceDto.setElementId(elementId4);
            performanceDto.setComplete((float)final_Count);
            performanceRecordService.performanceRecord(performanceDto);
            performanceRecordService.performanceRecord(performanceDto);
            ///////////////////4.折户
            performanceDto.setElementId(elementId5);
            performanceDto.setComplete((float)cal_Count);
            performanceRecordService.performanceRecord(performanceDto);
            ///////////////////5.案发率
            performanceDto.setElementId(elementId6);
            performanceDto.setComplete((float)rate);
            performanceRecordService.performanceRecord(performanceDto);
            /////////////6.分数
            performanceDto.setElementId(elementId);
            performanceDto.setScore((float)plus_OR_Less);
            performanceRecordService.performanceRecord(performanceDto);

        }
        performanceRecordService.saveQuartlyAverageScoreAndSumScore2(year,quarter);

        PerformanceShowDataDto dataDto = new PerformanceShowDataDto();
        dataDto.setDataList(values);
        //空缺值&空缺地区名称
        List<String> vacanHierachyList = performanceRecordService.getVacancyAreas(elementId,year,quarter,"1");
        dataDto.setNameList(vacanHierachyList);
        int vacancy = vacanHierachyList.size();
        dataDto.setVacancy(vacancy);
        return dataDto;
    }

    @Override
    public void uploadData(long elementId, int year, int quarter, MultipartFile mf, String OperatorId) {
        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile)mf;
        String fileName = commonsMultipartFile.getOriginalFilename();
        if(!fileName.contains("入室盗窃")){
            throw new IllegalArgumentException("文件名不正确!");
        }

        //保存数据
        ea.burglaryUpload(mf, year, String.valueOf(quarter), OperatorId);
        //保存平均分和总分
        this.performanceRecordService.saveQuartlyAverageScoreAndSumScore2(year,quarter);
    }

    @Override
    public Object selectAuthority(long elementId, Map<String, Object> requestMap, HttpServletRequest request) {
        return this.performancePower.getUserPower(String.valueOf(elementId),requestMap,request);
    }
}
