package com.ruoyi.report.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
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.constant.ApplicantType;
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.report.domain.HeadColumn;
import com.ruoyi.report.domain.RzlApplicantRankingInfo;
import com.ruoyi.report.service.IRzlApplicantRankingInfoExcel;
import com.ruoyi.report.service.IRzlApplicantRankingInfoService;

/**
 * 专利有效-申请人排名Controller
 *
 * @author ruoyi
 * @date 2023-03-26
 */
@RestController
@RequestMapping("/report/rzlApplicantRankingInfo")
public class RzlApplicantRankingInfoController extends BaseController {
	private final IRzlApplicantRankingInfoService rzlApplicantRankingInfoService;

	public RzlApplicantRankingInfoController(IRzlApplicantRankingInfoService rzlApplicantRankingInfoService) {
		this.rzlApplicantRankingInfoService = rzlApplicantRankingInfoService;
	}

	@Autowired
	private IRzlApplicantRankingInfoExcel rzlApplicantRankingInfoExcel;

	@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>();

		HeadColumn column1 = new HeadColumn();
		column1.setName("排名");
		columnList.add(column1);

		HeadColumn column2 = new HeadColumn();
		column2.setName("专利权人名称");
		columnList.add(column2);

		if (getPatentTypeCount(patentTypes) > 1) {
			HeadColumn column3 = new HeadColumn();
			column3.setName("有效专利量总计");
			columnList.add(column3);
		}
		String[] applicantTypeArr = applicantTypes.split(",");
		String[] patentTypeArr = patentTypes.split(",");

//		if (applicantTypeArr.length > 1) {
//			HeadColumn column1 = new HeadColumn();
//			column1.setName("合计");
//			columnList.add(column1);
//		}

		HeadColumn column4 = new HeadColumn();
		column4.setName("申请人类型");
		columnList.add(column4);

		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);
			}
		}

		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 rzlApplicantRankingInfo 专利有效-申请人排名
	 * @return 专利有效-申请人排名集合
	 * @date 2023-03-26
	 */
	@PreAuthorize("@ss.hasPermi('report:rzlApplicantRankingInfo:list')")
	@GetMapping("/list")
	public TableDataInfo list(RzlApplicantRankingInfo rzlApplicantRankingInfo) {

//    	patentTypes
		if (StringUtils.isBlank(rzlApplicantRankingInfo.getPatentTypes())) {
			rzlApplicantRankingInfo.setPatentTypes("1,2,3");
		}

		if (StringUtils.isNotBlank(rzlApplicantRankingInfo.getApplicantTypes())) {
			List<String> patentTypesList = new ArrayList<String>();
			String[] patentTypes = rzlApplicantRankingInfo.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());
					}
				}
			}
			rzlApplicantRankingInfo.setApplicantTypesList(patentTypesList);
		}

		String[] patentTypes = rzlApplicantRankingInfo.getPatentTypes().split(",");
		for (String pt : patentTypes) {
			if (StringUtils.isBlank(pt)) {
				continue;
			}
			PatentType patentType = PatentType.valueOf(pt.trim());
			if (patentType != null) {
				if (PatentType.INVENTION_PATENT.getTypeId().equals(patentType.getTypeId())) {
					rzlApplicantRankingInfo.setInventQ("1");
				}
				if (PatentType.MODEL_UTILITY.getTypeId().equals(patentType.getTypeId())) {
					rzlApplicantRankingInfo.setUtilityModelQ("1");
				}
				if (PatentType.APPEARANCE_PATENT.getTypeId().equals(patentType.getTypeId())) {
					rzlApplicantRankingInfo.setAppearanceDesignQ("1");
				}
			}
		}
		startPage();
		List<RzlApplicantRankingInfo> list = rzlApplicantRankingInfoService.listByReport(rzlApplicantRankingInfo);
		
		
		
//        try {
//			OutputStream out=new FileOutputStream(new File("D:\\temp\\exp.xlsx"));
//			
//			rzlApplicantRankingInfoExcel.doExport(out,rzlApplicantRankingInfo,list);
//			out.close();
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		
		return getDataTable(list);
	}

	/**
	 * 导出专利有效-申请人排名列表
	 *
	 * @param rzlApplicantRankingInfo 专利有效-申请人排名
	 * @date 2023-03-26
	 */
	@PreAuthorize("@ss.hasPermi('report:rzlApplicantRankingInfo:export')")
	// @Log(title = "专利有效-申请人排名", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, RzlApplicantRankingInfo rzlApplicantRankingInfo) {

//    	patentTypes
		if (StringUtils.isBlank(rzlApplicantRankingInfo.getPatentTypes())) {
			rzlApplicantRankingInfo.setPatentTypes("1,2,3");
		}

		if (StringUtils.isNotBlank(rzlApplicantRankingInfo.getApplicantTypes())) {
			List<String> patentTypesList = new ArrayList<String>();
			String[] patentTypes = rzlApplicantRankingInfo.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());
					}
				}
			}
			rzlApplicantRankingInfo.setApplicantTypesList(patentTypesList);
		}

		String[] patentTypes = rzlApplicantRankingInfo.getPatentTypes().split(",");
		for (String pt : patentTypes) {
			if (StringUtils.isBlank(pt)) {
				continue;
			}
			PatentType patentType = PatentType.valueOf(pt.trim());
			if (patentType != null) {
				if (PatentType.INVENTION_PATENT.getTypeId().equals(patentType.getTypeId())) {
					rzlApplicantRankingInfo.setInventQ("1");
				}
				if (PatentType.MODEL_UTILITY.getTypeId().equals(patentType.getTypeId())) {
					rzlApplicantRankingInfo.setUtilityModelQ("1");
				}
				if (PatentType.APPEARANCE_PATENT.getTypeId().equals(patentType.getTypeId())) {
					rzlApplicantRankingInfo.setAppearanceDesignQ("1");
				}
			}
		}
		startPage();
		List<RzlApplicantRankingInfo> list = rzlApplicantRankingInfoService.listByReport(rzlApplicantRankingInfo);
//		return getDataTable(list);

		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.setCharacterEncoding("utf-8");
		try {
			rzlApplicantRankingInfoExcel.doExport(response.getOutputStream(), rzlApplicantRankingInfo, list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("导出失败," + e.getMessage(), e);
			throw new RuntimeException("导出失败，请联系管理员",e);
		}

//		logger.error("导出失败,"+e.getMessage(),e);

	}

	/**
	 * 获取专利有效-申请人排名详细信息
	 *
	 * @param id 主键id
	 * @return 结果
	 * @date 2023-03-26
	 */
	@PreAuthorize("@ss.hasPermi('report:rzlApplicantRankingInfo:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		return AjaxResult.success(rzlApplicantRankingInfoService.getById(id));
	}

	/**
	 * 新增专利有效-申请人排名信息
	 *
	 * @param rzlApplicantRankingInfo 专利有效-申请人排名
	 * @return 结果
	 * @date 2023-03-26
	 */
	@PreAuthorize("@ss.hasPermi('report:rzlApplicantRankingInfo:add')")
	// @Log(title = "专利有效-申请人排名", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody RzlApplicantRankingInfo rzlApplicantRankingInfo) {
		return toAjax(rzlApplicantRankingInfoService.save(rzlApplicantRankingInfo));
	}

	/**
	 * 修改专利有效-申请人排名信息
	 *
	 * @param rzlApplicantRankingInfo 专利有效-申请人排名
	 * @return 结果
	 * @date 2023-03-26
	 */
	@PreAuthorize("@ss.hasPermi('report:rzlApplicantRankingInfo:edit')")
	// @Log(title = "专利有效-申请人排名", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody RzlApplicantRankingInfo rzlApplicantRankingInfo) {
		return toAjax(rzlApplicantRankingInfoService.updateById(rzlApplicantRankingInfo));
	}

	/**
	 * 删除专利有效-申请人排名信息
	 *
	 * @param ids 主键ids
	 * @return 结果
	 * @date 2023-03-26
	 */
	@PreAuthorize("@ss.hasPermi('report:rzlApplicantRankingInfo:remove')")
	// @Log(title = "专利有效-申请人排名", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {
		return toAjax(rzlApplicantRankingInfoService.removeByIds(Arrays.asList(ids)));
	}

}
