package com.unis.base.server.controller;


import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.github.pagehelper.PageInfo;
import com.unis.base.common.vo.CompanyVO;
import com.unis.base.server.entity.TyShougouqiyebeian;
import com.unis.base.server.entity.TyShougouqiyebeianEVo;
import com.unis.base.server.service.CompanyService;
import com.unis.base.server.service.TyShougouqiyebeianService;
import com.unis.common.utils.DateUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.Map.Entry;

/**
 * 收购企业备案
 *
 */
@RestController
@RequestMapping(value="/shouGouQyBa")
@Api(tags = "收购企业备案")
public class TyShougouqiyebeianController {

    @Resource
    private TyShougouqiyebeianService shougouqiyebeianService;
    
    @Autowired
	private CompanyService companyService;

    
    /**
     * 列表
     * @param pageNum  页码
     * @param pageSize 每页显示条数
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/selectPageByEntity",produces = MediaType.APPLICATION_JSON_VALUE, method=RequestMethod.POST)
    @ApiOperation(value="收购企业备案列表", notes = "查询数据列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query")
    })
    public PageInfo<TyShougouqiyebeian> selectPageByEntity(Integer pageNum, Integer pageSize,HttpServletRequest request, @RequestBody TyShougouqiyebeian shougouqiyebeian) throws Exception {

        List<TyShougouqiyebeian> list = shougouqiyebeianService.queryByExample(pageNum, pageSize,shougouqiyebeian);
        PageInfo<TyShougouqiyebeian> pageInfo = new PageInfo<TyShougouqiyebeian>(list);
        return pageInfo;
    }


    
    /** 保存
     * @param 
     * @param  TyShougouqiyebeian 实体对象
     * @return
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    @RequestMapping(value="/save",produces = MediaType.APPLICATION_JSON_VALUE, method=RequestMethod.POST)
    @ApiOperation(value="保存数据", notes = "保存")
    @SuppressWarnings("unchecked")
    @ApiImplicitParams({
            @ApiImplicitParam(name="TyShougouqiyebeian", value="收购企业备案数据对象", paramType="form")
    })
    public Map<String, Object> save(@RequestBody TyShougouqiyebeian tyShougouqiyebeian,HttpServletRequest request) 
    		throws JsonParseException, JsonMappingException, IOException {
                                    
                                    
        Map<String, Object> returnMap = new HashMap<String, Object>();
        int a = 0;
        try {

        	if(tyShougouqiyebeian.getId() == null || tyShougouqiyebeian.getId() == ""){
        		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            	tyShougouqiyebeian.setId(uuid);
            	tyShougouqiyebeian.setCjsj(new Date());
                a = shougouqiyebeianService.save(tyShougouqiyebeian);
                if(a>0){
                	CompanyVO companyVO = new CompanyVO();
                	companyVO.setTyshxydm(tyShougouqiyebeian.getTyshxydm());//统一社会信用代码
                	companyVO.setQymc(tyShougouqiyebeian.getQymc());
                    a = companyService.insert(companyVO);
                }
        	}else{
        		a = shougouqiyebeianService.update(tyShougouqiyebeian);
        	}
        	

            /*Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            String dateStr = simpleDateFormat.format(date);*/
            
            if (a>0) {
            	returnMap.put("status", "success");
            	
            }else{
            	returnMap.put("status", "error");
            	returnMap.put("msg", "保存失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("status", "error");
            returnMap.put("msg", "保存失败！");
            return returnMap;
        }
        return returnMap;
    }


    /**
	 * 删除
	 * @param id 主键
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping(value="/remove", produces = MediaType.APPLICATION_JSON_VALUE, method=RequestMethod.POST)
	@ApiOperation(value="删除", notes = "根据id删除")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "id", paramType = "query")
	})
	public Map<String, Object> remove(String id) throws JsonParseException, JsonMappingException, IOException {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (id != null && id != "") {
			int a = shougouqiyebeianService.remove(id);
			if(a>0){
				modelMap.put("status", "success");
			}else{
				modelMap.put("status", "error");
			}
		}else{
			modelMap.put("msg", "请输入有效id");
		}
		
		return modelMap;
	}

	
	/**
	 * 根据id查找
	 * @param id 主键
	 * @return
	 */
	@RequestMapping(value="/getById", produces = MediaType.APPLICATION_JSON_VALUE, method=RequestMethod.GET)
	@ApiOperation(value="根据id查找", notes = "根据id查找")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "id", paramType = "query")
	})
	public TyShougouqiyebeian getById(String id) {
		
		return shougouqiyebeianService.getById(id);
	}
	
	
	/*@ApiOperation(value = "收购企业备案---根据条件导出数据", notes = "收购企业备案---")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "qymc", value = "企业名称", paramType = "query"),
            @ApiImplicitParam(name = "barq", value = "备案日期", paramType = "query"),
            @ApiImplicitParam(name = "szxzqy", value = "所在行政区域", paramType = "query"),
            @ApiImplicitParam(name = "cjdw", value = "创建单位", paramType = "query"),
            @ApiImplicitParam(name = "sjzt", value = "数据状态", paramType = "query")
    })
    @RequestMapping(value="/exportByEntity",produces = MediaType.APPLICATION_JSON_VALUE, method=RequestMethod.POST)
    public void exportByEntity(HttpServletRequest request, HttpServletResponse response
            , String qymc, String barq, String szxzqy,String cjdw,Integer sjzt) throws Exception {
            
		
        List dataList = JsonUtils.parseList(
                JsonUtils.serialize(list), Map.class);
        //fileName导出文件名
        String fileName= "收购企业备案---导出.xls";
        //sheetName表格名
        String sheetName= "收购企业备案";
        //headMap表头Map, key为属性名, value为展示名,根据实际情况修改
        LinkedHashMap<String, String> headMap= new LinkedHashMap();
        FieldUtil.getPoweredOrderedFields(headMap, new TyShougouqiyebeianEVo(), new BaseEntity());
        
        JxlModelExcelUtil.exportExcel(request, response, fileName, dataList, sheetName, headMap);
    }*/

	// 收购企业备案---根据条件导出数据
    @PostMapping("/exportByEntity")
    public void exportByEntity(
                                         @RequestParam(value = "qymc",required = false) String qymc,
                                         @RequestParam(value = "barq",required = false) String barq,
                                         @RequestParam(value = "szxzqy",required = false) String szxzqy,
                                         @RequestParam(value = "cjdw",required = true) String cjdw,
                                         @RequestParam(value = "sjzt",required = false) Integer sjzt,
                                         HttpServletRequest request,HttpServletResponse response) {
                      
        try {
            // 查询list
        	TyShougouqiyebeian shougouqiyebeian =new TyShougouqiyebeian();
    		if(qymc != null && qymc != ""){
    			shougouqiyebeian.setQymc(qymc);
    		}
    		if(barq != null && barq != ""){
    			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    			Date barqDate = simpleDateFormat.parse(barq);
    			shougouqiyebeian.setBarq(barqDate);
    		}
    		if(szxzqy != null && szxzqy != ""){
    			shougouqiyebeian.setSzxzqy(szxzqy);
    		}
    		if(cjdw != null && cjdw != ""){
    			shougouqiyebeian.setCjdw(cjdw);
    		}
    		if(sjzt != null){
    			shougouqiyebeian.setSjzt(sjzt);
    		}
    		List<Map<String, Object>> data= shougouqiyebeianService.exportByEntityResult(shougouqiyebeian);
            
            LinkedHashMap<String, String> columnName = new LinkedHashMap<>();
          
            columnName.put("dictname","所在行政区域");
            columnName.put("qymc","企业名称");
            columnName.put("tyshxydm","统一社会信用代码");
            columnName.put("xxdz","地址");
            columnName.put("lxr","联系人");
            columnName.put("dh","电话");
            columnName.put("barq","备案日期");
            columnName.put("bajg","备案机关");
            columnName.put("sjztname","状态");
            
            
         // 输出Excel文件
    		
    		response.reset();
    		String fileName = "收购企业备案表";
    		response.setHeader("content-disposition", "attachment;filename="
    				+ new String(DateUtil.getDate()) + ".xls");
    	
    		response.setContentType("application/vnd.ms-excel;charset=gb2312");
    		ServletOutputStream output = response.getOutputStream();
    		pojo3Excel(data, output, columnName,fileName);
    		
    		output.close();
            
        } catch (Exception e) {
            e.printStackTrace();
           
        }
        
        
    }
    
  

    
    public static <T> void pojo3Excel(List<T> pojoList, OutputStream out, LinkedHashMap<String, String> alias,
			String fileName) throws Exception {
		// 创建一个工作簿
		HSSFWorkbook wb = new HSSFWorkbook();

		// 创建一个表
		HSSFSheet sheet = wb.createSheet(fileName);
		HSSFCellStyle contentStyle = createContentCellStyle(wb);
		// 创建第一行，作为表名
		HSSFRow row = sheet.createRow(0);
		row.setHeightInPoints(25);
		
		HSSFCell cell = row.createCell(0);
		cell.setCellValue(fileName);
		
		HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中  
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直对齐
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); 
        cellStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());//背景颜色
        
        HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式  
        headerFont1.setBold(true); //字体加粗 
        headerFont1.setFontName("宋体"); // 设置字体类型  
        headerFont1.setFontHeightInPoints((short) 12); // 设置字体大小  
        cellStyle.setFont(headerFont1); // 为标题样式设置字体样式
        
		
		
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 8));//合并第一行单元格
		
		
		for (int i = 1; i < pojoList.size()+1; i++) {
			HSSFRow tempRow = sheet.createRow(i);
            tempRow.setHeight((short) 350);
            for (int j = 0; j < 9; j++) {
    			sheet.setColumnWidth(j, 4500);
    			HSSFCell tempCell = tempRow.createCell(j);
    	       tempCell.setCellStyle(contentStyle);
    		}
        	
		}
		


        cell.setCellStyle(cellStyle);
        
        
        sheet.setDefaultColumnWidth(256*50);
		// 在第一行插入列名
		insertColumnName(1, sheet, alias);
		// *从第2行开始插入数据
		insertColumnDate(2, pojoList, sheet, alias);
		// 输出表格文件
		try {
			wb.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//wb.close();
			
		}
	}
    
    /**
     * 创建内容样式
     * @param wb
     * @return
     */
    private  static HSSFCellStyle createContentCellStyle(HSSFWorkbook wb) {
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        //cellStyle.setWrapText(true);// 设置自动换行  
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
        cellStyle.setBorderRight(BorderStyle.THIN); //右边框
        cellStyle.setBorderTop(BorderStyle.THIN); //上边框
        
        // 生成12号字体
         HSSFFont font = wb.createFont();
         font.setColor((short)8);
         font.setFontHeightInPoints((short) 9);
        cellStyle.setFont(font);

        return cellStyle;
    }
    
    
    private static void insertColumnName(int rowNum, HSSFSheet sheet, Map<String, String> alias) {
		HSSFRow row = sheet.createRow(rowNum);
		// 列的数量
		int columnCount = 0;

		Set<Entry<String, String>> entrySet = alias.entrySet();

		for (Entry<String, String> entry : entrySet) {
			// 创建第一行的第columnCount个格子
			HSSFCell cell = row.createCell(columnCount++);
			// 将此格子的值设置为alias中的键名
			cell.setCellValue(isNull(entry.getValue()).toString());
		}
	}
    
    
    private static Object isNull(Object object) {
		if (object != null) {
			return object;
		} else {
			return "0";
		}
	}
    
    

	/**
	 * 从指定行开始插入数据
	 * 
	 * @param beginRowNum
	 *            开始行
	 * @param models
	 *            对象数组
	 * @param sheet
	 *            表
	 * @param alias
	 *            列别名
	 * @throws Exception
	 */
	private static <T> void insertColumnDate(int beginRowNum, List<T> models, HSSFSheet sheet,
			Map<String, String> alias) throws Exception {
		for (T model : models) {
			// 创建新的一行
			HSSFRow rowTemp = sheet.createRow(beginRowNum++);

			// 获取列的迭代
			Set<Entry<String, String>> entrySet = alias.entrySet();

			// 从第0个格子开始创建
			int columnNum = 0;
			for (Entry<String, String> entry : entrySet) {
				// 获取属性值
				String property = BeanUtils.getProperty(model, entry.getKey());
				// 创建一个格子
				HSSFCell cell = rowTemp.createCell(columnNum++);
				cell.setCellValue(property);
			}
		}
	}

}