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.HashSet;
import java.util.List;
import java.util.Set;

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.ApplicantType;
import com.ruoyi.common.constant.HighValue;
import com.ruoyi.common.constant.PatentType;
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.hv.domain.RzgClassifiedStatisticsInfo;
import com.ruoyi.hv.service.IRzgClassifiedStatisticsInfoExcel;
import com.ruoyi.hv.service.IRzgClassifiedStatisticsInfoService;
import com.ruoyi.hv.vo.RzgClassifiedStatisticsInfoVo;
import com.ruoyi.report.domain.HeadColumn;

/**
 * 高价值专利-分类统计Controller
 *
 * @author ruoyi
 * @date 2023-04-02
 */
@RestController
@RequestMapping("/highval/rzgClassifiedStatisticsInfo")
public class RzgClassifiedStatisticsInfoController extends BaseController {
	private final IRzgClassifiedStatisticsInfoService rzgClassifiedStatisticsInfoService;

	@Autowired
	private IRzgClassifiedStatisticsInfoExcel rzgClassifiedStatisticsInfoExcel;

	public RzgClassifiedStatisticsInfoController(
			IRzgClassifiedStatisticsInfoService rzgClassifiedStatisticsInfoService) {
		this.rzgClassifiedStatisticsInfoService = rzgClassifiedStatisticsInfoService;
	}

	@GetMapping("/getHeader")
	public AjaxResult getHeader(String patentTypes, String applicantTypes) {
		if (StringUtils.isBlank(patentTypes)) {
			patentTypes = PatentType.getAllPatentTypeIdStr();
		}
		if (StringUtils.isBlank(applicantTypes)) {
			applicantTypes = ApplicantType.getAllApplicantTypeIdStr();
		}
		List<HeadColumn> columnList = new ArrayList<HeadColumn>();
//		if(getPatentTypeCount(patentTypes)>=1) {
//			HeadColumn column1 = new HeadColumn();
//			column1.setName("专利类型");
//			columnList.add(column1);
//		}
		String[] applicantTypeArr = applicantTypes.split(",");

//		if (applicantTypeArr.length > 1) {
//			HeadColumn column1 = new HeadColumn();
//			column1.setName("合计");
//			columnList.add(column1);
//		}
		for (int i = 0; i < applicantTypeArr.length; i++) {
			ApplicantType at = ApplicantType.valueOf(applicantTypeArr[i]);
			if (at != null) {
				HeadColumn column = new HeadColumn();
				column.setName(at.getTypeName());
				columnList.add(column);
			}
		}

		return AjaxResult.success(columnList);

	}

	private int getPatentTypeCount(String patentTypes) {
		Set<String> ids = new HashSet<String>();
		List<HeadColumn> columnList = new ArrayList<HeadColumn>();
		String[] patentTypeArr = patentTypes.split(",");
		if (patentTypeArr.length > 1) {
			for (int i = 0; i < patentTypeArr.length; i++) {
				PatentType at = PatentType.valueOf(patentTypeArr[i]);
				if (at != null) {
					HeadColumn column = new HeadColumn();
					column.setName(at.getTypeName());
					columnList.add(column);
					ids.add(at.getTypeId());
				}
			}
		}
		return ids.size();
	}

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

	@PreAuthorize("@ss.hasPermi('highval:rzgClassifiedStatisticsInfo:list')")
	@GetMapping("/list")
	public TableDataInfo listByReport(RzgClassifiedStatisticsInfo rzgClassifiedStatisticsInfo) {
//        startPage();

		if (rzgClassifiedStatisticsInfo != null) {
			if (StringUtils.isNotBlank(rzgClassifiedStatisticsInfo.getApplicantTypes())) {
				List<String> patentTypesList = new ArrayList<String>();
				String[] patentTypes = rzgClassifiedStatisticsInfo.getApplicantTypes().split(",");
				for (String pt : patentTypes) {
					if (StringUtils.isNotBlank(pt)) {
						ApplicantType patentType = ApplicantType.valueOf(pt.trim());
						if (patentType != null) {
//							   patentTypesList.add(patentType.getTypeCode());
							patentTypesList.add(patentType.getTypeName());
						}
					}
				}
				rzgClassifiedStatisticsInfo.setApplicantTypesList(patentTypesList);
			}

			if (StringUtils.isNotBlank(rzgClassifiedStatisticsInfo.getHighValueTypes())) {
				List<String> patentTypesList = new ArrayList<String>();
				List<String> patentIdsList = new ArrayList<String>();
				String[] patentTypes = rzgClassifiedStatisticsInfo.getHighValueTypes().split(",");
				for (String pt : patentTypes) {
					if (StringUtils.isNotBlank(pt)) {
						HighValue at = HighValue.valueOf(pt);
						if (at != null) {
							patentIdsList.add(at.getTypeId());
							patentTypesList.add(at.getTypeName());
						}
					}
//						1 ：战略性新兴产业的有效发明专利	
					if ("1".equals(pt)) {
						rzgClassifiedStatisticsInfo.setIndustryEmergIndustryQ("1");
					}
					if ("2".equals(pt)) {
						rzgClassifiedStatisticsInfo.setMaintenanceTenYearQ("1");
					}
//						2 ：维持年限超10年的有效发明专利	
//						3 ：在海外有同族专利权的有效发明专利	
					if ("3".equals(pt)) {
						rzgClassifiedStatisticsInfo.setOverseasCongenerPatentQ("1");
					}
//						4 ：获得较高质押融资金额的有效发明专利	
					if ("4".equals(pt)) {
						rzgClassifiedStatisticsInfo.setPledgeRecordQ("1");
					}
//						5 ：获得国家科技奖或中国专利奖的有效发明专利
					if ("5".equals(pt)) {
						rzgClassifiedStatisticsInfo.setNationalScienceAwardQ("1");
					}

				}
				Collections.sort(patentIdsList, new Comparator<String>() {
					@Override
					public int compare(String o1, String o2) {
						// TODO Auto-generated method stub
						return Integer.parseInt(o1)-Integer.parseInt(o2);
					}
				});
				String hvs="";
				for(int i=0;i<patentIdsList.size();i++) {
					if(i>0) {
						hvs=hvs+",";
					}
					hvs=hvs+patentIdsList.get(i);
				}
				rzgClassifiedStatisticsInfo.setHighValueTypes(hvs);

				rzgClassifiedStatisticsInfo.setHighValueTypesList(patentTypesList);
			}
		}
		List<RzgClassifiedStatisticsInfoVo> list = rzgClassifiedStatisticsInfoService.listByReport(rzgClassifiedStatisticsInfo);

//		OutputStream out = null;
//		try {
//			out = new FileOutputStream(new File("D:\\temp\\exp.xlsx"));
//			rzgClassifiedStatisticsInfoExcel.doExport(out, rzgClassifiedStatisticsInfo, 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 getDataTable(list);
	}

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

//      startPage();

		if (rzgClassifiedStatisticsInfo != null) {
			if (StringUtils.isNotBlank(rzgClassifiedStatisticsInfo.getApplicantTypes())) {
				List<String> patentTypesList = new ArrayList<String>();
				String[] patentTypes = rzgClassifiedStatisticsInfo.getApplicantTypes().split(",");
				for (String pt : patentTypes) {
					if (StringUtils.isNotBlank(pt)) {
						ApplicantType patentType = ApplicantType.valueOf(pt.trim());
						if (patentType != null) {
//							   patentTypesList.add(patentType.getTypeCode());
							patentTypesList.add(patentType.getTypeName());
						}
					}
				}
				rzgClassifiedStatisticsInfo.setApplicantTypesList(patentTypesList);
			}

			if (StringUtils.isNotBlank(rzgClassifiedStatisticsInfo.getHighValueTypes())) {
				List<String> patentTypesList = new ArrayList<String>();
				List<String> patentIdsList = new ArrayList<String>();
				
				String[] patentTypes = rzgClassifiedStatisticsInfo.getHighValueTypes().split(",");
				for (String pt : patentTypes) {
					if (StringUtils.isNotBlank(pt)) {
						HighValue at = HighValue.valueOf(pt);
						if (at != null) {
							patentIdsList.add(at.getTypeId());
							patentTypesList.add(at.getTypeName());
						}
					}
//						1 ：战略性新兴产业的有效发明专利	
					if ("1".equals(pt)) {
						rzgClassifiedStatisticsInfo.setIndustryEmergIndustryQ("1");
					}
					if ("2".equals(pt)) {
						rzgClassifiedStatisticsInfo.setMaintenanceTenYearQ("1");
					}
//						2 ：维持年限超10年的有效发明专利	
//						3 ：在海外有同族专利权的有效发明专利	
					if ("3".equals(pt)) {
						rzgClassifiedStatisticsInfo.setOverseasCongenerPatentQ("1");
					}
//						4 ：获得较高质押融资金额的有效发明专利	
					if ("4".equals(pt)) {
						rzgClassifiedStatisticsInfo.setPledgeRecordQ("1");
					}
//						5 ：获得国家科技奖或中国专利奖的有效发明专利
					if ("5".equals(pt)) {
						rzgClassifiedStatisticsInfo.setNationalScienceAwardQ("1");
					}

				}
				
				Collections.sort(patentIdsList, new Comparator<String>() {
					@Override
					public int compare(String o1, String o2) {
						// TODO Auto-generated method stub
						return Integer.parseInt(o1)-Integer.parseInt(o2);
					}
				});
				String hvs="";
				for(int i=0;i<patentIdsList.size();i++) {
					if(i>0) {
						hvs=hvs+",";
					}
					hvs=hvs+patentIdsList.get(i);
				}
				rzgClassifiedStatisticsInfo.setHighValueTypes(hvs);

				rzgClassifiedStatisticsInfo.setHighValueTypesList(patentTypesList);
			}
		}
		List<RzgClassifiedStatisticsInfoVo> list = rzgClassifiedStatisticsInfoService
				.listByReport(rzgClassifiedStatisticsInfo);

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

		try {

			rzgClassifiedStatisticsInfoExcel.doExport(response.getOutputStream(), rzgClassifiedStatisticsInfo, 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-04-02
	 */
	@PreAuthorize("@ss.hasPermi('highval:rzgClassifiedStatisticsInfo:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		return AjaxResult.success(rzgClassifiedStatisticsInfoService.getById(id));
	}

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

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

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

}
