package com.ruoyi.report.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dimp.domain.DPopulationDataInfo;
import com.ruoyi.dimp.service.IDPopulationDataInfoService;
import com.ruoyi.report.domain.RzlInventStatisticsInfo;
import com.ruoyi.report.mapper.RzlInventStatisticsInfoMapper;
import com.ruoyi.report.service.IRzlInventStatisticsInfoService;
import com.ruoyi.system.domain.BladeRegion;
import com.ruoyi.system.service.IBladeRegionService;
import com.ruoyi.utils.BladeRegionUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 专利有效-万人发明拥有量统计Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-26
 */
@Service
public class RzlInventStatisticsInfoServiceImpl extends ServiceImpl<RzlInventStatisticsInfoMapper, RzlInventStatisticsInfo> implements IRzlInventStatisticsInfoService {

    @Autowired
    private RzlInventStatisticsInfoMapper rzlInventStatisticsInfoMapper;
    @Autowired
    private IDPopulationDataInfoService dPopulationDataInfoService;
    @Autowired
	private IBladeRegionService bladeRegionService;

    @Override
    public List<RzlInventStatisticsInfo> listByReport(RzlInventStatisticsInfo rzlInventStatisticsInfo) {
        List<RzlInventStatisticsInfo> list = new ArrayList<RzlInventStatisticsInfo>();
        List<Map> mapList = rzlInventStatisticsInfoMapper.listByReport(rzlInventStatisticsInfo);
        if (mapList != null && !mapList.isEmpty()) {
            RzlInventStatisticsInfo statist = new RzlInventStatisticsInfo();
          
            String areaName="云南省";
//    		if (rzlInventStatisticsInfo.getCityCode() == null
//    				|| "null".equals(rzlInventStatisticsInfo.getCityCode().trim())
//    				|| "".equals(rzlInventStatisticsInfo.getCityCode().trim())
//    				|| "53".equals(rzlInventStatisticsInfo.getCityCode().trim())) {
//    			areaName="云南省";
//    		} else {
//    			BladeRegion bladeRegion = bladeRegionService
//    					.selectBladeRegionByCode(rzgHighValueIewStatisticsInfo.getCityCode().trim());
//    			if (bladeRegion != null) {
//    				areaName = bladeRegion.getName();
//    			}
//
//    		}
    		  statist.setCityName(areaName);
            statist.setCityCode("53");
            Integer yearValid = 0;
            double population = 0f;
            for (Map map : mapList) {
                RzlInventStatisticsInfo vo = new RzlInventStatisticsInfo();
                vo.setCityName(getStr(map, "modify_city_name"));
                vo.setCityCode(getStr(map, "modify_city_code"));
                vo.setYear(getStr(map, "year_batch"));
                vo.setMonth(getStr(map, "month_batch"));
                
                BladeRegion br = BladeRegionUtils.selectByCode(vo.getCityCode());
    			if (br != null) {
    				vo.setCityName(br.getDistrictShortName());
    			}

                DPopulationDataInfo p = getDPopulationDataInfo(vo.getYear(), vo.getCityCode());
                vo.setYearValid(getInt(map, "total_cnt"));
                yearValid = yearValid + vo.getYearValid();
                if (p != null) {
                    vo.setYearPopulation(p.getPopulationTotal());
                    population = population + Double.parseDouble(p.getPopulationTotal());
                } else {
                    vo.setYearPopulation("0");
                }
                vo.setYearCnt("0");
                if (Double.parseDouble(vo.getYearPopulation()) > 0) {
                    Double yearCntDouble = vo.getYearValid() / Double.parseDouble(vo.getYearPopulation());
                    String yearCnt = String.format("%.4f", yearCntDouble);
                    vo.setYearCnt(yearCnt);
                }
                list.add(vo);
            }
            Collections.sort(list, new Comparator<RzlInventStatisticsInfo>() {

                @Override
                public int compare(RzlInventStatisticsInfo o1, RzlInventStatisticsInfo o2) {
                    // TODO Auto-generated method stub
                    if (o1 == null && o2 == null) {
                        return 0;
                    } else if (o1 == null) {
                        return -1;
                    } else if (o2 == null) {
                        return 1;
                    } else {
                        Double d1 = Double.parseDouble(o1.getYearCnt());
                        Double d2 = Double.parseDouble(o2.getYearCnt());

                        Double d = d2 - d1;
                        if (d > 0) {
                            return 1;
                        } else if (d < 0) {
                            return -1;
                        } else {
                            return 0;
                        }
                    }

                }
            });
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setRanking(i + 1 + "");
            }
            statist.setYearCnt("0");
            statist.setYearValid(yearValid);
            
            
           String popuStr= String.format("%.2f", population);
           statist.setYearPopulation("" + popuStr);
            
            if (population > 0) {
                Double yearCntDouble = yearValid / population;
                String yearCnt = String.format("%.4f", yearCntDouble);
                statist.setYearCnt(yearCnt);
            }
            statist.setRanking("-");
            list.add(statist);
        }
        return list;
//		  select modify_city_name,modify_city_code,year_batch,month_batch,count(*) total_cnt from d_patent_effective_info


    }

    private DPopulationDataInfo getDPopulationDataInfo(String year, String cityCode) {
        DPopulationDataInfo qo = new DPopulationDataInfo();
        qo.setCityCode(cityCode);
        qo.setYear(year);
        List<DPopulationDataInfo> list = dPopulationDataInfoService.queryList(qo);
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    private String getStr(Map map, String key) {
        if (map == null || key == null || !map.containsKey(key)) {
            return "";
        }
        return map.get(key).toString();
    }

    private int getInt(Map map, String key) {
        if (map == null || key == null || !map.containsKey(key)) {
            return 0;
        }
        return Integer.parseInt(map.get(key).toString());
    }


    /**
     * 查询专利有效-万人发明拥有量统计列表
     *
     * @param rzlInventStatisticsInfo 专利有效-万人发明拥有量统计
     * @return 专利有效-万人发明拥有量统计集合
     * @date 2023-03-26
     */
    @Override
    public List<RzlInventStatisticsInfo> queryList(RzlInventStatisticsInfo rzlInventStatisticsInfo) {
        QueryWrapper<RzlInventStatisticsInfo> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(rzlInventStatisticsInfo.getPatentType())) {
            queryWrapper.eq("patent_type", rzlInventStatisticsInfo.getPatentType());
        }
        if (StringUtils.isNotNull(rzlInventStatisticsInfo.getCityCode())) {
            queryWrapper.eq("city_code", rzlInventStatisticsInfo.getCityCode());
        }
        if (StringUtils.isNotEmpty(rzlInventStatisticsInfo.getCityName())) {
            queryWrapper.like("city_name", rzlInventStatisticsInfo.getCityName());
        }
        if (StringUtils.isNotEmpty(rzlInventStatisticsInfo.getYear())) {
            queryWrapper.eq("year", rzlInventStatisticsInfo.getYear());
        }
        if (StringUtils.isNotEmpty(rzlInventStatisticsInfo.getMonth())) {
            queryWrapper.eq("month", rzlInventStatisticsInfo.getMonth());
        }
//                if ( StringUtils.isNotEmpty(rzlInventStatisticsInfo.getHigherSchool())  ){
//                    queryWrapper.eq("higher_school", rzlInventStatisticsInfo.getHigherSchool());
//                }
        if (StringUtils.isNotEmpty(rzlInventStatisticsInfo.getResearchInstitute())) {
            queryWrapper.eq("research_institute", rzlInventStatisticsInfo.getResearchInstitute());
        }
        if (StringUtils.isNotNull(rzlInventStatisticsInfo.getStatus())) {
            queryWrapper.eq("status", rzlInventStatisticsInfo.getStatus());
        }
        queryWrapper.orderByAsc("ranking");
        return this.list(queryWrapper);
    }
}
