package com.ssj.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.fx.domain.Merchant;
import com.ssj.bean.sys.fx.domain.MerchantArea;
import com.ssj.bean.sys.fx.domain.MerchantOut;
import com.ssj.bean.sys.problem.domain.BanbenDetail;
import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.bean.weixin.libmy.domain.TbLibJoin;
import com.ssj.bean.weixin.libmy.domain.TbLibSubscribe;
import com.ssj.bean.weixin.problem.domain.CnArea;
import com.ssj.bean.weixin.problem.domain.Experience;
import com.ssj.bean.weixin.problem.domain.Problem;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.conch.push.util.PushConstants;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.basic.utils.StringUtils;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.util.HttpRemote;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.service.sys.fx.service.MerchantAreaService;
import com.ssj.service.sys.fx.service.MerchantService;
import com.ssj.service.sys.problem.service.IBanbenDetailService;
import com.ssj.service.sys.push.service.SconXingeService;
import com.ssj.service.sys.sort.service.SortService;
import com.ssj.service.weixin.library.service.ILibJoinService;
import com.ssj.service.weixin.library.service.ILibSubscribeService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.library.service.LibUserHistoryService;
import com.ssj.service.weixin.problem.service.*;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.user.service.UserService;
import com.ssj.sys.util.thirdparty.excel.CustomizeToExcel;
import com.ssj.sys.util.thirdparty.excel.ExcelColumn;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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 org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

@RequestMapping("sys/problem")
@Controller
public class SysProblemController extends BaseController{
	@Autowired
	private ProblemService  problemService;
	@Autowired
	private ExperienceService  experienceService;
    @Autowired
    private SortService  sortService;
    @Autowired
	private  ILibSubscribeService libSubscribeService;
	@Autowired
    private  ILibJoinService  libJoinService;
	@Autowired
	private LibUserHistoryService  libUserHistoryService;
	@Autowired
	private  ILibVipService iLibVipService;
	@Autowired
	private UserService userService;
	 @Autowired
	private PushTemplateService pushTemplateService;
	 @Autowired
	private ValidVipService validVipService;
	 @Autowired
	private CnAreaService cnAreaService;
	 @Autowired
    private RequestMethodLogService requestMethodLogServicee;
	 @Autowired
	private SconXingeService sconXingeService;
	@Autowired
	 private IBanbenDetailService banbenDetailService;
	@Autowired
	private MerchantService merchantService;
	@Autowired
	private MerchantAreaService areaService;
	
	/**
	 * 
	* 创建人:zhanglin
	* @param @param model
	* @param @param pageSize
	* @param @param pageNo
	* @param @return
	* @param @throws Exception       
	* 方法说明：操作指南后台查询
	 * @date 2017年8月25日 上午9:34:49
	 */
	@RequestMapping("/problemlist")
	public String problemlist(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("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= problemService.findForPage(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/problem/problemlist";
	}
	/**
	 * 
	* 创建人:zhanglin
	* @param @param problem
	* @param @return       
	* 方法说明：保存或修改问题
	 * @date 2017年8月3日 下午3:54:10
	 */
	@RequestMapping(value = "/saveProblem", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity  saveProblem( Problem  problem) throws Exception{
	  ResponseEntity   response  = new  ResponseEntity ();
	  if(problem.getNum()==null){
		  problem.setNum(problemService.countType());
	  }
	  problem.setCreateTime(new Date());
	  problem= problemService.save(problem);
//	  if(problem.getType()>=4){
//		  String sysurl= (String) SystemResourceLocator.getValue("sys_url");
//		  String link = problem.getLink();
//		  if(link==null || !link.contains(sysurl)){
//			  String url=sysurl+"/article/{id}.html";
//			  url=url.replace("{id}", problem.getId());
//			  problem.setLink(url);
//			  problemService.save(problem);
//		  }
//	  }
    	response.success();
    	return response;
    }
	/**
	 * 
	* 创建人:zhanglin
	* @param @param model
	* @param @param id
	* @param @return       
	* 方法说明：跳转到添加或修改问题页面
	 * @date 2017年8月25日 上午9:38:13
	 */
	 @RequestMapping("/addproblem")
	 public String addproblem(Model model,@RequestParam(required = false, defaultValue = "1")String id){
		 Problem  problem = problemService.getById(id);
		 if(problem ==null ) {problem =new Problem();}
		 model.addAttribute("problem",problem);
		 return "sys/problem/addproblem";

}
	 /**
	  * 
	 * 创建人:zhanglin
	 * @param @param id
	 * @param @return       
	 * 方法说明：操作指南删除
	  * @date 2017年8月25日 上午9:37:41
	  */
	 @RequestMapping(value = "/problemDelete", method = RequestMethod.POST)
	   @ResponseBody
	   public Response problemDelete(String id){
		  Response  response  = new  Response();
		  problemService.delete(id);
	   	response.success();
	   	return response;
	   }
	 /**
	  * 
	 * 创建人:zhanglin
	 * @param @param model
	 * @param @param pageSize
	 * @param @param pageNo
	 * @param @return
	 * @param @throws Exception       
	 * 方法说明：零元阅读后台查询
	  * @date 2017年8月25日 上午9:36:31
	  */
	 @RequestMapping("/experiencelist")
		public String experiencelist(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("grade", request.getParameter("grade")==null?"":request.getParameter("grade"));
			 params.put("type", request.getParameter("type")==null?"":request.getParameter("type"));
			 params.put("beginDate", request.getParameter("beginDate")==null?"":request.getParameter("beginDate"));
			 params.put("endDate", request.getParameter("endDate")==null?"":request.getParameter("endDate"));
			SplitPage sp = new SplitPage();
		        sp.setAction(request.getRequestURI().toString());
		        sp.setPageNo(pageNo);
		        sp.setPageSize(pageSize);
		        sp.setParams(params);
		    Page<Map<String, Object>>  page= experienceService.findForExpPage(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);
			model.addAttribute("grade", sortService.getParamValByCode("grade"));//年级
			return "sys/problem/experiencelist";
		}
	 /**
	  * 
	 * 创建人:zhanglin
	 * @param @param experience
	 * @param @return       
	 * 方法说明：零元阅读后台保存
	  * @date 2017年8月25日 上午9:40:03
	  */
	 @RequestMapping(value = "/saveExperience", method = RequestMethod.POST)
	    @ResponseBody
	    public ResponseEntity  saveExperience( Experience  experience){
		  ResponseEntity   response  = new  ResponseEntity ();
		  experience.setDateTime(new Date());
		  experienceService.save(experience);
	    	response.success();
	    	return response;
	    }
	 /**
	  * 
	 * 创建人:zhanglin
	 * @param @param model
	 * @param @param id
	 * @param @return       
	 * 方法说明：跳转到添加或修改页面
	  * @date 2017年8月25日 上午9:37:00
	  */
	 @RequestMapping("/addexperience")
	 public String addexperience(Model model,@RequestParam(required = false, defaultValue = "1")String id){
		 Experience  experience = experienceService.getById(id);
		 if(experience ==null ) {experience =new Experience();}
		 model.addAttribute("experience",experience);
		 model.addAttribute("grade", sortService.getParamValByCode("grade"));//年级
		 return "sys/problem/addexperience";

}
	 /**
	  * 
	 * 创建人:zhanglin
	 * @param @param id
	 * @param @return       
	 * 方法说明：零元阅读删除
	  * @date 2017年8月25日 上午9:35:56
	  */
	 @RequestMapping(value = "/experienceDelete", method = RequestMethod.POST)
	   @ResponseBody
	   public Response experienceDelete(String id){
		  Response  response  = new  Response();
		  experienceService.delete(id);
	   	response.success();
	   	return response;
	   }
/**
 * 
* 创建人:zhanglin
* @param @param id
* @param @param price
* @param @return       
* 方法说明：修改排序保存
 * @date 2017年8月25日 上午9:35:34
 */
	    @RequestMapping(value = "/updatenum", method = RequestMethod.POST)
		 @ResponseBody
		 public Response updatenum( String id,Integer price){
			 Response response = new  Response();
			 problemService.updatenum(id, price);
			 response.success();
			 return response;
		 }


/**
 * 
* 创建人:zhanglin
* @param @param model
* @param @param pageSize
* @param @param pageNo
* @param @return
* @param @throws Exception       
* 方法说明：PC端一键签到签离
 * @date 2017年10月25日 上午11:12:25
 */
@RequestMapping("/checklist")
public String checklist(Model model,
		@RequestParam(required = false, defaultValue = "10") int pageSize,
		@RequestParam(required = false, defaultValue = "1") int pageNo,
		@RequestParam(required = false, defaultValue = "1")String type)throws Exception {
	Map<String, Object> params = new HashMap<String, Object>();
	params.put("child_name", request.getParameter("child_name")==null?"":request.getParameter("child_name"));
	params.put("libId", request.getParameter("libId")==null?"":request.getParameter("libId"));
	SplitPage sp = new SplitPage();
    sp.setAction(request.getRequestURI().toString());
    sp.setPageNo(pageNo);
    sp.setPageSize(pageSize);
    sp.setParams(params);
    Page<Map<String, Object>> page =  null;
    if("2".equals(type)){
    	 page = libUserHistoryService.findCheckOutPage(params, initPage(pageNo, pageSize));
    }else{
         page = libUserHistoryService.findCheckPage(params, initPage(pageNo, pageSize));
    }
   
    params.put("type", type);
	sp.setRowCnt((int) page.getTotalElements());
	model.addAttribute("list", page.getContent());
	model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
	model.addAttribute("page", sp);
	model.addAttribute("search", params);
	model.addAttribute("libList",libJoinService.getLibJoinByCode(orgcodeList()));
	return "sys/problem/checklist";
}
/**
 * 
* 创建人:zhanglin
* @param @param request
* @param @param model
* @param @param vipIds
* @param @param type
* @param @param libId
* @param @return
* @param @throws Exception       
* 方法说明：保存签到签离数据
 * @date 2017年10月26日 下午10:08:44
 */
@RequestMapping(value = "/savesub", method = RequestMethod.POST)
@ResponseBody
 public Response savesub(HttpServletRequest request, Model model,
		 @RequestParam(value = "vipIds[]")String[] vipIds, String type,String libId) throws Exception {
	Response responseEntity = new Response();
	Map<String, Object> data = new HashMap<String, Object>();
	List<TbLibSubscribe> libSubscribes = new ArrayList<TbLibSubscribe>();
	TbLibSubscribe libSubscribe = null;
	Date now = new Date();
	//用于时间累加
	Map<String, Date> dateMap = new HashMap<>(16);
	dateMap.put("now", now);
	for (int i = 0; i < vipIds.length; i++) {
			if("1".equals(type)){   //签到
				//校验是否已经签到过
				libSubscribe = libSubscribeService.findTodaySignedHistoryByVipId(vipIds[i]);
				if (libSubscribe != null) {//已经签到过了，不可重复签到
					logger.warn("确认到馆失败，不能重复签到，vipId=" + vipIds[i]);
					continue;
				}

			LibVip libVip=iLibVipService.getById(vipIds[i]);
			libSubscribe=new TbLibSubscribe();
			libSubscribe.setRykeTime(new Date());
			libSubscribe.setOrderDate(new Date());
			libSubscribe.setRykeConfirmUser(adminId());
			libSubscribe.setUserId(libVip.getUserId());
			libSubscribe.setFlowStat("3");
			libSubscribe.setVipId(vipIds[i]);
			libSubscribe.setLibId(libId);
			libSubscribe.setCreateTime(new Date());
			libSubscribe.setStat("1");
			libSubscribes.add(libSubscribe);

			libSubscribeService.signInCreatePush(vipIds[i], libId, dateMap);

			try {
				Map<String,String> data1 =new HashMap<String, String>();
				User user = userService.getById(libSubscribe.getUserId());
				TbLibJoin libJoin = libJoinService.getById(libId);
				String template_id_short="OPENTM207941156";
				data1.put("first", libVip.getChildName()+"妈妈/爸爸，您好！我是馆长"+libJoin.getLeadueManager()+"，您的孩子已安全到达"+libJoin.getLeagueName()+"\n");
				data1.put("keyword1", libVip.getChildName());
				data1.put("keyword2", DateHelper.format(new Date(),"yyyy年MM月dd日  HH时mm分"));
				data1.put("keyword3",libJoin.getLeagueName());
				data1.put("remark", "\n状态：已到馆");
				SendTemplateShort templateShort = new SendTemplateShort(user.getAccount(), template_id_short, null, data1);
				pushTemplateService.savePushWxTemplate(templateShort);
				
				String contentMessage =  "尊敬的"+libVip.getParentName()+"家长，您的孩子已于"+DateHelper.format(new Date(),"yyyy年MM月dd日  HH时mm分")+"，安全到达私塾家"+libJoin.getLeagueName()+"，稍后会由系统推送给您今日作业反馈报告，请您留意，感谢";
				sconXingeService.asynPushThreadTask(libVip.getUserId(),null, 2, contentMessage,PushConstants.PUSH_HOMEWORK);
				//NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(),  new  SendTemplate(user.getAccount(),template_id,null,data1));
			} catch (Exception e) {
				logger.info("图书馆签到模板，推送异常..."+e.getMessage());
			}
			}else{  //签离
				libSubscribe=libSubscribeService.getById(vipIds[i]);
				LibVip vip = iLibVipService.getById(libSubscribe.getVipId());
				if(libSubscribe!=null){
						libSubscribe.setLeaveTime(new Date());
						libSubscribe.setLeaveConfirmUser(adminId());
						libSubscribe.setFlowStat("4");
						libSubscribes.add(libSubscribe);
						try {
							Map<String,String> data1 =new HashMap<String, String>();
							User user = userService.getById(libSubscribe.getUserId());
							TbLibJoin libJoin = libJoinService.getById(libId);
							String template_id_short="OPENTM406027659";
							data1.put("first", vip.getChildName()+"妈妈/爸爸，您好。我是馆长"+libJoin.getLeadueManager()+"您的孩子已离开"+libJoin.getLeagueName()+",请留意孩子是否安全到家。\n");
							data1.put("keyword1", vip.getChildName());
							data1.put("keyword2", DateHelper.format(new Date(),"yyyy年MM月dd日  HH时mm分"));
							data1.put("keyword3",libJoin.getLeagueName());
							data1.put("remark", "\n状态：已离馆");
							SendTemplateShort templateShort = new SendTemplateShort(user.getAccount(), template_id_short, null, data1);
							pushTemplateService.savePushWxTemplate(templateShort);
							//NewsUtil.sendTemplate( tokenManager.getSSJAccessToken(),  new  SendTemplate(user.getAccount(),template_id,null,data1));
						} catch (Exception e) {
							logger.info("图书馆签离模板，推送异常..."+e.getMessage());
						}
				}
			}
			
		}
		if(libSubscribes.size()>0){
			libSubscribeService.save(libSubscribes);
		}
	responseEntity.success(data, "成功！");
    return responseEntity;
 }



/**
 * 
* 创建人:zhanglin
* @param @param model
* @param @param pageSize
* @param @param pageNo
* @param @return
* @param @throws Exception       
* 方法说明：查询每个月各馆各种卡类有效会员数
 * @date 2017年12月8日 上午10:55:39
 */
@RequestMapping("/validViplist")
public String validViplist(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("months", request.getParameter("months")==null?"":request.getParameter("months"));
	params.put("libId", request.getParameter("libId")==null?"":request.getParameter("libId"));
	params.put("type", request.getParameter("type")==null?"":request.getParameter("type"));
	if(!"admin".equals(loginName())){
		params.put("orgCode", orgCodeStr());
	}
	SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
    Page<Map<String, Object>>  page= validVipService.findValidVipPage(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);
	model.addAttribute("libList",libJoinService.getLibJoinByCode(orgcodeList()));
	return "sys/problem/validViplist";
}

@RequestMapping("/validViplist2")
public String validViplist2(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("beginDate", request.getParameter("beginDate")==null?"":request.getParameter("beginDate"));
	 params.put("endDate", request.getParameter("endDate")==null?"":request.getParameter("endDate"));
	 params.put("libId", request.getParameter("libId")==null?"":request.getParameter("libId"));
	 if(!"admin".equals(loginName())){
			params.put("orgCode", orgCodeStr());
		}
	 SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
    Page<Map<String, Object>>  page= validVipService.findValidVip2Page(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);
	model.addAttribute("libList",libJoinService.getLibJoinByCode(orgcodeList()));
	return "sys/problem/validViplist2";
}
/**
 * 
* 创建人:zhanglin
* @param @param model
* @param @param pageSize
* @param @param pageNo
* @param @return
* @param @throws Exception       
* 方法说明：查询学校地址
 * @date 2017年12月8日 上午10:57:18
 */
@RequestMapping("/cnArealist")
public String cnArea(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("province", request.getParameter("province")==null?"":request.getParameter("province"));
	params.put("city", request.getParameter("city")==null?"":request.getParameter("city"));
	params.put("area", request.getParameter("area")==null?"":request.getParameter("area"));
	SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
    Page<Map<String, Object>>  page= cnAreaService.findCnAreaPage(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/problem/cnArealist";
}
/**
 * 
* 创建人:zhanglin
* @param @param model
* @param @param id
* @param @return       
* 方法说明：跳转或修改
 * @date 2017年12月8日 上午11:44:30
 */
@RequestMapping("/addcnArea")
public String addcnArea(Model model,@RequestParam(required = false, defaultValue = "1")String id){
	CnArea  cnArea = cnAreaService.getById(id);
	 if(cnArea ==null ) {cnArea =new CnArea();}
	 List<CnArea> areaList = cnAreaService.findByTypeList("3");
	 model.addAttribute("cnArea",cnArea);
	 model.addAttribute("areaList",areaList);
	 return "sys/problem/addcnArea";

}
/**
 * 
* 创建人:zhanglin
* @param @param cnArea
* @param @return       
* 方法说明：保存
 * @date 2017年12月8日 上午11:46:19
 */
@RequestMapping(value = "/saveCnArea", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity  saveCnArea( CnArea  cnArea){
  ResponseEntity   response  = new  ResponseEntity ();
	String url = "https://apis.map.qq.com/ws/geocoder/v1/";
	Map<String, Object> data = new HashMap<String, Object>();
	try {
		data.put("address",cnArea.getSchoolAddress());
		data.put("key", "CA5BZ-KRF3J-3RXFX-FUAYV-EUIC7-ADBDK");
		JSONObject jsonObject = JSONObject.parseObject(HttpRemote.GETMethod(url, data));
		if(jsonObject.getInteger("status") == 0){  //正常
			String lat = jsonObject.getJSONObject("result").getJSONObject("location").getString("lat"); //纬度
			String lng = jsonObject.getJSONObject("result").getJSONObject("location").getString("lng"); //经度
			cnArea.setSchoolLng(lng);
			cnArea.setSchoolLat(lat);
		}
	} catch (Exception e) {
		logger.error("异常", e);
	}
    cnAreaService.save(cnArea);
	response.success();
	return response;
}

	@RequestMapping(value = "/cnAreaDelete", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity  cnAreaDelete( String  id){
		ResponseEntity   response  = new  ResponseEntity ();
		cnAreaService.delete(id);
		//CnArea cnArea = cnAreaService.getById(id);
		response.success("删除成功!");
		return response;
	}
/**
 * 
* 创建人:zhanglin
* @param @param request
* @param @param response2
* @param @return       
* 方法说明：导入学校地址
 * @date 2017年12月14日 下午3:26:59
 */
@RequestMapping(value = "/cnAreaSave", method = RequestMethod.POST)
@ResponseBody
public Response cnAreaSave(HttpServletRequest request,HttpServletResponse response2) {
	 Response response = new Response();
	 XSSFWorkbook workbook = null; 
	 try {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");  
		workbook = new XSSFWorkbook(file.getInputStream());
		XSSFSheet sheet = workbook.getSheetAt(0);   //读取第一个工作簿 
        Row row = null;  
        
        int startReadLine = 1;
        //int lastRow = -1;
        for(int i=startReadLine; i<=sheet.getLastRowNum(); i++) {  
        	Thread.sleep(1000);
        	CnArea cnArea= new CnArea();
            row = sheet.getRow(i);
            int x = 0;
            cnArea.setType(4);
        	cnArea.setPy("xx");
        	cnArea.setIsHotcity(0);
        	String city = "";
            for(Cell c : row) {  
            	x = c.getColumnIndex();
                c.setCellType(Cell.CELL_TYPE_STRING);
               // Map<String, Integer> isMerge =ReadMergeRegionExcel.isMergedRegion(sheet, i, c.getColumnIndex());
                
                //判断是否具有合并单元格  
                String rs  = c.getRichStringCellValue().toString().trim(); 
                if(x == 0){
                	city = rs;
                }else if (x==1){
                	String name = cnAreaService.getName(city,rs);
           		 	cnArea.setUpId(name);
                }else if (x==2){
                	cnArea.setName(rs);
                }else if (x==3){
                	cnArea.setSchoolAddress(rs);
                	String url = "https://apis.map.qq.com/ws/geocoder/v1/";
            		Map<String, Object> data = new HashMap<String, Object>();
            		try {
            			data.put("address",rs);
            			data.put("key", "CA5BZ-KRF3J-3RXFX-FUAYV-EUIC7-ADBDK");
            			JSONObject jsonObject = JSONObject.parseObject(HttpRemote.GETMethod(url, data));
            			if(jsonObject.getInteger("status") == 0){  //正常
            				String lat = jsonObject.getJSONObject("result").getJSONObject("location").getString("lat"); //纬度
            				String lng = jsonObject.getJSONObject("result").getJSONObject("location").getString("lng"); //经度
            				cnArea.setSchoolLng(lng);
            				cnArea.setSchoolLat(lat);
            				}	
            		} catch (Exception e) {
						logger.error("异常", e);
            		}		
            		cnArea = cnAreaService.save(cnArea);
                }
            }    
        }  
	} catch (FileNotFoundException e) {
		 logger.error("异常", e);
	} catch (Exception e) {
		 logger.error("异常", e);
	}
	 response.success("添加成功");
	 return response;
}
/**
 * 
* 创建人:zhanglin
* @param @param model
* @param @return
* @param @throws Exception       
* 方法说明：跳转导入页面
 * @date 2017年12月14日 下午3:27:25
 */
@RequestMapping("/cnAreaImport")
public String cnAreaImport(Model model) throws Exception {
	 return "sys/problem/cnAreaImport";
}
/**
 * 
* 创建人:zhanglin
* @param @param model
* @param @param pageSize
* @param @param pageNo
* @param @return
* @param @throws Exception       
* 方法说明：
 * @date 2017年12月27日 下午5:34:07
 */
@RequestMapping("/RequestMethodLoglist")
public String RequestMethodLoglist(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("libId", request.getParameter("libId")==null?"":request.getParameter("libId"));
	if(!"admin".equals(loginName())){
		params.put("orgCode", orgCodeStr());
	}
	SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
    Page<Map<String, Object>>  page= requestMethodLogServicee.findRequestMethodLogPage(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);
	model.addAttribute("libList",libJoinService.getLibJoinByCode(orgcodeList()));
	return "sys/problem/RequestMethodLoglist";
}
/**
 * 
* 创建人:zhanglin
* @param @param id
* @param @param ids
* @param @return       
* 方法说明：旧会员卡数据换到新会员卡上
 * @date 2018年1月12日 下午4:28:57
 */
@RequestMapping(value = "/updateLibVip", method = RequestMethod.POST)
@ResponseBody
public Response updateLibVip( @RequestParam(value = "id")String id,@RequestParam(value = "ids")String ids){
	 Response response = new  Response();
	 problemService.updateLibVip(id, ids);
	 problemService.updateZybStudentBg(id, ids);
	 problemService.updateZybStudentPush(id, ids);
	 problemService.updateZybStudentWork(id, ids);
	 problemService.updateLibUserHistory(id, ids);
	 problemService.updateOrderDetails(id, ids);
	 problemService.updateLibBookDetails(id, ids);
	 problemService.updateLibVipService(id, ids);
	 problemService.updateLibOrderDetails(id, ids);
	 problemService.updateLibSubscribe(id, ids);
	 response.success();
	 return response;
}
/**
 * 
* 创建人:zhanglin
* @param @param model
* @param @param pageSize
* @param @param pageNo
* @param @return
* @param @throws Exception       
* 方法说明：旧卡页面
 * @date 2018年1月12日 下午4:30:33
 */
@RequestMapping("/viplist")
public String viplist(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("flow_id", request.getParameter("flow_id")==null?"":request.getParameter("flow_id"));
	params.put("child_name", request.getParameter("child_name")==null?"":request.getParameter("child_name"));
	SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
    Page<Map<String, Object>>  page= problemService.findVipPage(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/problem/viplist";
}        
/**
 * 
* 创建人:zhanglin
* @param @param model
* @param @param pageSize
* @param @param pageNo
* @param @return
* @param @throws Exception       
* 方法说明：选择新卡页面
 * @date 2018年1月12日 下午4:30:52
 */
@RequestMapping("/updateviplist")
public String updateviplist(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("flow_id", request.getParameter("flow_id")==null?"":request.getParameter("flow_id"));
	params.put("ids", request.getParameter("ids"));
	SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
    Page<Map<String, Object>>  page= problemService.findUpdateVipPage(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/problem/updateviplist";
	                    
}

	@RequestMapping("/schoolBanbenlist")
	public String schoolBanbenlist(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("courseName", request.getParameter("courseName")==null?"":request.getParameter("courseName")); //科目
		params.put("grade", request.getParameter("grade")==null?"":request.getParameter("grade")); //年级
		SplitPage sp = new SplitPage();
		sp.setAction(request.getRequestURI().toString());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<Map<String, Object>>  page= problemService.findBanbenDetailPage(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);
		model.addAttribute("grade", sortService.getParamValByCode("grade"));//年级
		model.addAttribute("zyb_course", sortService.getParamValByCode("zyb_course"));//科目
		model.addAttribute("version",SystemResourceLocator.getVersionList());
		return "sys/problem/schoolBanbenlist";
	}

	@RequestMapping("/schoolBanbenAdit")
	public String schoolBanbenAdit(Model model,@RequestParam( defaultValue = "0")String id) throws Exception {

		BanbenDetail detail = banbenDetailService.getById(id);
		if(detail == null){
			detail = new BanbenDetail();
		}
		model.addAttribute("grade", sortService.getParamValByCode("grade"));
		model.addAttribute("zyb_course", sortService.getParamValByCode("zyb_course"));
		model.addAttribute("version",SystemResourceLocator.getVersionList());
		model.addAttribute("how",detail);
		return "sys/problem/banbenAdd";
	}

	@RequestMapping(value = "/banbenSave", method = RequestMethod.POST)
	@ResponseBody
	public Response banbenSave(BanbenDetail how) {
		Response response = new Response();
		String[] gradeAttr = how.getGrade().split(",");
		for (int i = 0; i < gradeAttr.length; i++) {
			BanbenDetail detail = banbenDetailService.findBanbenByAnyParams(how.getCourseName(),how.getSchoolId(),gradeAttr[i].trim());
			if(detail == null){
				detail = new BanbenDetail();
			}
			detail.setBanben(how.getBanben());
			detail.setCourseName(how.getCourseName());
			detail.setGrade(gradeAttr[i].trim());
			detail.setSchoolId(how.getSchoolId());
			detail.setSchoolName(how.getSchoolName());
			detail.setCreateTime(new Date());
			detail.setArea(how.getArea());
			banbenDetailService.save(detail);
		}

		response.success("添加成功");
		return response;
	}
	/**
	 * 删除
	 * @param id
	 * @return
	 * 创建人：ZhangCaibao
	 * 2017年9月26日 下午3:13:43
	 * @Response
	 */
	@RequestMapping(value = "/banbenDelete", method = RequestMethod.POST)
	@ResponseBody
	public Response banbenDelete(
			@RequestParam(value = "id")String id) {
		Response response = new Response();
		banbenDetailService.delete(id);
		response.success("删除成功");
		return response;
	}

	@RequestMapping("/schoolList")
	public String schoolList(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().toString());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<Map<String, Object>>  page= cnAreaService.findCnAreaPage(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/problem/schoolList";
	}

	@RequestMapping(value = "/exportDetail", method = RequestMethod.POST)
	@ResponseBody
	public void exportDetail(HttpServletRequest request, HttpServletResponse response) {
		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>();
			//筛选月份
			params.put("name", request.getParameter("name")==null?"":request.getParameter("name"));
			params.put("province", request.getParameter("province")==null?"":request.getParameter("province"));
			params.put("city", request.getParameter("city")==null?"":request.getParameter("city"));
			params.put("area", request.getParameter("area")==null?"":request.getParameter("area"));
			List<Map<String, Object>> list = cnAreaService.findCnAreaAll(params);
			List<ExcelColumn> myColumns3 = new ArrayList<ExcelColumn>();
			myColumns3.add(new ExcelColumn("名称", "name", 20));
			myColumns3.add(new ExcelColumn("类型", "type", 20));
			myColumns3.add(new ExcelColumn("首字母拼音", "py", 20));
			myColumns3.add(new ExcelColumn("是否热门城市", "is_hotcity", 20));
			myColumns3.add(new ExcelColumn("详细地址", "school_address", 20));
			myColumns3.add(new ExcelColumn("学校经度", "school_lng", 20));
			myColumns3.add(new ExcelColumn("学校纬度", "school_lat", 20));
			CustomizeToExcel.downFile(myColumns3, list, os);
		}catch (IOException e) {
			logger.error("异常", e);
		}catch (Exception e1){
			logger.error("异常", e1);
		}finally{
			if(os != null){
				try {
					os.flush();
					os.close();
				} catch (IOException e) {
					logger.error("异常", e);
				}
			}
		}
	}

	@RequestMapping("/areaMerchantList")
	public String areaMerchantList(Model model,
								   @RequestParam(required = false, defaultValue = "10") int pageSize,
								   @RequestParam(required = false, defaultValue = "1") int pageNo)
			throws Exception {
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("schoolAreaId", request.getParameter("schoolAreaId")==null?"":request.getParameter("schoolAreaId"));
		params.put("LIKE_unitName", request.getParameter("unitName")==null?"":request.getParameter("unitName"));
		params.put("LIKE_posCode", request.getParameter("posCode")==null?"":request.getParameter("posCode"));

		String orgCode=request.getParameter("orgCode")==null?"":request.getParameter("orgCode");
		if(StringUtils.isNotEmpty(orgCode)) {
			params.put("LIKE_orgCode", orgCode);
		}else {
			params.put("LIKE_orgCode", merchant.getOrgCode());
		}

		SplitPage sp = new SplitPage();
		sp.setAction(request.getRequestURI());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<MerchantOut> page = cnAreaService.findMerchantByPage(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);
		model.addAttribute("curMerchant", merchant);
		return "sys/problem/merchantAreaList";
	}

	@RequestMapping("/merchantList")
	public String merchantList(Model model, @RequestParam(required = false, defaultValue = "10") int pageSize, @RequestParam(required = false, defaultValue = "1") int pageNo) {
		HttpSession session = request.getSession();
		Admin admin =(Admin) session.getAttribute("admin");
		Merchant merchant=merchantService.getMerchantByPosCode(admin.getLoginName());

		Map<String, Object> params = new HashMap<String, Object>();

		params.put("LIKE_unitName", request.getParameter("unitName")==null?"":request.getParameter("unitName"));
		params.put("LIKE_posCode", request.getParameter("posCode")==null?"":request.getParameter("posCode"));
		params.put("NOT_status", 4);
		 
		String orgCode=request.getParameter("orgCode")==null?"":request.getParameter("orgCode");
		if(StringUtils.isNotEmpty(orgCode)) {
			params.put("LIKE_orgCode", orgCode);
		}else {
			params.put("LIKE_orgCode", merchant.getOrgCode());
		}

		SplitPage sp = new SplitPage();
		sp.setAction(request.getRequestURI());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<Merchant> page = merchantService.findMerchantByPage(params, initPage(pageNo, pageSize, Sort.Direction.DESC, new String[]{"createTime"}));
		sp.setRowCnt((int) page.getTotalElements());
        params.put("schoolAreaId", request.getParameter("schoolAreaId")==null?"":request.getParameter("schoolAreaId"));
		model.addAttribute("list", page.getContent());
		model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
		model.addAttribute("page", sp);
		model.addAttribute("search", params);
		model.addAttribute("curMerchant", merchant);
		return "sys/problem/merchantList";
	}

	@RequestMapping(value = "/delArea", method = RequestMethod.POST)
	@ResponseBody
	public Response delArea(@RequestParam(value = "id")String id,@RequestParam(value = "areaId")String areaId) {
		Response response = new Response();
		MerchantArea area =areaService.findBySchoolIdAndMerchant(areaId,id);
		if(area!=null){
			areaService.delete(area);
		}
		response.success("删除成功");
		return response;
	}

	@RequestMapping(value = "/addMerchant", method = RequestMethod.POST)
	@ResponseBody
	public Response addMerchant(@RequestParam(value = "ids[]")String[] ids,@RequestParam(value = "areaId")String areaId) {
		Response response = new Response();
		for(String id:ids){
			MerchantArea area =areaService.findBySchoolIdAndMerchant(areaId,id);
			if(area==null){
				MerchantArea next = new MerchantArea();
				next.setCnAreaId(areaId);
				next.setMerchantId(id);
				next.setCreateTime(new Date());
				next.setSchoolName(cnAreaService.getById(areaId).getName());
				areaService.save(next);
			}
		}

		response.success("添加成功");
		return response;
	}
}
