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.constant.HighValue;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.dimp.domain.DPopulationDataInfo;
import com.ruoyi.dimp.service.IDPopulationDataInfoService;
import com.ruoyi.hv.domain.RzgHighValueIewStatisticsInfo;
import com.ruoyi.hv.service.IRzgHighValueIewStatisticsInfoExcel;
import com.ruoyi.hv.service.IRzgHighValueIewStatisticsInfoService;
import com.ruoyi.hv.vo.RzgHighValueIewStatisticsInfoRep;

/**
 * 高价值专利-概况统计Controller
 *
 * @author ruoyi
 * @date 2023-04-02
 */
@RestController
@RequestMapping("/highval/rzgHighValueIewStatisticsInfo")
public class RzgHighValueIewStatisticsInfoController extends BaseController {
	private final IRzgHighValueIewStatisticsInfoService rzgHighValueIewStatisticsInfoService;

	@Autowired
	private IRzgHighValueIewStatisticsInfoExcel rzgHighValueIewStatisticsInfoExcel;

	public RzgHighValueIewStatisticsInfoController(
			IRzgHighValueIewStatisticsInfoService rzgHighValueIewStatisticsInfoService) {
		this.rzgHighValueIewStatisticsInfoService = rzgHighValueIewStatisticsInfoService;
	}

	@Autowired
	public IDPopulationDataInfoService dPopulationDataInfoService;

	/**
	 * 查询高价值专利-概况统计列表
	 *
	 * @param rzgHighValueIewStatisticsInfo 高价值专利-概况统计
	 * @return 高价值专利-概况统计集合
	 * @date 2023-04-02
	 */
//    @PreAuthorize("@ss.hasPermi('highval:rzgHighValueIewStatisticsInfo:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(RzgHighValueIewStatisticsInfo rzgHighValueIewStatisticsInfo) {
//        startPage();
//        List<RzgHighValueIewStatisticsInfo> list = rzgHighValueIewStatisticsInfoService.queryList(rzgHighValueIewStatisticsInfo);
//        return getDataTable(list);
//    }

	@GetMapping("/listPopulation")
	public AjaxResult population(RzgHighValueIewStatisticsInfo rzgHighValueIewStatisticsInfo) {
		if (StringUtils.isBlank(rzgHighValueIewStatisticsInfo.getYear())) {
			rzgHighValueIewStatisticsInfo.setYear("2022");
		}

		Map<String, Object> resMap = new HashMap<String, Object>();

		int maxYear = Integer.parseInt(rzgHighValueIewStatisticsInfo.getYear().trim());
		int minYear = maxYear - 1;

		resMap.put("minYear", minYear);
		resMap.put("maxYear", maxYear);

		DPopulationDataInfo dPopulationDataInfo = new DPopulationDataInfo();
		List<DPopulationDataInfo> list = dPopulationDataInfoService.queryList(dPopulationDataInfo);

		// key:cityCode
		Map<String, PopuMode> popuMap = new HashMap<String, PopuMode>();

		for (DPopulationDataInfo pop : list) {
			if ("53".equals(pop.getCityCode())) {
				continue;
			}

			PopuMode popu = null;
			if (popuMap.containsKey(pop.getCityCode())) {
				popu = popuMap.get(pop.getCityCode());
			} else {
				popu = new PopuMode();
				popu.cityCode = pop.getCityCode();
				popu.cityName = pop.getCityName();
				popu.popuMap = new HashMap<String, String>();
				popuMap.put(pop.getCityCode(), popu);
			}

			String year = pop.getYear();
			popu.popuMap.put(year, pop.getPopulationTotal());
		}

		List<PopuMode> resList = new ArrayList<PopuMode>();
		resList.addAll(popuMap.values());
		Collections.sort(resList, new Comparator<PopuMode>() {

			@Override
			public int compare(PopuMode o1, PopuMode o2) {
				String cc1=o1==null?"":(o1.cityCode==null?"":o1.cityCode);
				String cc2=o2==null?"":(o2.cityCode==null?"":o2.cityCode);
				return cc1.compareTo(cc2);
			}
		});

		resMap.put("popuList", resList);

		return AjaxResult.success(resMap);

	}

	public static class PopuMode {
		public String cityCode;
		public String cityName;
		// key:year,val:popu
		public Map<String, String> popuMap;
	}

	@PreAuthorize("@ss.hasPermi('highval:rzgHighValueIewStatisticsInfo:list')")
	@GetMapping("/list")
	public AjaxResult list(RzgHighValueIewStatisticsInfo rzgHighValueIewStatisticsInfo) {
//        startPage();
		if (StringUtils.isNotBlank(rzgHighValueIewStatisticsInfo.getHighValueTypes())) {
			List<String> patentTypesList = new ArrayList<String>();
			String[] patentTypes = rzgHighValueIewStatisticsInfo.getHighValueTypes().split(",");
			for (String pt : patentTypes) {
				if (StringUtils.isNotBlank(pt)) {
					HighValue at = HighValue.valueOf(pt);
					if (at != null) {
						patentTypesList.add(at.getTypeName());
					}
				}

//				   @TableField(exist =false)
//				    private String industryEmergIndustryQ;
//
//				    /**
//				     * 在海外有同族专利
//				     */
//				@TableField(exist =false)
//				    private String overseasCongenerPatentQ;
//
//				    /**
//				     * 维持年限超十年
//				     */
//				@TableField(exist =false)
//				    private String maintenanceTenYearQ;
//
//				    /**
//				     * 存在质押记录
//				     */
//				@TableField(exist =false)
//				    private String pledgeRecordQ;
//
//				    /**
//				     * 获得国家科技奖或者中国专利奖
//				     */
//				@TableField(exist =false)
//				    private String nationalScienceAwardQ;
//				
//					1 ：战略性新兴产业的有效发明专利	
				if ("1".equals(pt)) {
					rzgHighValueIewStatisticsInfo.setIndustryEmergIndustryQ("1");
				}
				if ("2".equals(pt)) {
					rzgHighValueIewStatisticsInfo.setMaintenanceTenYearQ("1");
				}
//					2 ：维持年限超10年的有效发明专利	
//					3 ：在海外有同族专利权的有效发明专利	
				if ("3".equals(pt)) {
					rzgHighValueIewStatisticsInfo.setOverseasCongenerPatentQ("1");
				}
//					4 ：获得较高质押融资金额的有效发明专利	
				if ("4".equals(pt)) {
					rzgHighValueIewStatisticsInfo.setPledgeRecordQ("1");
				}
//					5 ：获得国家科技奖或中国专利奖的有效发明专利
				if ("5".equals(pt)) {
					rzgHighValueIewStatisticsInfo.setNationalScienceAwardQ("1");
				}

			}

			rzgHighValueIewStatisticsInfo.setHighValueTypesList(patentTypesList);
		}
		RzgHighValueIewStatisticsInfoRep rep = rzgHighValueIewStatisticsInfoService.listByReport(rzgHighValueIewStatisticsInfo);

//		OutputStream out = null;
//		try {
//			out = new FileOutputStream(new File("D:\\temp\\exp.xlsx"));
//			rzgHighValueIewStatisticsInfoExcel.doExport(out, rzgHighValueIewStatisticsInfo, rep);
//
//		} 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 AjaxResult.success(rep);
	}

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

//      startPage();
		if (StringUtils.isNotBlank(rzgHighValueIewStatisticsInfo.getHighValueTypes())) {
			List<String> patentTypesList = new ArrayList<String>();
			String[] patentTypes = rzgHighValueIewStatisticsInfo.getHighValueTypes().split(",");
			for (String pt : patentTypes) {
				if (StringUtils.isNotBlank(pt)) {
					HighValue at = HighValue.valueOf(pt);
					if (at != null) {
						patentTypesList.add(at.getTypeName());
					}
				}

//				   @TableField(exist =false)
//				    private String industryEmergIndustryQ;
//
//				    /**
//				     * 在海外有同族专利
//				     */
//				@TableField(exist =false)
//				    private String overseasCongenerPatentQ;
//
//				    /**
//				     * 维持年限超十年
//				     */
//				@TableField(exist =false)
//				    private String maintenanceTenYearQ;
//
//				    /**
//				     * 存在质押记录
//				     */
//				@TableField(exist =false)
//				    private String pledgeRecordQ;
//
//				    /**
//				     * 获得国家科技奖或者中国专利奖
//				     */
//				@TableField(exist =false)
//				    private String nationalScienceAwardQ;
//				
//					1 ：战略性新兴产业的有效发明专利	
				if ("1".equals(pt)) {
					rzgHighValueIewStatisticsInfo.setIndustryEmergIndustryQ("1");
				}
				if ("2".equals(pt)) {
					rzgHighValueIewStatisticsInfo.setMaintenanceTenYearQ("1");
				}
//					2 ：维持年限超10年的有效发明专利	
//					3 ：在海外有同族专利权的有效发明专利	
				if ("3".equals(pt)) {
					rzgHighValueIewStatisticsInfo.setOverseasCongenerPatentQ("1");
				}
//					4 ：获得较高质押融资金额的有效发明专利	
				if ("4".equals(pt)) {
					rzgHighValueIewStatisticsInfo.setPledgeRecordQ("1");
				}
//					5 ：获得国家科技奖或中国专利奖的有效发明专利
				if ("5".equals(pt)) {
					rzgHighValueIewStatisticsInfo.setNationalScienceAwardQ("1");
				}

			}

			rzgHighValueIewStatisticsInfo.setHighValueTypesList(patentTypesList);
		}
		RzgHighValueIewStatisticsInfoRep rep = rzgHighValueIewStatisticsInfoService
				.listByReport(rzgHighValueIewStatisticsInfo);

		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.setCharacterEncoding("utf-8");

		try {

			rzgHighValueIewStatisticsInfoExcel.doExport(response.getOutputStream(), rzgHighValueIewStatisticsInfo, rep);
		} 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:rzgHighValueIewStatisticsInfo:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		return AjaxResult.success(rzgHighValueIewStatisticsInfoService.getById(id));
	}

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

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

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

}
