package com.ssj.sys.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.ssj.bean.common.files.domain.FileInfo;
import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.jxy.domain.Jxy;
import com.ssj.bean.sys.jxy.domain.JxyImg;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.util.ResponseConstant;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.files.service.FileInfoService;
import com.ssj.service.sys.jxy.service.JxyImgService;
import com.ssj.service.sys.jxy.service.JxyService;
import com.ssj.service.weixin.user.service.SubActivityService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
@RequestMapping("sys/jxy")
@Controller
public class JxyController extends BaseController {
	@Autowired
	 private JxyService jxyService;
	@Autowired
	 private JxyImgService jxyImgService;

	@Autowired
	private FileInfoService fileInfoService;

	@Autowired
	private SubActivityService subActivityService;
	/**
	 * 
	* 创建人:zhanglin
	* @param @param model
	* @param @param pageSize
	* @param @param pageNo
	* @param @return
	* @param @throws Exception       
	* 方法说明：查询方法
	 * @date 2017年6月8日 下午3:25:08
	 */
	@RequestMapping("/jxylist")
	 public String jxylist(Model model,
	    		@RequestParam(required = false, defaultValue = "10") int pageSize,
	    		@RequestParam(required = false, defaultValue = "1") int pageNo) throws Exception {
		 Map<String, Object> params = new HashMap<String, Object>();
		 params.put("LIKE_isbn13", request.getParameter("LIKE_isbn13")== null ? "":request.getParameter("LIKE_isbn13"));
		 params.put("LIKE_title", request.getParameter("LIKE_title")== null ? "":request.getParameter("LIKE_title"));
		    SplitPage sp = new SplitPage();
	        sp.setAction(request.getRequestURI().toString());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize);
	        sp.setParams(params);
	        Page<Jxy>  page= jxyService.findByPage(params, initPage(pageNo,pageSize));
		 sp.setRowCnt((int)page.getTotalElements());
		 model.addAttribute("list", page.getContent());
		 model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
        model.addAttribute("page", sp);
        model.addAttribute("search", params);
	     return "sys/jxy/jxylist";
	 }
	/**
	 * 
	* 创建人:zhanglin
	* @param @param model
	* @param @param pageSize
	* @param @param pageNo
	* @param @return
	* @param @throws Exception       
	* 方法说明：查询图书
	 * @date 2017年6月13日 下午5:06:56
	 */
	@RequestMapping("/jxyliblist")
	 public String jxyliblist(Model model,
	    		@RequestParam(required = false, defaultValue = "10") int pageSize,
				@RequestParam(required = false, defaultValue = "1") int pageNo ) throws Exception {
		 Map<String, Object> params = new HashMap<String, Object>();
		 params.put("isbn13", request.getParameter("isbn13")== null ? "":request.getParameter("isbn13"));
		 params.put("title", request.getParameter("title")== null ? "":request.getParameter("title"));
		    SplitPage sp = new SplitPage();
	        sp.setAction(request.getRequestURI().toString());
	        sp.setPageNo(pageNo);
	        sp.setPageSize(pageSize);
	        sp.setParams(params);
	     Page<Map<String, Object>> page= jxyService.getJxylib(params, initPage(pageNo,pageSize));
		 sp.setRowCnt((int)page.getTotalElements());
		 model.addAttribute("list", page.getContent());
		 model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
       model.addAttribute("page", sp);
       model.addAttribute("search", params);
	     return "sys/jxy/jxyliblist";
	 }
	/**
	 * 
	* 创建人:zhanglin
	* @param @param id
	* @param @return       
	* 方法说明：删除方法
	 * @date 2017年6月8日 下午3:25:01
	 */
	@RequestMapping(value = "/jxyDelete", method = RequestMethod.POST)
    @ResponseBody
    public Response jxyDelete(String id){
		Response  response  = new  Response();
    	jxyService.delete(id);
    	response.success();
    	return response;
    }
    /**
     * 
    * 创建人:zhanglin
    * @param @param id
    * @param @return       
    * 方法说明：删除文件
     * @date 2017年6月14日 下午2:09:38
     */
	@RequestMapping(value = "/jxyImgDelete", method = RequestMethod.POST)
	@ResponseBody
	public Response jxyImgDelete( String id){
		Response response = new  Response();
			jxyImgService.delete(id);
			 response.success();
			 return response;
	}
	/**
	 * 
	* 创建人:zhanglin
	* @param @param jxy
	* @param @return       
	* 方法说明：保存方法
	 * @date 2017年6月8日 下午3:30:50
	 */
	 @RequestMapping(value = "/saveJxy", method = RequestMethod.POST)
	    @ResponseBody
	    public ResponseEntity saveJxy(Jxy  jxy)throws Exception{
		 ResponseEntity  response  = new  ResponseEntity();
	    	jxy.setCreateTime(new Date());
	    	jxyService.generateQrcode(jxy);
	    	response.success();
	    	return response;
	    }
	 /**
	  * 
	 * 创建人:zhanglin
	 * @param @param model
	 * @param @param id
	 * @param @return       
	 * 方法说明：添加方法
	  * @date 2017年6月14日 下午2:03:29
	  */
	 @RequestMapping("/addjxy")
	 public String addjxy(Model model,@RequestParam(required = false, defaultValue = "1")String id){
		 Jxy  jxy = jxyService.getById(id);
		 if(jxy ==null ) {
			 jxy =new Jxy();
			 jxy.setId(UUID.randomUUID().toString());
		 }
		 model.addAttribute("jxy",jxy);
		 return "sys/jxy/addjxy";
	 }
	 /**
	  * 
	 * 创建人:zhanglin
	 * @param @param request
	 * @param @param response
	 * @param @param leadyId
	 * @param @return
	 * @param @throws Exception       
	 * 方法说明：上传文件
	  * @date 2017年6月14日 下午2:03:06
	  */
	 @RequestMapping("/uploads")
	    @ResponseBody
	    public ResponseEntity uploadfile(HttpServletRequest request, HttpServletResponse response,String leadyId) throws Exception{
		 ResponseEntity responseEntity = new ResponseEntity();
	    	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
	    	 Map<String, MultipartFile> fileList = multipartRequest.getFileMap();
	        if (fileList !=null && fileList.size() > 0) {
	            //文件信息入库
	            List<FileInfo> fileInfos = fileInfoService.uploadFilePicture(loginName(),fileList);
	            if (fileList.size() == fileInfos.size()) {
	                List<JxyImg> list = new ArrayList<JxyImg>();
	                Integer count =  jxyImgService.countLeadyId(leadyId);
	                for (FileInfo info : fileInfos) {
	                	count++;
	                	JxyImg fileUrl = new JxyImg();
	                	fileUrl.setLeadyId(leadyId);
	                	fileUrl.setFileUrl(info.getFilePath());
	                	fileUrl.setFileName(info.getFileName());
	                	if("mp3".equals(info.getFileExt())){
	                		fileUrl.setFileType("2");
	                	}else{
	                		fileUrl.setFileType("1");
	                	}
	                	fileUrl.setImgIndex(count);
						list.add(fileUrl);
					}
	               jxyImgService.save(list);
	                responseEntity.success("上传文件成功 ");
	            } else {
	                responseEntity.failure(ResponseConstant.CODE_000, "上传文件失败");
	            }

	        } else {
	            responseEntity.failure(ResponseConstant.CODE_000, "上传文件失败");
	        }

	        return responseEntity;
	    }		
	
	 
	 
	 
	 
	    @RequestMapping(value = "/updateImgIndex", method = RequestMethod.POST)
		 @ResponseBody
		 public Response updateImgIndex( String id,Integer price){
			 Response response = new  Response();
			 jxyImgService.updateImgIndex(id, price);
			 response.success();
			 return response;
		 }

	@RequestMapping("/extensionList")
	public String extensionList(@RequestParam(required = false, defaultValue = "10") int pageSize,
								@RequestParam(required = false, defaultValue = "1") int pageNo,Model model){
		String area = request.getParameter("area")==null?"":request.getParameter("area");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("area",area);
		SplitPage sp = new SplitPage();
		sp.setAction(request.getRequestURI().toString());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<Map<String,Object>> page = subActivityService.findByTypePages(params,initPage(pageNo,pageSize));
		sp.setRowCnt((int) page.getTotalElements());
		model.addAttribute("list", page.getContent());
		model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
		model.addAttribute("page", sp);
		model.addAttribute("search", params);
		return  "sys/jxy/extensionList";
	}

	@RequestMapping(value = "/exportData", method = RequestMethod.POST)
	@ResponseBody
	public void exportData(Model model, HttpServletRequest request, HttpServletResponse response) {
		String sysVersion=model.asMap().getOrDefault("sys_version_val","1").toString();

		ServletOutputStream os = null;
		try {
			String libName="推广信息";
			os = response.getOutputStream(); //获得输出流
			response.reset();   //清空输出流
			String fileName = new String(libName.getBytes("gb2312"), "ISO8859-1") +".xlsx";
			response.setHeader("Content-disposition", "attachment; filename="+ fileName); //设定输出文件头
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			response.setCharacterEncoding("utf-8");
			Map<String, Object> params = new HashMap<String, Object>();
			String area = request.getParameter("area")==null?"":request.getParameter("area");

			Page<Map<String, Object>> page = subActivityService.findByTypePages(params, initPage(1, 1));
			int total = (int)page.getTotalElements();
			if(total>0){
				page = subActivityService.findByTypePages(params, initPage(1, total));
			}
			List<Map<String, Object>> list = page.getContent();
			List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>(){{
				add(new ExcelExportEntity("微信昵称", "wx_name"));
				add(new ExcelExportEntity("来源", "parent_id"));
				add(new ExcelExportEntity("创建时间", "create_time"));
			}};

			//把我们构造好的bean对象放到params就可以了
			List<Map<String, Object>> list2 = new ArrayList<>();
			list2.addAll(list);
			Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(libName, libName, ExcelType.XSSF), entity,
					list2);
			workbook.write(os);
		}catch (IOException e) {
			logger.info("下载出现异常--->"+e);
		}catch (Exception e1){
			logger.info("下载出现异常--->"+e1);
		}finally{
			if(os != null){
				try {
					os.flush();
					os.close();
				} catch (IOException e) {
					logger.info("下载出现异常--->"+e);
				}
			}
		}
	}
}
