package com.ssj.sys.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.*;

import com.ssj.bean.sys.poster.domain.PosterActivityJoin;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.util.BarcodeFactory;
import com.ssj.service.sys.poster.service.PosterActivityJoinService;
import com.ssj.util.ZipCompressor;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
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 com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.imlibuser.TbClassTeacherTemp;
import com.ssj.bean.sys.poster.domain.PosterActivity;
import com.ssj.bean.sys.poster.domain.PosterJoin;
import com.ssj.bean.sys.poster.domain.PosterTemplate;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.service.sys.poster.service.PosterActivityService;
import com.ssj.service.sys.poster.service.PosterJoinService;
import com.ssj.service.sys.poster.service.PosterTemplateService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author admin
 * @date xxx
 * 海报管理
 */
@Controller
@RequestMapping("/sys/poster")
public class PosterController extends BaseController {

    @Autowired
    private PosterActivityService posterActivityService;
    
    @Autowired
    private PosterJoinService posterJoinService;
    
    @Autowired
    private PosterTemplateService posterTemplateService;

    @Autowired
    private PosterActivityJoinService activityJoinService;


	/**
	 * 查询活动列表
	 * @param model
	 * @param pageSize
	 * @param pageNo
	 * @return
	 * @throws Exception
	 */
    @RequestMapping("/activity/list")
    public String activityList(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {
		
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page = posterActivityService.findActivityByPage(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/poster/activity_list";
    }
    /**
	 * 查询活动列表
	 * @param model
	 * @param pageSize
	 * @param pageNo
	 * @return
	 * @throws Exception
	 */
    @RequestMapping("/template/list")
    public String templateList(Model model,
            @RequestParam(required = false, defaultValue = "100") int pageSize,
            @RequestParam(required = false, defaultValue = "1") int pageNo)throws Exception {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("LIKE_templateName", request.getParameter("LIKE_templateName")==null?"":request.getParameter("LIKE_templateName"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<PosterTemplate> page = posterTemplateService.findBypage(params, initPage(pageNo,pageSize, Sort.Direction.DESC, new String[] { "createTime" }));
        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/poster/template_list";
    }

	/**
	 * 下载海报
	 * @param response
	 */
	@RequestMapping(value = "/exportDetail", method = RequestMethod.POST)
	@ResponseBody
	public void exportDetail(HttpServletResponse response) {
		try {
			String file_path = (String) SystemResourceLocator.getValue("file_save_path");
			String dataStr = DateHelper.formatDateByFormat(new Date(), "yyyyMMddHHmmss");
			String zip = "/poster/"+dataStr+".zip";
			//先压缩文件
			ZipCompressor zc = new ZipCompressor(file_path+zip);
			//根据条件查询需要下载的文件
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
			List<Map<String,Object>> list = posterActivityService.exportActivityList(params);
			String[] compressorFiles = new String[list.size()];
			int i = 0;
			if(Objects.nonNull(list)){
				for(Map<String,Object> m:list){
					compressorFiles[i]= file_path+"/poster/"+MapUtils.getString(m,"name");
					i++;
				}
			}
			zc.compress(compressorFiles);
			exportResponseHeadSet(response,dataStr);
			exportFile(response,file_path+zip);
		} catch (Exception e) {
			logger.error("异常", e);
		}
	}

	public void exportResponseHeadSet(HttpServletResponse response,String fileName) throws  Exception{
		response.setContentType("application/octet-stream;charset=UTF-8");
		fileName=new String((fileName).getBytes("gb2312"), "iso8859-1");
		response.setHeader("Content-Disposition", "attachment;filename="+fileName+".zip");
		response.setCharacterEncoding("utf-8");
	}

	public void exportFile(HttpServletResponse response,String fileNameUrl) throws Exception{
		//压缩完成后，下载文件
		File file = new File(fileNameUrl);
		FileInputStream fis = new FileInputStream(file);
		BufferedInputStream buff = new BufferedInputStream(fis);
		// 相当于我们的缓存
		byte[] b = new byte[4096];
		// 该值用于计算当前实际下载了多少字节
		long k = 0;
		// 从response对象中得到输出流,准备下载
		OutputStream myout = response.getOutputStream();
		// 开始循环下载
		while (k < file.length()) {
			int j = buff.read(b, 0, 1024);
			k += j;
			myout.write(b, 0, j);
		}
		buff.close();
		fis.close();
	}
	/**
	 * 编辑活动页面
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/activity/edit")
    public String activityEdit(Model model,String id)throws Exception {
    	PosterActivity posterActivity=new PosterActivity();
    	if(StringUtils.isNotEmpty(id)) {
    		posterActivity=posterActivityService.getById(id);
    	}
        List<PosterTemplate> templates=posterTemplateService.findPosterTemplateByList();
        model.addAttribute("posterActivity",posterActivity);
        model.addAttribute("templates",templates);
        return "sys/poster/activity_edit";
    }


	/**
	 * 保存活动信息
	 * @param model
	 * @param id
	 * @param templateId
	 * @param name
	 * @return
	 * @throws Exception
	 */
    @RequestMapping("/activity/save")
	@ResponseBody
    public Response activitySave(Model model,String id,String templateId,String name)throws Exception {
		Response response = new  Response();
		if(StringUtils.isEmpty(id)){
			PosterActivity posterActivity=new PosterActivity();
			posterActivity.setName(name);
			posterActivity.setTemplateId(templateId);
			posterActivity.setStatus(1);
			posterActivity.setCreateTime(new Date());
			posterActivityService.save(posterActivity);
		}else{
			PosterActivity posterActivity=posterActivityService.getById(id);
			if(posterActivity!=null) {
				posterActivity.setName(name);
				posterActivityService.save(posterActivity);
			}
		}
		response.success("成功");
        return response;
    }

	/**
	 * 编辑机构页面
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/template/edit")
	public String templateEdit(Model model,String id)throws Exception {
		PosterTemplate template=new PosterTemplate();
		if(StringUtils.isNotEmpty(id)) {
			template=posterTemplateService.getById(id);
		}
		model.addAttribute("template",template);
		return "sys/poster/template_edit";
	}

	@RequestMapping("/template/save")
	@ResponseBody
	public Response templateSave(Model model,PosterTemplate template)throws Exception {
		Response response = new  Response();
		posterTemplateService.save(template);
		response.success("成功");
		return response;
	}

	/**
	 * 删除模板信息
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/template/del")
	@ResponseBody
	public Response templateyDel(Model model,String id)throws Exception {
		Response response = new  Response();
		if(StringUtils.isNotEmpty(id)){
			posterTemplateService.delete(id);
		}
		response.success("成功");
		return response;
	}


	/**
	 * 删除活动信息
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/activity/del")
	@ResponseBody
    public Response activityDel(Model model,String id)throws Exception {
		Response response = new  Response();
		if(StringUtils.isNotEmpty(id)){
			PosterActivity posterActivity=posterActivityService.getById(id);
			if(posterActivity!=null) {
				posterActivity.setStatus(0);
				posterActivityService.save(posterActivity);
			}
		}
		response.success("成功");
        return response;
    }


	/**
	 * 查询机构列表
	 * @param model
	 * @param pageSize
	 * @param pageNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/join/list")
    public String joinList(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("name", request.getParameter("name")==null?"":request.getParameter("name"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page = posterJoinService.findJoinByPage(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/poster/join_list";
    }
    /**
	 * 查询机构列表
	 * @param model
	 * @param pageSize
	 * @param pageNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/activityJoin/list")
    public String activityJoinList(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("name", request.getParameter("name")==null?"":request.getParameter("name"));
        params.put("id", request.getParameter("id")==null?"":request.getParameter("id"));
        SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
        Page<Map<String, Object>> page = activityJoinService.findActivityJoinByPage(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/poster/activity_join_list";
    }


	/**
	 * 编辑机构页面
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/join/edit")
    public String joinEdit(Model model,String id)throws Exception {
    	PosterJoin posterJoin=new PosterJoin();
    	if(StringUtils.isNotEmpty(id)) {
    		posterJoin=posterJoinService.getById(id);
    	}
        model.addAttribute("posterJoin",posterJoin);
        return "sys/poster/join_edit";
    }
    /**
	 * 编辑活动页面
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/activityJoin/edit")
    public String activityJoinEdit(Model model,@RequestParam(required = false, defaultValue = "0") String id)throws Exception {

		PosterActivityJoin join = activityJoinService.getById(id);
		PosterJoin posterJoin=new PosterJoin();
		PosterActivity activity = new PosterActivity();
		List<PosterTemplate> list  = new ArrayList<>();
		if(Objects.nonNull(join)){
			posterJoin = posterJoinService.getById(join.getJoinId());
			activity = posterActivityService.getById(join.getActivityId());
			List<String> ids = Arrays.asList(activity.getTemplateId().split(","));
			list = posterTemplateService.findPosterTemplateByIds(ids);
		}
        model.addAttribute("posterJoin",posterJoin);
        model.addAttribute("templates",list);
        model.addAttribute("activity",activity);
        model.addAttribute("join",join);
        return "sys/poster/activity_join_edit";
    }
    /**
	 * 活动页面新增
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/activityJoin/add")
    public String activityJoinAdd(Model model,@RequestParam(required = false, defaultValue = "0") String id)throws Exception {

		List<PosterJoin> posterJoin= posterJoinService.findAll();
		PosterActivity activity =  posterActivityService.getById(id);
		List<String> ids = Arrays.asList(activity.getTemplateId().split(","));
		List<PosterTemplate> list  =  posterTemplateService.findPosterTemplateByIds(ids);
        model.addAttribute("posterJoins",posterJoin);
        model.addAttribute("templates",list);
        model.addAttribute("activity",activity);
        return "sys/poster/activity_join_add";
    }


	/**
	 * 保存机构信息，并生成海报
	 * @param model
	 * @param id
	 * @param name
	 * @param phone
	 * @param address
	 * @param logoImg
	 * @param qrcodeImg1
	 * @param qrcodeImg2
	 * @param posterImg
	 * @return
	 * @throws Exception
	 */
    @RequestMapping("/join/save")
	@ResponseBody
    public Response joinSave(Model model,String id,String name,String phone,String address,String logoImg,String qrcodeImg1,String qrcodeImg2,String posterImg)throws Exception {
		Response response = new  Response();
		PosterJoin posterJoin=new PosterJoin();
		if(StringUtils.isEmpty(id)){
			posterJoin.setCreateTime(new Date());
			posterJoin.setStatus(1);
		}else{
			posterJoin=posterJoinService.getById(id);
			if(posterJoin==null) {
				posterJoin = new PosterJoin();
				//posterJoinService.generatePosterImg(posterJoin);
			}
		}
		posterJoin.setLogoImg(logoImg);
		posterJoin.setName(name);
		posterJoin.setPhone(phone);
		posterJoin.setPosterImg(posterImg);
		posterJoin.setQrcodeImg1(qrcodeImg1);
		posterJoin.setQrcodeImg2(qrcodeImg2);
		posterJoin.setAddress(address);
		posterJoinService.save(posterJoin);
		response.success("成功");
        return response;
    }
    @RequestMapping("/activityJoin/save")
	@ResponseBody
    public Response activityJoinSave(Model model,String ids,String aid,String templateId)throws Exception {
		Response response = new  Response();
		List<String> list = Arrays.asList(ids.split(","));
		for(String str:list){
			posterJoinService.generatePosterImg(posterJoinService.getById(str),aid,templateId);
		}
		response.success("成功");
        return response;
    }

	/**
	 * 删除机构
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/join/del")
	@ResponseBody
    public Response joinDel(Model model,String id)throws Exception {
		Response response = new  Response();
		if(StringUtils.isNotEmpty(id)){
			PosterJoin posterJoin=posterJoinService.getById(id);
			if(posterJoin!=null) {
				posterJoin.setStatus(0);
				posterJoinService.save(posterJoin);
			}
		}
		response.success("成功");
        return response;
    }
    /**
	 * 删除海报
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/activityJoin/del")
	@ResponseBody
    public Response activityJoinDel(Model model,String id)throws Exception {
		Response response = new  Response();

		PosterActivityJoin activityJoin = activityJoinService.getById(id);

		//删除海报文件
		String file_path = SystemResourceLocator.getValue("file_save_path")+"/poster/";
		File file = new File(file_path+activityJoin.getPosterImg());
		file.delete();

		activityJoinService.delete(id);
		response.success("成功");
        return response;
    }


	/**
	 * 导入机构信息
	 * @param model
	 * @param id
	 * @param file
	 * @return
	 */
	@RequestMapping(value="/join/import")
	@ResponseBody
	public Response teacherImport(Model model,String id,@RequestParam("file") MultipartFile file) {
		Response response = new  Response();
		try {
			List<Map<String,String>> datas=ImLibUserController.analysisExFile(file);
			if(datas!=null && datas.size()>0){
				List<PosterJoin> posterJoins=new ArrayList<PosterJoin>();
				PosterJoin posterJoin=null;
				for (Map<String,String> map : datas) {
					posterJoin=new PosterJoin();
					posterJoin.setName(map.get("data_0"));
					posterJoin.setPhone(map.get("data_1"));
					posterJoin.setCreateTime(new Date());
					posterJoin.setStatus(1);
					posterJoins.add(posterJoin);
				}
				if(posterJoins.size()>0) {
					posterJoinService.save(posterJoins);
				}
			}
			response.success("导入成功");
		} catch (Exception e) {
			logger.error("导入机构异常", e);
			response.failure("导入机构异常："+e.getMessage());
		}
		return response;
	}	
    
    
	

}
