package com.ruoyi.reportpub.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.List;

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.NationalRankingUtils;
import com.ruoyi.NationalRankingUtils.Item;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.report.domain.RzlNationalRankingInfo;
import com.ruoyi.reportpub.domain.RzgNationalRankingInfo;
import com.ruoyi.reportpub.service.IRzgNationalRankingInfoExcel;
import com.ruoyi.reportpub.service.IRzgNationalRankingInfoService;

/**
 * 专利公开-全国排名Controller
 *
 * @author ruoyi
 * @date 2023-03-27
 */
@RestController
@RequestMapping("/reportpub/rzgNationalRankingInfo")
public class RzgNationalRankingInfoController extends BaseController {
    private final IRzgNationalRankingInfoService rzgNationalRankingInfoService;
    
    @Autowired
    private  IRzgNationalRankingInfoExcel rzgNationalRankingInfoExcel;


	@Autowired
	private RedisCache redisCache;
	@Autowired
	private RuoYiConfig ruoYiConfig;
	
    public RzgNationalRankingInfoController(IRzgNationalRankingInfoService rzgNationalRankingInfoService) {
        this.rzgNationalRankingInfoService = rzgNationalRankingInfoService;
    }


    /**
     * 查询专利公开-全国排名列表
     *
     * @param rzgNationalRankingInfo 专利公开-全国排名
     * @return 专利公开-全国排名集合
     * @date 2023-03-27
     */
    @PreAuthorize("@ss.hasPermi('reportpub:rzgNationalRankingInfo:list')")
    @GetMapping("/list")
    public AjaxResult list(RzgNationalRankingInfo rzgNationalRankingInfo) {

//    	createTimeBegin=2023-04-07 00:00:00&createTimeEnd=2023-05-17 23:59:59
//      startPage();
//		if (StringUtils.isBlank(rzgNationalRankingInfo.getCreateTime())
//				|| StringUtils.isBlank(rzgNationalRankingInfo.getMonth())) {
//			return AjaxResult.error("请指定数据年月");
//		}
    	
    	
		if (StringUtils.isBlank(rzgNationalRankingInfo.getCreateTimeBegin())
				|| StringUtils.isBlank(rzgNationalRankingInfo.getCreateTimeEnd())) {
			return AjaxResult.error("请指定数据区间");
		}
		String createTimeBegin=rzgNationalRankingInfo.getCreateTimeBegin().trim();
		String createTimeEnd=rzgNationalRankingInfo.getCreateTimeEnd().trim();

		rzgNationalRankingInfo.setCountTimeStr(createTimeBegin+"至"+createTimeEnd);
		createTimeBegin=createTimeBegin.replaceAll("-", "");
		if(createTimeBegin.length()>8) {
			createTimeBegin=createTimeBegin.substring(0, 8);
		}
		
		createTimeEnd=createTimeEnd.replaceAll("-", "");
		if(createTimeEnd.length()>8) {
			createTimeEnd=createTimeEnd.substring(0, 8);
		}
		
		if(createTimeBegin.length()==6) {
			createTimeBegin=createTimeBegin+"01";
		}
		if(createTimeEnd.length()==6) {
			createTimeEnd=DateUtils.getMaxdayInMonth(createTimeEnd);
		}
		
//      List<RzlNationalRankingInfo> list = rzlNationalRankingInfoService.queryList(new RzlNationalRankingInfo());
//      return getDataTable(list);
//		String timeUpdate = rzgNationalRankingInfo.getYear() + rzgNationalRankingInfo.getMonth() + "01";
		String type = "pub";

		List<Item> items = NationalRankingUtils.getRankingList(type, createTimeBegin,createTimeEnd, redisCache,ruoYiConfig,createTimeBegin,createTimeEnd);
		List<RzgNationalRankingInfo> list = new ArrayList<RzgNationalRankingInfo>();
		for(Item item:items) {
			
			RzgNationalRankingInfo info=new RzgNationalRankingInfo();
			info.setRanking(item.ranking);
			info.setArea(item.province);
			info.setInventionPatentsUmber(item.number+"");
			list.add(info);
			
		}
		
//		OutputStream out=null;
//      try {
//			out=new FileOutputStream(new File("D:\\temp\\exp.xlsx"));
////			rzsIpcStatisticsInfoExcel.doExport(out, rzsIpcStatisticsInfo, list);
//			rzgNationalRankingInfoExcel.doExport(out, rzgNationalRankingInfo, list);
//			
//		} 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(list);
	
    
		
    }
    
//    @PreAuthorize("@ss.hasPermi('reportpub:rzgNationalRankingInfo:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(RzgNationalRankingInfo rzgNationalRankingInfo) {
//        startPage();
//        List<RzgNationalRankingInfo> list = rzgNationalRankingInfoService.queryList(rzgNationalRankingInfo);
//        return getDataTable(list);
//    }


    /**
     * 导出专利公开-全国排名列表
     *
     * @param rzgNationalRankingInfo 专利公开-全国排名
     * @date 2023-03-27
     */
    @PreAuthorize("@ss.hasPermi('reportpub:rzgNationalRankingInfo:export')")
    @Log(title = "专利公开-全国排名", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RzgNationalRankingInfo rzgNationalRankingInfo) {
    	
    	
    	


//    	createTimeBegin=2023-04-07 00:00:00&createTimeEnd=2023-05-17 23:59:59
//      startPage();
//		if (StringUtils.isBlank(rzgNationalRankingInfo.getCreateTime())
//				|| StringUtils.isBlank(rzgNationalRankingInfo.getMonth())) {
//			return AjaxResult.error("请指定数据年月");
//		}
    	
    	
		if (StringUtils.isBlank(rzgNationalRankingInfo.getCreateTimeBegin())
				|| StringUtils.isBlank(rzgNationalRankingInfo.getCreateTimeEnd())) {
//			return AjaxResult.error("请指定数据区间");
			throw new RuntimeException("请指定数据区间");
		}
		String createTimeBegin=rzgNationalRankingInfo.getCreateTimeBegin().trim();
		String createTimeEnd=rzgNationalRankingInfo.getCreateTimeEnd().trim();
		

		rzgNationalRankingInfo.setCountTimeStr(createTimeBegin+"至"+createTimeEnd);
		
		createTimeBegin=createTimeBegin.replaceAll("-", "");
		if(createTimeBegin.length()>8) {
			createTimeBegin=createTimeBegin.substring(0, 8);
		}
		
		createTimeEnd=createTimeEnd.replaceAll("-", "");
		if(createTimeEnd.length()>8) {
			createTimeEnd=createTimeEnd.substring(0, 8);
		}
		
		if(createTimeBegin.length()==6) {
			createTimeBegin=createTimeBegin+"01";
		}
		if(createTimeEnd.length()==6) {
			createTimeEnd=createTimeEnd+"31";
		}
		
//      List<RzlNationalRankingInfo> list = rzlNationalRankingInfoService.queryList(new RzlNationalRankingInfo());
//      return getDataTable(list);
//		String timeUpdate = rzgNationalRankingInfo.getYear() + rzgNationalRankingInfo.getMonth() + "01";
		String type = "pub";

		List<Item> items = NationalRankingUtils.getRankingList(type, createTimeBegin,createTimeEnd, redisCache,ruoYiConfig,createTimeBegin,createTimeEnd);
		List<RzgNationalRankingInfo> list = new ArrayList<RzgNationalRankingInfo>();
		for(Item item:items) {
			
			RzgNationalRankingInfo info=new RzgNationalRankingInfo();
			info.setRanking(item.ranking);
			info.setArea(item.province);
			info.setInventionPatentsUmber(item.number+"");
			list.add(info);
			
		}

		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.setCharacterEncoding("utf-8");
		try {
			rzgNationalRankingInfoExcel.doExport(response.getOutputStream(), rzgNationalRankingInfo , list);
		} 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-03-27
     */
    @PreAuthorize("@ss.hasPermi('reportpub:rzgNationalRankingInfo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(rzgNationalRankingInfoService.getById(id));
    }


    /**
     * 新增专利公开-全国排名信息
     *
     * @param rzgNationalRankingInfo 专利公开-全国排名
     * @return 结果
     * @date 2023-03-27
     */
    @PreAuthorize("@ss.hasPermi('reportpub:rzgNationalRankingInfo:add')")
    @Log(title = "专利公开-全国排名", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RzgNationalRankingInfo rzgNationalRankingInfo) {
        return toAjax(rzgNationalRankingInfoService.save(rzgNationalRankingInfo));
    }


    /**
     * 修改专利公开-全国排名信息
     *
     * @param rzgNationalRankingInfo 专利公开-全国排名
     * @return 结果
     * @date 2023-03-27
     */
    @PreAuthorize("@ss.hasPermi('reportpub:rzgNationalRankingInfo:edit')")
    @Log(title = "专利公开-全国排名", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RzgNationalRankingInfo rzgNationalRankingInfo) {
        return toAjax(rzgNationalRankingInfoService.updateById(rzgNationalRankingInfo));
    }


    /**
     * 删除专利公开-全国排名信息
     *
     * @param ids 主键ids
     * @return 结果
     * @date 2023-03-27
     */
    @PreAuthorize("@ss.hasPermi('reportpub:rzgNationalRankingInfo:remove')")
    @Log(title = "专利公开-全国排名", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(rzgNationalRankingInfoService.removeByIds(Arrays.asList(ids)));
    }


}
