package com.ruoyi.reportrzs.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
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.report.vo.IpcStatisticsInfo;
import com.ruoyi.report.vo.IpcStatisticsInfoVo;
import com.ruoyi.reportrzs.domain.RzsIpcStatisticsInfo;
import com.ruoyi.reportrzs.service.IRzsIpcStatisticsInfoExcel;
import com.ruoyi.reportrzs.service.IRzsIpcStatisticsInfoService;

/**
 * 专利授权-主IPC统计Controller
 *
 * @author ruoyi
 * @date 2023-03-27
 */
@RestController
@RequestMapping("/reportrzs/rzsIpcStatisticsInfo")
public class RzsIpcStatisticsInfoController extends BaseController {
	private final IRzsIpcStatisticsInfoService rzsIpcStatisticsInfoService;

	@Autowired
	private IRzsIpcStatisticsInfoExcel rzsIpcStatisticsInfoExcel;

	public RzsIpcStatisticsInfoController(IRzsIpcStatisticsInfoService rzsIpcStatisticsInfoService) {
		this.rzsIpcStatisticsInfoService = rzsIpcStatisticsInfoService;
	}

	/**
	 * 查询专利授权-主IPC统计列表
	 *
	 * @param rzsIpcStatisticsInfo 专利授权-主IPC统计
	 * @return 专利授权-主IPC统计集合
	 * @date 2023-03-27
	 */
	@PreAuthorize("@ss.hasPermi('reportrzs:rzsIpcStatisticsInfo:list')")
	@GetMapping("/list")
	public TableDataInfo list(RzsIpcStatisticsInfo rzsIpcStatisticsInfo) {
//        startPage();
//        List<RzsIpcStatisticsInfo> list = rzsIpcStatisticsInfoService.queryList(rzsIpcStatisticsInfo);

		String createTimeBegin = rzsIpcStatisticsInfo.getCreateTimeBegin();
		String createTimeEnd = rzsIpcStatisticsInfo.getCreateTimeEnd();
		if (StringUtils.isNotBlank(createTimeBegin) && StringUtils.isNotBlank(createTimeEnd)
				&& createTimeBegin.trim().length() >= 6 && createTimeEnd.trim().length() >= 6
//    			&& createTimeBegin.trim().substring(0, 6).equals(createTimeEnd.trim().substring(0, 6))
		) {// 单选一个月
			rzsIpcStatisticsInfo.setCountTimeStr(createTimeBegin+"至"+createTimeEnd);
//    		createTimeBegin=createTimeBegin.trim().substring(0, 6)+"00";
//    		createTimeEnd=createTimeEnd.trim().substring(0, 6)+"00";
			createTimeBegin=createTimeBegin.trim().replace("-", "");
			createTimeEnd=createTimeEnd.trim().replace("-", "");
			rzsIpcStatisticsInfo.setCreateTimeBegin(createTimeBegin.trim().substring(0, 6));
			rzsIpcStatisticsInfo.setCreateTimeEnd(createTimeEnd.trim().substring(0, 6));

		} else {
			rzsIpcStatisticsInfo.setYear(null);
			rzsIpcStatisticsInfo.setMonth(null);
		}

//    	if(StringUtils.isNotBlank(createTimeBegin) && StringUtils.isNotBlank(createTimeEnd)
//    			&& createTimeBegin.trim().length()>=6  && createTimeEnd.trim().length()>=6  
//    			&& createTimeBegin.trim().substring(0, 6).equals(createTimeEnd.trim().substring(0, 6))) {//单选一个月
//    		createTimeBegin=createTimeBegin.trim().substring(0, 6)+"00";
//    		createTimeEnd=createTimeEnd.trim().substring(0, 6)+"00";
//    	}

		rzsIpcStatisticsInfo.setCreateTimeBegin(createTimeBegin);
		rzsIpcStatisticsInfo.setCreateTimeEnd(createTimeEnd);

		List<IpcStatisticsInfoVo> list = rzsIpcStatisticsInfoService.listByReport(rzsIpcStatisticsInfo);

		if (null != list && list.size() > 0) {
			IpcStatisticsInfoVo sum = new IpcStatisticsInfoVo();
			sum.setType("-");
			if ("ipc".equals(rzsIpcStatisticsInfo.getQueryIpc()) && "ipc".equals(rzsIpcStatisticsInfo.getQueryData())) {
				sum.setTypeName("A-H总计");
			} else {
				sum.setTypeName("总计");
			}
			sum.setDatas(new HashMap<String, IpcStatisticsInfo>());

			for (IpcStatisticsInfoVo vo : list) {
				if (vo.getDatas() == null || vo.getDatas().isEmpty()) {
					continue;
				}

				for (Map.Entry<String, IpcStatisticsInfo> ent : vo.getDatas().entrySet()) {
					IpcStatisticsInfo data = ent.getValue();
					String type = ent.getKey();
					if (sum.getDatas().containsKey(type)) {
						IpcStatisticsInfo sumData = sum.getDatas().get(type);
						sumData.setNumber(sumData.getNumber() + data.getNumber());
						sumData.setProportion("100%");
						sumData.setHigherSchool(sumData.getHigherSchool() + data.getHigherSchool());
						sumData.setResearchInstitute(sumData.getResearchInstitute() + data.getResearchInstitute());
						sumData.setEnterprise(sumData.getEnterprise() + data.getEnterprise());
						sumData.setInstitutions(sumData.getInstitutions() + data.getInstitutions());
						sumData.setIndividual(sumData.getIndividual() + data.getIndividual());

					} else {
						IpcStatisticsInfo sumData = new IpcStatisticsInfo();
						sum.getDatas().put(type, sumData);
						sumData.setNumber(data.getNumber());
						sumData.setProportion("100%");
						sumData.setHigherSchool(data.getHigherSchool());
						sumData.setResearchInstitute(data.getResearchInstitute());
						sumData.setEnterprise(data.getEnterprise());
						sumData.setInstitutions(data.getInstitutions());
						sumData.setIndividual(data.getIndividual());

					}

				}
			}

			for (IpcStatisticsInfoVo vo : list) {
				if (vo.getDatas() == null || vo.getDatas().isEmpty()) {
					continue;
				}
				for (Map.Entry<String, IpcStatisticsInfo> ent : vo.getDatas().entrySet()) {
					String type = ent.getKey();
					long total = sum.getDatas().get(type).getNumber();
					if (total > 0) {
						double prop = (ent.getValue().getNumber() * 100 + 0.0) / total;
						ent.getValue().setProportion(String.format("%.2f", prop) + "%");
					} else {
						ent.getValue().setProportion("--");
					}

				}

			}

			list.add(sum);

		}

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

	/**
	 * 导出专利授权-主IPC统计列表
	 *
	 * @param rzsIpcStatisticsInfo 专利授权-主IPC统计
	 * @date 2023-03-27
	 */
	@PreAuthorize("@ss.hasPermi('reportrzs:rzsIpcStatisticsInfo:export')")
	@Log(title = "专利授权-主IPC统计", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, RzsIpcStatisticsInfo rzsIpcStatisticsInfo) {

//      startPage();
//      List<RzsIpcStatisticsInfo> list = rzsIpcStatisticsInfoService.queryList(rzsIpcStatisticsInfo);

		String createTimeBegin = rzsIpcStatisticsInfo.getCreateTimeBegin();
		String createTimeEnd = rzsIpcStatisticsInfo.getCreateTimeEnd();
		if (StringUtils.isNotBlank(createTimeBegin) && StringUtils.isNotBlank(createTimeEnd)
				&& createTimeBegin.trim().length() >= 6 && createTimeEnd.trim().length() >= 6
//  			&& createTimeBegin.trim().substring(0, 6).equals(createTimeEnd.trim().substring(0, 6))
		) {// 单选一个月
			rzsIpcStatisticsInfo.setCountTimeStr(createTimeBegin+"至"+createTimeEnd);
//  		createTimeBegin=createTimeBegin.trim().substring(0, 6)+"00";
//  		createTimeEnd=createTimeEnd.trim().substring(0, 6)+"00";
			createTimeBegin=createTimeBegin.trim().replace("-", "");
			createTimeEnd=createTimeEnd.trim().replace("-", "");
			rzsIpcStatisticsInfo.setCreateTimeBegin(createTimeBegin.trim().substring(0, 6));
			rzsIpcStatisticsInfo.setCreateTimeEnd(createTimeEnd.trim().substring(0, 6));

		} else {
			rzsIpcStatisticsInfo.setYear(null);
			rzsIpcStatisticsInfo.setMonth(null);
		}

//  	if(StringUtils.isNotBlank(createTimeBegin) && StringUtils.isNotBlank(createTimeEnd)
//  			&& createTimeBegin.trim().length()>=6  && createTimeEnd.trim().length()>=6  
//  			&& createTimeBegin.trim().substring(0, 6).equals(createTimeEnd.trim().substring(0, 6))) {//单选一个月
//  		createTimeBegin=createTimeBegin.trim().substring(0, 6)+"00";
//  		createTimeEnd=createTimeEnd.trim().substring(0, 6)+"00";
//  	}

		rzsIpcStatisticsInfo.setCreateTimeBegin(createTimeBegin);
		rzsIpcStatisticsInfo.setCreateTimeEnd(createTimeEnd);

		List<IpcStatisticsInfoVo> list = rzsIpcStatisticsInfoService.listByReport(rzsIpcStatisticsInfo);

		if (null != list && list.size() > 0) {
			IpcStatisticsInfoVo sum = new IpcStatisticsInfoVo();
			sum.setType("-");
			if ("ipc".equals(rzsIpcStatisticsInfo.getQueryIpc()) && "ipc".equals(rzsIpcStatisticsInfo.getQueryData())) {
				sum.setTypeName("A-H总计");
			} else {
				sum.setTypeName("总计");
			}
			sum.setDatas(new HashMap<String, IpcStatisticsInfo>());

			for (IpcStatisticsInfoVo vo : list) {
				if (vo.getDatas() == null || vo.getDatas().isEmpty()) {
					continue;
				}

				for (Map.Entry<String, IpcStatisticsInfo> ent : vo.getDatas().entrySet()) {
					IpcStatisticsInfo data = ent.getValue();
					String type = ent.getKey();
					if (sum.getDatas().containsKey(type)) {
						IpcStatisticsInfo sumData = sum.getDatas().get(type);
						sumData.setNumber(sumData.getNumber() + data.getNumber());
						sumData.setProportion("100%");
						sumData.setHigherSchool(sumData.getHigherSchool() + data.getHigherSchool());
						sumData.setResearchInstitute(sumData.getResearchInstitute() + data.getResearchInstitute());
						sumData.setEnterprise(sumData.getEnterprise() + data.getEnterprise());
						sumData.setInstitutions(sumData.getInstitutions() + data.getInstitutions());
						sumData.setIndividual(sumData.getIndividual() + data.getIndividual());

					} else {
						IpcStatisticsInfo sumData = new IpcStatisticsInfo();
						sum.getDatas().put(type, sumData);
						sumData.setNumber(data.getNumber());
						sumData.setProportion("100%");
						sumData.setHigherSchool(data.getHigherSchool());
						sumData.setResearchInstitute(data.getResearchInstitute());
						sumData.setEnterprise(data.getEnterprise());
						sumData.setInstitutions(data.getInstitutions());
						sumData.setIndividual(data.getIndividual());

					}

				}
			}

			for (IpcStatisticsInfoVo vo : list) {
				if (vo.getDatas() == null || vo.getDatas().isEmpty()) {
					continue;
				}
				for (Map.Entry<String, IpcStatisticsInfo> ent : vo.getDatas().entrySet()) {
					String type = ent.getKey();
					long total = sum.getDatas().get(type).getNumber();
					if (total > 0) {
						double prop = (ent.getValue().getNumber() * 100 + 0.0) / total;
						ent.getValue().setProportion(String.format("%.2f", prop) + "%");
					} else {
						ent.getValue().setProportion("--");
					}

				}

			}

			list.add(sum);

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

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

	}

	/**
	 * 获取专利授权-主IPC统计详细信息
	 *
	 * @param id 主键id
	 * @return 结果
	 * @date 2023-03-27
	 */
	@PreAuthorize("@ss.hasPermi('reportrzs:rzsIpcStatisticsInfo:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		return AjaxResult.success(rzsIpcStatisticsInfoService.getById(id));
	}

	/**
	 * 新增专利授权-主IPC统计信息
	 *
	 * @param rzsIpcStatisticsInfo 专利授权-主IPC统计
	 * @return 结果
	 * @date 2023-03-27
	 */
	@PreAuthorize("@ss.hasPermi('reportrzs:rzsIpcStatisticsInfo:add')")
	@Log(title = "专利授权-主IPC统计", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody RzsIpcStatisticsInfo rzsIpcStatisticsInfo) {
		return toAjax(rzsIpcStatisticsInfoService.save(rzsIpcStatisticsInfo));
	}

	/**
	 * 修改专利授权-主IPC统计信息
	 *
	 * @param rzsIpcStatisticsInfo 专利授权-主IPC统计
	 * @return 结果
	 * @date 2023-03-27
	 */
	@PreAuthorize("@ss.hasPermi('reportrzs:rzsIpcStatisticsInfo:edit')")
	@Log(title = "专利授权-主IPC统计", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody RzsIpcStatisticsInfo rzsIpcStatisticsInfo) {
		return toAjax(rzsIpcStatisticsInfoService.updateById(rzsIpcStatisticsInfo));
	}

	/**
	 * 删除专利授权-主IPC统计信息
	 *
	 * @param ids 主键ids
	 * @return 结果
	 * @date 2023-03-27
	 */
	@PreAuthorize("@ss.hasPermi('reportrzs:rzsIpcStatisticsInfo:remove')")
	@Log(title = "专利授权-主IPC统计", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {
		return toAjax(rzsIpcStatisticsInfoService.removeByIds(Arrays.asList(ids)));
	}

}
