package com.ruoyi.hv.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.dimp.domain.DPopulationDataInfo;
import com.ruoyi.dimp.service.IDPopulationDataInfoService;
import com.ruoyi.hv.domain.RzgHighValuePatentInfo;
import com.ruoyi.hv.service.IRzgHighValuePatentInfoExcel;
import com.ruoyi.hv.service.IRzgHighValuePatentInfoService;
import com.ruoyi.hv.vo.RzgHighValuePatentInfoVo;

/**
 * 高价值专利-万人高价值专利统计Controller
 *
 * @author ruoyi
 * @date 2023-04-02
 */
@RestController
@RequestMapping("/highval/rzgHighValuePatentInfo")
public class RzgHighValuePatentInfoController extends BaseController {
	private final IRzgHighValuePatentInfoService rzgHighValuePatentInfoService;

	@Autowired
	private IRzgHighValuePatentInfoExcel rzgHighValuePatentInfoExcel;
	
	
	public RzgHighValuePatentInfoController(IRzgHighValuePatentInfoService rzgHighValuePatentInfoService) {
		this.rzgHighValuePatentInfoService = rzgHighValuePatentInfoService;
	}
	
	@Autowired
	private IDPopulationDataInfoService dPopulationDataInfoService;
	/**
	 * 查询高价值专利-万人高价值专利统计列表
	 *
	 * @param rzgHighValuePatentInfo 高价值专利-万人高价值专利统计
	 * @return 高价值专利-万人高价值专利统计集合
	 * @date 2023-04-02
	 */
	@PreAuthorize("@ss.hasPermi('highval:rzgHighValuePatentInfo:list')")
	@GetMapping("/list")
	public TableDataInfo list(RzgHighValuePatentInfo rzgHighValuePatentInfo) {
//		startPage();
		
		String cityCode = null;
		if (StringUtils.isNotBlank(rzgHighValuePatentInfo.getCityCode())
				&& !"53".equals(rzgHighValuePatentInfo.getCityCode())) {
			cityCode = rzgHighValuePatentInfo.getCityCode().trim();
		}
		
		rzgHighValuePatentInfo.setCityCode(cityCode);

		String qyear = rzgHighValuePatentInfo.getYear();
		if (StringUtils.isBlank(qyear)) {
			throw new RuntimeException("请选择数据年份");
		}
		
		if (StringUtils.isBlank(rzgHighValuePatentInfo.getMonth())) {
			rzgHighValuePatentInfo.setMonth("12");
		}
		
		List<RzgHighValuePatentInfo>resList=rzgHighValuePatentInfoService.listByReport(rzgHighValuePatentInfo);
		TableDataInfo td= getDataTable(resList);
		
		

//		OutputStream out = null;
//		try {
//			out = new FileOutputStream(new File("D:\\temp\\exp.xlsx"));
////			rzgClassifiedStatisticsInfoExcel.doExport(out, rzgClassifiedStatisticsInfo, list);
//			rzgHighValuePatentInfoExcel.doExport(out, rzgHighValuePatentInfo, resList);
//
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} finally {
//			try {
//				out.close();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
		
		
		
		return td;
	}
	/**
	 * 查询高价值专利-万人高价值专利统计列表
	 *
	 * @param rzgHighValuePatentInfo 高价值专利-万人高价值专利统计
	 * @return 高价值专利-万人高价值专利统计集合
	 * @date 2023-04-02
	 */
	@PreAuthorize("@ss.hasPermi('highval:rzgHighValuePatentInfo:list')")
	@GetMapping("/list_bak")
	public TableDataInfo list_bak(RzgHighValuePatentInfo rzgHighValuePatentInfo) {
//		startPage();
		
		if(StringUtils.isBlank(rzgHighValuePatentInfo.getCityCode())) {
			rzgHighValuePatentInfo.setCityCode("53");
		}

		RzgHighValuePatentInfo qo = new RzgHighValuePatentInfo();

		
		
		String cityCode = null;
		if (StringUtils.isNotBlank(rzgHighValuePatentInfo.getCityCode())
				&& !"53".equals(rzgHighValuePatentInfo.getCityCode())) {
			cityCode = rzgHighValuePatentInfo.getCityCode().trim();
		}
		

		String qyear = rzgHighValuePatentInfo.getYear();
		if (StringUtils.isBlank(qyear)) {
			throw new RuntimeException("请选择数据年份");
		}
//		qo.setYear(qyear);

		String minYear = (Integer.parseInt(qyear) - 1) + "";
		qo.setMinYear(minYear);
		qo.setMaxYear(qyear);
		qo.setCityCode(cityCode);
		List<RzgHighValuePatentInfo> list = rzgHighValuePatentInfoService.listByReport(qo);

		List<RzgHighValuePatentInfo> resList=new ArrayList<RzgHighValuePatentInfo>();

//    	List<RzgHighValuePatentInfo> list = rzgHighValuePatentInfoService.queryList(qo);
		for (RzgHighValuePatentInfo data : list) {
			setTotal(data);
			data.setGrowth("-");
			data.setYearPopulation(0+"");
			DPopulationDataInfo popu=dPopulationDataInfoService.queryPoupation(data.getYear(), rzgHighValuePatentInfo.getCityCode());
			if(popu!=null && StringUtils.isNotBlank(popu.getPopulationTotal())) {
				data.setYearPopulation(popu.getPopulationTotal());
				Double popuDouble=Double.parseDouble(popu.getPopulationTotal());
				if(data.getEffectiveTotal()  >0 && popuDouble>0) {
					Double hvPatentThousandsDouble=data.getEffectiveTotal()/popuDouble;
					String hvPatentThousands = String.format("%.4f", hvPatentThousandsDouble);
					data.setHvPatentThousands(hvPatentThousands);
				}else {
					data.setHvPatentThousands("0");
				}
				
			}
		}
		Map<String,RzgHighValuePatentInfoVo>areaMap=new HashMap<String,RzgHighValuePatentInfoVo>();
		for(RzgHighValuePatentInfo data : list) {
//			String dataCityCode=data.getCityCode();
			String dataCityCode=data.getAreaName();
			RzgHighValuePatentInfoVo vo=null;
			if(areaMap.containsKey(dataCityCode)) {
				vo=areaMap.get(dataCityCode);
			}else {
				vo=new RzgHighValuePatentInfoVo();
				vo.setAreaName(data.getAreaName());
				vo.setStatisticsYear(qyear);
				vo.setGrowth("-");
				areaMap.put(dataCityCode, vo);
			}
			
			if(qyear.equals(data.getYear())) {
				vo.setCurrData(data);
			}else if(minYear.equals(data.getYear())) {
				vo.setLastData(data);
			}
		}
		
		for(RzgHighValuePatentInfoVo vo:areaMap.values()) {
			if(vo.getCurrData()!=null && vo.getLastData()!=null) {
				//统计增长率
				RzgHighValuePatentInfo currData=vo.getCurrData();
				RzgHighValuePatentInfo lastData=vo.getLastData();
				
				if(StringUtils.isNotBlank(currData.getHvPatentThousands()) && StringUtils.isNotBlank(lastData.getHvPatentThousands())) {
					Double curr=Double.parseDouble(currData.getHvPatentThousands());
					Double last=Double.parseDouble(lastData.getHvPatentThousands());
					if(last>0) {
						Double growThDouble=(curr-last)/last*100;
						String growTh = String.format("%.2f", growThDouble);
						vo.setGrowth(growTh);
						currData.setGrowth(growTh);
					}
				}
				
			}
			if(vo.getCurrData()!=null) {
				resList.add(vo.getCurrData());
			}
		}
		
		Collections.sort(resList,new Comparator<RzgHighValuePatentInfo>() {

			@Override
			public int compare(RzgHighValuePatentInfo o1, RzgHighValuePatentInfo 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 {
						o1.getHvPatentThousands();
						o2.getHvPatentThousands();
						if(StringUtils.isBlank(o1.getHvPatentThousands()) && StringUtils.isBlank(o2.getHvPatentThousands())) {
							return 0;
						}else {
							if(StringUtils.isBlank(o1.getHvPatentThousands()) ) {
								return -1;
							}else if(StringUtils.isBlank(o2.getHvPatentThousands()) ) {
								return 1;
							}else {
								Double hv1=Double.parseDouble(o1.getHvPatentThousands());
								Double hv2=Double.parseDouble(o2.getHvPatentThousands());
								return hv2.compareTo(hv1);
							}
							
						}
						
						
					}
				}
			}
			
		});
		
		
//    	Collections.sort(list,new Comparator<RzgHighValuePatentInfo>() {
//
//			@Override
//			public int compare(RzgHighValuePatentInfo o1, RzgHighValuePatentInfo o2) {
//				// TODO Auto-generated method stub
//				if(o2.getHighValuePatentOwner()==null) {
//					return -1;
//				}
//				return o2.getHighValuePatentOwner().compareTo(o1.getHighValuePatentOwner());
//			}
//    		
//		});
		for (int i = 1; i <= resList.size(); i++) {
			resList.get(i - 1).setRanking(i);
		}
		return getDataTable(resList);
	}
	
	private void setTotal(RzgHighValuePatentInfo data) {
		long total=0;
//		/** 战略性新兴产业 */
//		@Excel(name = "战略性新兴产业")
//		private Integer industryEmergIndustry;
		if(data.getIndustryEmergIndustry()!=null) {
			total=total+data.getIndustryEmergIndustry();
		}else {
			data.setIndustryEmergIndustry(0L);
		}
//
//		/** 在海外有同族专利 */
//		@Excel(name = "在海外有同族专利")
//		private Integer overseasCongenerPatent;
		if(data.getOverseasCongenerPatent()!=null) {
			total=total+data.getOverseasCongenerPatent();
		}else {
			data.setOverseasCongenerPatent(0L);
		}
//
//		/** 维持年限超十年 */
//		@Excel(name = "维持年限超十年")
//		private Integer maintenanceTenYear;
		if(data.getMaintenanceTenYear()!=null) {
			total=total+data.getMaintenanceTenYear();
		}else {
			data.setMaintenanceTenYear(0L);
		}
//
//		/** 存在质押记录 */
//		@Excel(name = "存在质押记录")
//		private Integer pledgeRecord;
		if(data.getPledgeRecord()!=null) {
			total=total+data.getPledgeRecord();
		}else {
			data.setPledgeRecord(0L);
		}
//
//		/** 获得国家科技奖或者中国专利奖 */
//		@Excel(name = "获得国家科技奖或者中国专利奖")
//		private Integer nationalScienceAward;
		if(data.getNationalScienceAward()!=null) {
			total=total+data.getNationalScienceAward();
		}else {
			data.setNationalScienceAward(0L);
		}
		data.setEffectiveTotal(total);
	}

	/**
	 * 导出高价值专利-万人高价值专利统计列表
	 *
	 * @param rzgHighValuePatentInfo 高价值专利-万人高价值专利统计
	 * @date 2023-04-02
	 */
	@PreAuthorize("@ss.hasPermi('highval:rzgHighValuePatentInfo:export')")
	@Log(title = "高价值专利-万人高价值专利统计", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, RzgHighValuePatentInfo rzgHighValuePatentInfo) {
		

//		startPage();
		
		String cityCode = null;
		if (StringUtils.isNotBlank(rzgHighValuePatentInfo.getCityCode())
				&& !"53".equals(rzgHighValuePatentInfo.getCityCode())) {
			cityCode = rzgHighValuePatentInfo.getCityCode().trim();
		}
		
		rzgHighValuePatentInfo.setCityCode(cityCode);

		String qyear = rzgHighValuePatentInfo.getYear();
		if (StringUtils.isBlank(qyear)) {
			throw new RuntimeException("请选择数据年份");
		}
		
		if (StringUtils.isBlank(rzgHighValuePatentInfo.getMonth())) {
			rzgHighValuePatentInfo.setMonth("12");
		}
		
		List<RzgHighValuePatentInfo>resList=rzgHighValuePatentInfoService.listByReport(rzgHighValuePatentInfo);
		TableDataInfo td= getDataTable(resList);
		
		
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.setCharacterEncoding("utf-8");

		try {

			rzgHighValuePatentInfoExcel.doExport(response.getOutputStream(), rzgHighValuePatentInfo, resList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("导出失败," + e.getMessage(), e);
			throw new RuntimeException("导出失败，请联系管理员", e);
		}

		
	}

	/**
	 * 获取高价值专利-万人高价值专利统计详细信息
	 *
	 * @param id 主键id
	 * @return 结果
	 * @date 2023-04-02
	 */
	@PreAuthorize("@ss.hasPermi('highval:rzgHighValuePatentInfo:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		return AjaxResult.success(rzgHighValuePatentInfoService.getById(id));
	}

	/**
	 * 新增高价值专利-万人高价值专利统计信息
	 *
	 * @param rzgHighValuePatentInfo 高价值专利-万人高价值专利统计
	 * @return 结果
	 * @date 2023-04-02
	 */
	@PreAuthorize("@ss.hasPermi('highval:rzgHighValuePatentInfo:add')")
	@Log(title = "高价值专利-万人高价值专利统计", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody RzgHighValuePatentInfo rzgHighValuePatentInfo) {
		return toAjax(rzgHighValuePatentInfoService.save(rzgHighValuePatentInfo));
	}

	/**
	 * 修改高价值专利-万人高价值专利统计信息
	 *
	 * @param rzgHighValuePatentInfo 高价值专利-万人高价值专利统计
	 * @return 结果
	 * @date 2023-04-02
	 */
	@PreAuthorize("@ss.hasPermi('highval:rzgHighValuePatentInfo:edit')")
	@Log(title = "高价值专利-万人高价值专利统计", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody RzgHighValuePatentInfo rzgHighValuePatentInfo) {
		return toAjax(rzgHighValuePatentInfoService.updateById(rzgHighValuePatentInfo));
	}

	/**
	 * 删除高价值专利-万人高价值专利统计信息
	 *
	 * @param ids 主键ids
	 * @return 结果
	 * @date 2023-04-02
	 */
	@PreAuthorize("@ss.hasPermi('highval:rzgHighValuePatentInfo:remove')")
	@Log(title = "高价值专利-万人高价值专利统计", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {
		return toAjax(rzgHighValuePatentInfoService.removeByIds(Arrays.asList(ids)));
	}

}
