package com.ruoyi.circuit.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
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.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.circuit.domain.CIntegratedCircuit;
import com.ruoyi.circuit.service.ICIntegratedCircuitExcel;
import com.ruoyi.circuit.service.ICIntegratedCircuitService;
import com.ruoyi.circuit.vo.CIntegratedCircuitDTO;
import com.ruoyi.circuit.vo.CIntegratedCircuitVO;
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.common.utils.poi.ExcelUtil;

/**
 * 中国集成电路Controller
 *
 * @author ruoyi
 * @date 2023-04-28
 */
@RestController
@RequestMapping("/circuit/cIntegratedCircuit")
public class CIntegratedCircuitController extends BaseController {
    private final ICIntegratedCircuitService cIntegratedCircuitService;
    @Autowired
    private ICIntegratedCircuitExcel cIntegratedCircuitExcel;
    public CIntegratedCircuitController(ICIntegratedCircuitService cIntegratedCircuitService) {
        this.cIntegratedCircuitService = cIntegratedCircuitService;
    }
    
    
	@PreAuthorize("@ss.hasPermi('circuit:cIntegratedCircuit:list')")
	@GetMapping("/listReport")
	public AjaxResult listReport(CIntegratedCircuit cIntegratedCircuit) {
		if(StringUtils.isBlank(cIntegratedCircuit.getEndDate()) 
				&& StringUtils.isNotBlank(cIntegratedCircuit.getYear()) 
				&& StringUtils.isNotBlank(cIntegratedCircuit.getMonth()) ) {
			cIntegratedCircuit.setEndDate(cIntegratedCircuit.getYear()+cIntegratedCircuit.getMonth());
		}
		if(StringUtils.isBlank(cIntegratedCircuit.getEndDate()) ) {
			cIntegratedCircuit.setEndDate(new SimpleDateFormat("yyyy").format(new Date())+"12");
		}
		
		cIntegratedCircuit.setCountTimeStr("统计时期"+cIntegratedCircuit.getEndDate());
		
		String endDate=cIntegratedCircuit.getEndDate().replace("-", "");
		String month=endDate.substring(4,6);
		int endYear=Integer.parseInt(cIntegratedCircuit.getEndDate().substring(0,4));
		int beginYear=endYear-5;
		String beginDate=beginYear+month+"16";
		endDate=endYear+month+"15";
		
		cIntegratedCircuit.setBeginDate(beginDate);
		cIntegratedCircuit.setEndDate(endDate);
		
		if(StringUtils.isNotBlank(cIntegratedCircuit.getAppliCity()) && !"53".equals(cIntegratedCircuit.getAppliCity().trim())) {
			cIntegratedCircuit.setCityCode(cIntegratedCircuit.getAppliCity().trim());
		}
		
		CIntegratedCircuitDTO dto = cIntegratedCircuitService.listReport(cIntegratedCircuit);
		
		
//		OutputStream out = null;
//		try {
//			out = new FileOutputStream(new File("D:\\temp\\exp.xlsx"));
//			cIntegratedCircuitExcel.exportReport(out, cIntegratedCircuit, dto);
//
//		} 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(dto);
	}
	
	
	@PreAuthorize("@ss.hasPermi('circuit:cIntegratedCircuit:list')")
	@PostMapping("/exportReport")
	public void exportReport(HttpServletResponse response,CIntegratedCircuit cIntegratedCircuit) {
		if(StringUtils.isBlank(cIntegratedCircuit.getEndDate()) 
				&& StringUtils.isNotBlank(cIntegratedCircuit.getYear()) 
				&& StringUtils.isNotBlank(cIntegratedCircuit.getMonth()) ) {
			cIntegratedCircuit.setEndDate(cIntegratedCircuit.getYear()+cIntegratedCircuit.getMonth());
		}
		if(StringUtils.isBlank(cIntegratedCircuit.getEndDate()) ) {
			cIntegratedCircuit.setEndDate(new SimpleDateFormat("yyyy").format(new Date())+"12");
		}
		cIntegratedCircuit.setCountTimeStr("统计时期"+cIntegratedCircuit.getEndDate());
		
		String endDate=cIntegratedCircuit.getEndDate().replace("-", "");
		String month=endDate.substring(4,6);
		int endYear=Integer.parseInt(cIntegratedCircuit.getEndDate().substring(0,4));
		int beginYear=endYear-5;
		String beginDate=beginYear+month+"16";
		endDate=endYear+month+"15";
		
		cIntegratedCircuit.setBeginDate(beginDate);
		cIntegratedCircuit.setEndDate(endDate);
		
		if(StringUtils.isNotBlank(cIntegratedCircuit.getAppliCity()) && !"53".equals(cIntegratedCircuit.getAppliCity().trim())) {
			cIntegratedCircuit.setCityCode(cIntegratedCircuit.getAppliCity().trim());
		}
		
		CIntegratedCircuitDTO dto = cIntegratedCircuitService.listReport(cIntegratedCircuit);
//		return AjaxResult.success(dto);
		

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

		try {

			cIntegratedCircuitExcel.exportReport(response.getOutputStream(), cIntegratedCircuit, dto);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("导出失败," + e.getMessage(), e);
			throw new RuntimeException("导出失败，请联系管理员", e);
		}
	}
	
	@PreAuthorize("@ss.hasPermi('circuit:cIntegratedCircuit:list')")
	@GetMapping("/listRank")
	public AjaxResult listRank(CIntegratedCircuit cIntegratedCircuit) {
		if(StringUtils.isBlank(cIntegratedCircuit.getEndDate()) 
				&& StringUtils.isNotBlank(cIntegratedCircuit.getYear()) 
				&& StringUtils.isNotBlank(cIntegratedCircuit.getMonth()) ) {
			cIntegratedCircuit.setEndDate(cIntegratedCircuit.getYear()+cIntegratedCircuit.getMonth());
		}
		if(StringUtils.isBlank(cIntegratedCircuit.getEndDate()) ) {
			cIntegratedCircuit.setEndDate(new SimpleDateFormat("yyyy").format(new Date())+"12");
		}
		
		String endDate=cIntegratedCircuit.getEndDate().replace("-", "");
		String month=endDate.substring(4,6);
		int endYear=Integer.parseInt(cIntegratedCircuit.getEndDate().substring(0,4));
//		int beginYear=endYear-5;
		int beginYear=endYear-50;//20231030 传一个很久以前的时间
		String beginDate=beginYear+month+"16";
		endDate=endYear+month+"15";
		
		cIntegratedCircuit.setBeginDate(beginDate);
		cIntegratedCircuit.setEndDate(endDate);
		
		List<CIntegratedCircuitVO> dto = cIntegratedCircuitService.listRank(cIntegratedCircuit);
		
//		OutputStream out = null;
//		try {
//			out = new FileOutputStream(new File("D:\\temp\\exp.xlsx"));
//			cIntegratedCircuitExcel.exportRank(out, cIntegratedCircuit, dto);
//
//		} 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(dto);
	}

	@PreAuthorize("@ss.hasPermi('circuit:cIntegratedCircuit:list')")
	@PostMapping("/exportRank")
	public void exportRank(HttpServletResponse response,CIntegratedCircuit cIntegratedCircuit) {
		if(StringUtils.isBlank(cIntegratedCircuit.getEndDate()) 
				&& StringUtils.isNotBlank(cIntegratedCircuit.getYear()) 
				&& StringUtils.isNotBlank(cIntegratedCircuit.getMonth()) ) {
			cIntegratedCircuit.setEndDate(cIntegratedCircuit.getYear()+cIntegratedCircuit.getMonth());
		}
		if(StringUtils.isBlank(cIntegratedCircuit.getEndDate()) ) {
			cIntegratedCircuit.setEndDate(new SimpleDateFormat("yyyy").format(new Date())+"12");
		}
		
		String endDate=cIntegratedCircuit.getEndDate().replace("-", "");
		String month=endDate.substring(4,6);
		int endYear=Integer.parseInt(cIntegratedCircuit.getEndDate().substring(0,4));
		int beginYear=endYear-5;
		String beginDate=beginYear+month+"16";
		endDate=endYear+month+"15";
		
		cIntegratedCircuit.setCountTimeStr("统计时期"+endYear+month);
		
		cIntegratedCircuit.setBeginDate(beginDate);
		cIntegratedCircuit.setEndDate(endDate);
		
		List<CIntegratedCircuitVO> dto = cIntegratedCircuitService.listRank(cIntegratedCircuit);
//		return AjaxResult.success(dto);
		

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

		try {

			cIntegratedCircuitExcel.exportRank(response.getOutputStream(), cIntegratedCircuit, dto);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("导出失败," + e.getMessage(), e);
			throw new RuntimeException("导出失败，请联系管理员", e);
		}
		
		
		
	}
	
    /**
     * 查询中国集成电路列表
     *
     * @param cIntegratedCircuit 中国集成电路
     * @return 中国集成电路集合
     * @date 2023-04-28
     */
    @PreAuthorize("@ss.hasPermi('circuit:cIntegratedCircuit:list')")
    @GetMapping("/list")
    public TableDataInfo list(CIntegratedCircuit cIntegratedCircuit) {
        startPage();
        List<CIntegratedCircuit> list = cIntegratedCircuitService.queryList(cIntegratedCircuit);
        return getDataTable(list);
    }


    /**
     * 导出中国集成电路列表
     *
     * @param cIntegratedCircuit 中国集成电路
     * @date 2023-04-28
     */
    @PreAuthorize("@ss.hasPermi('circuit:cIntegratedCircuit:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, CIntegratedCircuit cIntegratedCircuit) {
        List<CIntegratedCircuit> list = cIntegratedCircuitService.list(new QueryWrapper<>());
        ExcelUtil<CIntegratedCircuit> util = new ExcelUtil<>(CIntegratedCircuit. class);
        util.exportExcel(response, list, "中国集成电路数据");
    }

    /**
     * 获取中国集成电路详细信息
     *
     * @param id 主键id
     * @return 结果
     * @date 2023-04-28
     */
    @PreAuthorize("@ss.hasPermi('circuit:cIntegratedCircuit:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(cIntegratedCircuitService.getById(id));
    }


    /**
     * 新增中国集成电路信息
     *
     * @param cIntegratedCircuit 中国集成电路
     * @return 结果
     * @date 2023-04-28
     */
    @PreAuthorize("@ss.hasPermi('circuit:cIntegratedCircuit:add')")
    @Log(title = "中国集成电路", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CIntegratedCircuit cIntegratedCircuit) {
        return toAjax(cIntegratedCircuitService.save(cIntegratedCircuit));
    }


    /**
     * 修改中国集成电路信息
     *
     * @param cIntegratedCircuit 中国集成电路
     * @return 结果
     * @date 2023-04-28
     */
    @PreAuthorize("@ss.hasPermi('circuit:cIntegratedCircuit:edit')")
    @Log(title = "中国集成电路", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CIntegratedCircuit cIntegratedCircuit) {
        return toAjax(cIntegratedCircuitService.updateById(cIntegratedCircuit));
    }


    /**
     * 删除中国集成电路信息
     *
     * @param ids 主键ids
     * @return 结果
     * @date 2023-04-28
     */
    @PreAuthorize("@ss.hasPermi('circuit:cIntegratedCircuit:remove')")
    @Log(title = "中国集成电路", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(cIntegratedCircuitService.removeByIds(Arrays.asList(ids)));
    }


}
