package com.iamberry.wechat.handles.drp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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

import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.iamberry.wechat.core.entity.JsonBack;
import com.iamberry.wechat.core.entity.Page;
import com.iamberry.wechat.core.entity.PageBean;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.banner.MessageDTO;
import com.iamberry.wechat.core.entity.drp.ApplyPlaceLogs;
import com.iamberry.wechat.core.entity.drp.ApplyUserInfo;
import com.iamberry.wechat.core.entity.drp.PageBeanEarningLogs;
import com.iamberry.wechat.core.entity.drp.PageBeanPlaceInfo;
import com.iamberry.wechat.core.entity.drp.PageBeanPlaceLogs;
import com.iamberry.wechat.core.entity.drp.PageBeanWithdraw;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.drp.PlaceInfoBattleDto;
import com.iamberry.wechat.core.entity.drp.PlaceLogs;
import com.iamberry.wechat.core.entity.drp.PlaceRoleInfo;
import com.iamberry.wechat.core.entity.drp.PlaceWithDrawalsLogs;
import com.iamberry.wechat.core.entity.flow.TemplateInfo;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.face.drp.DrpRoleInfoService;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.drp.PlaceLogsService;
import com.iamberry.wechat.face.drp.PlaceWithDrawalsLogsService;
import com.iamberry.wechat.face.flow.TemplateInfoService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.qrcode.QrcodeService;
import com.iamberry.wechat.face.reback.RebackStaticService;
import com.iamberry.wechat.service.wechat.WeChatServiceImpl;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.HttpClient431Util;
import com.iamberry.wechat.tools.ImageUtils;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ObjectExcelView;
import com.iamberry.wechat.tools.ResultInfo;

/**
 * @description 后台的分销管理
 * @author 欧阳明
 * @date 2016-4-21
 */
@Deprecated
@Controller
@RequestMapping("/admin/drp")
public class AdminWithDrp {
	@Autowired
	private PlaceInfoService placeInfoService;
	@Autowired
	private PlaceWithDrawalsLogsService placeWithDrawalsLogsService;
	@Autowired
	private PlaceLogsService placeLogsService;
	@Autowired
	private MemberService memberService;

	@Autowired
	private RebackStaticService rebackStaticService;
	@Autowired
	private QrcodeService qrcodeService;
	@Autowired
	private DrpRoleInfoService drpRoleInfoService;
	@Autowired
	private TemplateInfoService templateInfoService;
	@Autowired
	private WeChatServiceImpl weChatServiceImpl;
	

	/**
	 * 后台-进入商户添加页面(在用)
	 * @return
	 */
	@RequestMapping("/addPlaceInfo")
	public String addPlaceInfo(HttpServletRequest request, Model model) {
		// 获取角色列表
		List<PlaceRoleInfo> roles = drpRoleInfoService.getDrpRoleList2();
		// 获取模板列表
		List<TemplateInfo> templates = templateInfoService.getSelectTemplateInfo();
		model.addAttribute("roles", roles);
		model.addAttribute("templates", templates);
		return "/admin/drp/addPlaceInfo";
	}

	/**
	 * 后台-Drp分销增加页面
	 * 
	 * @return
	 */
	@RequestMapping("/addPlaceInfoBattle")
	public String addPlaceInfoBattle(HttpServletRequest request, Model model) {

		// 获取角色列表
		List<PlaceRoleInfo> roles = drpRoleInfoService.getDrpRoleList2();
		// 获取模板列表
		List<TemplateInfo> templates = templateInfoService.getSelectTemplateInfo();
		model.addAttribute("roles", roles);
		model.addAttribute("templates", templates);
		return "/admin/drp/addPlaceInfoBattle";
	}

	/**
	 * 后台-Drp分销商预生成分销商
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addPlaceInfoAutoBattle")
	public Map<String, Object> PlaceInfoAddAutoBattle(HttpServletRequest request, PlaceInfoBattleDto placeInfoDto) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		int count = placeInfoDto.getNum();
		if (count < 1) {
			map.put("state", "false");
			map.put("message", "批量生成必须大于10");
		}
		PlaceInfo placeInfo = new PlaceInfo();
		placeInfo.setTemplateId(placeInfoDto.getTemplateId());
		placeInfo.setHasQrcode(placeInfoDto.getHasQrcode());
		placeInfo.setRoleId(placeInfoDto.getRoleId());
		placeInfo.setPlacePid(placeInfoDto.getPlacePid());
		String timeBefore = "a" + new Date().getTime();
		int beginId = 0;
		for (int i = 0; i < count; i++) {
			placeInfo.setName(timeBefore + i);
			placeInfo.setUserName(timeBefore + i);
			placeInfo.setAddr("待定中");
			placeInfo.setTel("13828467890");
			placeInfo.setRemark("批量生成");
			Map<String, Object> map2 = new HashMap<String, Object>();
			try {
				map2 = addPlaceInfoDeal(placeInfo);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			if (i == 0) {
				beginId = ((PlaceInfo) map2.get("data")).getId();
			}
		}
		map.put("state", "true");
		map.put("message", "批量生成成功");
		map.put("id", beginId);
		return map;
	}

	/**
	 * 后台-Drp预生成分销商修改
	 * 
	 * @return
	 */
	@RequestMapping("/advanceDownLoadPlaceInfos")
	public ModelAndView advanceDownLoadPlaceInfos(HttpServletRequest request) {

		String beginNumStr = request.getParameter("beginNum");
		String numstr = request.getParameter("num");
		Integer beginNum = null;
		Integer num = null;
		if (beginNumStr.equals("") || beginNumStr == null) {
			return null;
		}

		beginNum = Integer.valueOf(beginNumStr);

		// 准备model
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("fileName", "分销商新增记录"); // 下载文件名称
		// 标题
		List<String> titles = new ArrayList<String>();
		titles.add("编号");
		titles.add("公司名");
		titles.add("用户名");
		titles.add("区域名");
		/*
		 * titles.add("是否二维码"); titles.add("父级id"); titles.add("角色id");
		 */
		titles.add("联系方式");
		titles.add("联系地址");
		titles.add("激活码");
		titles.add("备注");
		model.put("titles", titles);
		HashMap<String, Object> mapCondition = new HashMap<String, Object>();
		mapCondition.put("beginNum", beginNum);
		if (!numstr.equals("") && numstr != null) {
			num = Integer.valueOf(numstr);
			mapCondition.put("num", num);
		}
		List<PlaceInfo> placeList = placeInfoService.selectPlaceInfosForDownLoad(mapCondition);
		// 封装导出内容
		List<List<Object>> countexts = new ArrayList<List<Object>>();
		if (placeList != null && placeList.size() > 0) {
			for (PlaceInfo placeInfo : placeList) {
				List<Object> row = new ArrayList<Object>();
				row.add(placeInfo.getId());
				row.add(placeInfo.getName());
				row.add(placeInfo.getUserName());
				row.add(placeInfo.getAreaName());
				row.add(placeInfo.getTel());
				row.add(placeInfo.getAddr());
				row.add(placeInfo.getInitCode());
				row.add(placeInfo.getRemark());
				countexts.add(row);
			}
		}
		model.put("varList", countexts);
		ObjectExcelView erv = new ObjectExcelView();
		ModelAndView mv = new ModelAndView(erv, model);
		return mv;

	}

	/**
	 * 后台-添加一个商户 提交(在用)
	 * 添加一个和批量添加都用此方法
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/addPlaceInfoDeal")
	public Map<String, Object> addPlaceInfoDeal(PlaceInfo placeInfo) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		placeInfo.setStatus(1);
		//默认没完善个人信息	批量的时候添加的 须去掉
		if(placeInfo.getPlaceInfoStus() == null){
			placeInfo.setPlaceInfoStus(1);
		}
		int st = placeInfo.getHasQrcode();
		ResultMsg remsg = placeInfoService.addOne(placeInfo);
		if(!remsg.isStatus()){
			map.put("result", remsg.getResultCode());
			map.put("message", remsg.getMessage());
			return map;
		}
		placeInfo = (PlaceInfo) remsg.getData();
		if (st == 2) {
			qrcodeService.applyPlaceQrcodeUrl(placeInfo.getId());
		}
		if (remsg.getResultCode().equals(ResultInfo.SUCCESSCODE)) {
			map.put("result", ResultInfo.SUCCESSCODE);
			map.put("data", placeInfo);
			map.put("message", "操作成功,激活码是:" + placeInfo.getInitCode());
		} else {
			map.put("result", ResultInfo.ERRORCODE);
			map.put("message", NameUtils.getConfig("ERRORINFO"));
		}
		return map;
	}

	/**
	 * 商户父节点搜索(根据商户名称)(在用  	<一次查出了所有数据 待修改>)
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	//@RequestMapping("/searchPlaceInfoParent")
	@RequestMapping(value="/searchPlaceInfoParent",method = RequestMethod.POST)
	public Map<String, Object> searchPlaceInfoParent(HttpServletRequest request, String search, Integer roleId,Integer templateId)
			throws UnsupportedEncodingException {
		Map<String, Object> map = new HashMap<String, Object>();
		PlaceInfo placeInfo = new PlaceInfo();
		if (search == null || search.equals("")) {
			map.put("error", "参数错误异常"); 
			map.put("status", "false");
			return map;
		}
		if (roleId == null || roleId == 0) {
			map.put("error", "请先选择所属角色");
			map.put("status", "false");
			return map;
		}
		if (templateId == null || templateId == 0) {
			map.put("error", "请先选择模板");
			map.put("status", "false");
			return map;
		}
		if (roleId != null) {
			if(roleId == 47){//如果选择为合伙人或钻石会员则直接返回不查询
				return map;
			}
			if(roleId == 53){
				return map;
			}
			placeInfo.setRoleId(roleId);
		}
		if (templateId != null) { 
			if(templateId == 24 ){
				if(roleId == 52){
					placeInfo.setTemplateId(templateId);
				}else{
					map.put("error", "模板与角色不匹配");
					map.put("status", "false");
					return map;
				}
			}else{
				placeInfo.setTemplateId(templateId);
			}
			
		}
		placeInfo.setName(search);

		map = placeInfoService.SearchPlaceInfo(placeInfo);
		return map;
	}

	/**
	 * 用于修改页面增加角色或者模板的下拉列表
	 * @author 欧阳明
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getSelectList")
	public List getSelectList(HttpServletRequest request) {
		int type = Integer.valueOf(request.getParameter("type"));
		if (type == 1) {
			// 获取角色列表
			List<PlaceRoleInfo> roles = drpRoleInfoService.getDrpRoleList2();
			return roles;
		} else {
			// 获取模板列表
			List<TemplateInfo> templates = templateInfoService.getSelectTemplateInfo();
			return templates;
		}
	}

	/**
	 * 后台-Drp分销编辑页面
	 * @return
	 */
	@RequestMapping("/EditPlaceInfo")
	public String EditPlaceInfoPage(HttpServletRequest request, Model model) {
		int id = Integer.valueOf(request.getParameter("id"));
		PlaceInfo placeInfo = placeInfoService.getPlaceInfoById(id);
		if (placeInfo.getPlacePid() == 0) {
			placeInfo.setParentName(placeInfo.getName());
		} else {
			PlaceInfo parentPlaceInfo = placeInfoService.getPlaceInfoById(placeInfo.getPlacePid());
			placeInfo.setParentName(parentPlaceInfo.getName());
		}
		model.addAttribute("placeInfo", placeInfo);
		return "/admin/drp/editPlaceInfo";
	}

	/**
	 * 后台-Drp分销编辑页面
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/EditPlaceInfoSubmit")
	public Map EditPlaceInfoSubmit(PlaceInfo placeInfo) {
		int st = placeInfo.getHasQrcode();

		PlaceInfo orgin = placeInfoService.getPlaceInfoById(placeInfo.getId());
		if (orgin.getHasQrcode() == 1 && st == 2) {
			qrcodeService.applyPlaceQrcodeUrl(placeInfo.getId());
		}
		if (orgin.getHasQrcode() == 2 && st == 1) {
			qrcodeService.updateQRcodeStatusByUserOpenid(String.valueOf(orgin.getId()));
		}

		ResultMsg remsg = placeInfoService.update(placeInfo);
		HashMap map = new HashMap();
		if (remsg.getResultCode().equals(ResultInfo.SUCCESSCODE)) {
			map.put("result", ResultInfo.SUCCESSCODE);
			map.put("message", remsg.getMessage());
		} else {
			map.put("result", ResultInfo.ERRORCODE);
			map.put("message", NameUtils.getConfig("ERRORINFO"));
		}
		return map;
	}

	/**
	 * 删除分销商-属于逻辑删除
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/deletePlaceInfo")
	public Map deletePlaceInfo(HttpServletRequest request) {
		int id2 = Integer.valueOf(request.getParameter("id"));

		PlaceInfo placeInfo = new PlaceInfo();
		placeInfo.setId(id2);
		placeInfo.setStatus(2);
		ResultMsg remsg = placeInfoService.update(placeInfo);
		HashMap map = new HashMap();
		if (remsg.getResultCode().equals(ResultInfo.SUCCESSCODE)) {
			map.put("result", ResultInfo.SUCCESSCODE);
			map.put("message", remsg.getMessage());
		} else {
			map.put("result", ResultInfo.ERRORCODE);
			map.put("message", NameUtils.getConfig("ERRORINFO"));
		}
		return map;
	}

	/**
	 * 后台-Drp分销绑定页面
	 * 
	 * @return
	 */
	@RequestMapping("/bindingPlaceInfo")
	public String bindingPlaceInfo(
			@RequestParam(value = "pageNO", defaultValue = "1", required = false) int pageNO,
			@RequestParam(value = "pageSize", defaultValue = "5", required = false) int pageSize,
			HttpServletRequest request,Model model) {
		String userInput = request.getParameter("userInput");
		
		Page page = new Page();
		if(userInput !=null && !userInput.equals("")){
			page.getParams().put("userInput", userInput);
			model.addAttribute("userInput", userInput);
		}
		page.setPageNo((pageNO - 1) * pageSize);
		int count = memberService.getCount();
		int pageCount = count % pageSize == 0 ? count / pageSize : count
				/ pageSize + 1;
		page.setPageSize(pageSize);
		List<Member> memberList = memberService.getMemberByPage(page);
		model.addAttribute("memberList", memberList);
		model.addAttribute("pageNO", pageNO);
		model.addAttribute("pageSize", pageCount);
		model.addAttribute("url", "/admin/drp/bindingPlaceInfo?pageSize=" + pageSize
				+ "&pageNO=");
		String initCode = request.getParameter("initCode");
		model.addAttribute("initCode", initCode);
		return "/admin/drp/bindingPlaceInfo";
	}
	/**
	 * 后台-Drp分销绑定
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/bindingPlaceInfoSubmit")
	public Map bindingPlaceInfoSubmit(HttpServletRequest request,Model model) {
		String initCode = request.getParameter("initCode");
		String openId = request.getParameter("openId");
		HashMap map = new HashMap();
		if(initCode == null|| initCode.equals("") || openId == null || openId.equals("")){
			map.put("result", ResultInfo.ERRORCODE);	
		}
		weChatServiceImpl.bulidPlace(initCode, openId);
		map.put("result", ResultInfo.SUCCESSCODE);
		return map;
	}
	
	/**
	 * 后台-Drp分销管理主界面
	 * @param pageNO
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/index")
	public String index() {
		return "/admin/drp/placeInfolist";
	}

	/**
	 * 分销商综合查询
	 * @param str
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/initTable")
	public Map initPlaceInfoTable2(@RequestBody PageBeanPlaceInfo tmp) throws Exception {
		if (tmp != null && tmp.getCondition().getUserNickname() != null
				&& !"".equals(tmp.getCondition().getUserNickname())) {
			tmp.getCondition().setUserNickname(URLEncoder.encode(tmp.getCondition().getUserNickname(), "UTF-8"));
		}
		PageBean page = new PageBean();
		page.setCondition(tmp.getCondition());
		page.setPageNumber(tmp.getPageNumber());
		page.setPageSize(tmp.getPageSize());
		PlaceInfo pinfo = new PlaceInfo();
		if (page.getCondition() == null) {
			page.setCondition(pinfo);
		}
		Map map = placeInfoService.SearchPlaceInfoPage(page);
		page = (PageBean) map.get("page");

		return map;
	}

	// ===================================分销提现管理==========================================
	/**
	 * 分销提现页面
	 * @param str
	 * @return
	 */
	@RequestMapping("/initWithdraw")
	public String withdraw() {
		return "/admin/drp/withdrawlist";
	}

	@RequestMapping("/downLoadWithdraw")
	public ModelAndView downLoadWithdraw(HttpServletRequest request, PlaceWithDrawalsLogs tmp) {
		// 准备model
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("fileName", "分销提现记录"); // 下载文件名称

		// 标题
		List<String> titles = new ArrayList<String>();
		titles.add("分销商");
		titles.add("角色");
		titles.add("金额");
		titles.add("收款人");
		titles.add("收款人联系方式");
		titles.add("收款人卡号");
		titles.add("所属银行");
		titles.add("申请状态");
		titles.add("创建时间");
		model.put("titles", titles);

		// 查询分销提现记录
		PageBean page = new PageBean();
		// page.setCondition(tmp.getCondition());
		PlaceWithDrawalsLogs pinfo = new PlaceWithDrawalsLogs();
		if (page.getCondition() == null) {
			page.setCondition(pinfo);
		}
		List<PlaceWithDrawalsLogs> placeList = placeWithDrawalsLogsService.selectAllMore(tmp);
		// 封装导出内容
		List<List<Object>> countexts = new ArrayList<List<Object>>();
		if (placeList != null && placeList.size() > 0) {
			for (PlaceWithDrawalsLogs drawalsLogs : placeList) {
				List<Object> row = new ArrayList<Object>();
				row.add(drawalsLogs.getName());
				row.add(drawalsLogs.getRoleName());
				row.add(drawalsLogs.getWithDrawalsNum());
				row.add(drawalsLogs.getWithDrawalsName());
				row.add(drawalsLogs.getTel());

				row.add(drawalsLogs.getAccountNo());
				row.add(drawalsLogs.getBankLocal());
				String status = "";
				switch (drawalsLogs.getStatus()) {
				case 1:
					status = "申请中";
					break;
				case 2:
					status = "申请成功";
					break;
				case 3:
					status = "申请失败";
					break;
				}
				row.add(status);
				if (drawalsLogs.getCreateDate() != null) {
					row.add(DateTimeUtil.format(drawalsLogs.getCreateDate(), NameUtils.getConfig("DATE_TIME_FORMAT")));
				}
				countexts.add(row);
			}
		}
		model.put("varList", countexts);
		ObjectExcelView erv = new ObjectExcelView();
		ModelAndView mv = new ModelAndView(erv, model);
		return mv;
	}

	/**
	 * 分销提现管理
	 * 
	 * @param str
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/withdrawTable")
	public Map withdrawTable(@RequestBody PageBeanWithdraw tmp) {
		PageBean page = new PageBean();
		page.setCondition(tmp.getCondition());
		page.setPageNumber(tmp.getPageNumber());
		page.setPageSize(tmp.getPageSize());
		PlaceWithDrawalsLogs pinfo = new PlaceWithDrawalsLogs();
		if (page.getCondition() == null) {
			page.setCondition(pinfo);
		}
		Map map = placeWithDrawalsLogsService.HistoryRecordsManager(page);
		// page=(PageBean)map.get("page");
		return map;
	}

	/**
	 * 进入提现处理页
	 * 
	 * @param str
	 * @return
	 */
	@RequestMapping("/withdrawPaper")
	public String withdrawPaper(HttpServletRequest request, Model model) {
		int id = Integer.valueOf(request.getParameter("id"));
		PlaceWithDrawalsLogs placeWithDrawalsLogs = placeWithDrawalsLogsService.getOne(id);
		model.addAttribute("placeWithDrawalsLogs", placeWithDrawalsLogs);
		return "/admin/drp/withdrawPaper";
	}

	/**
	 * 处理提现
	 * 
	 * @param str
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/dealWithdraw")
	public Map<String, String> dealWithdrawPaper(PlaceWithDrawalsLogs placeWithDrawalsLogs) {
		ResultMsg remsg = placeWithDrawalsLogsService.dealApply(placeWithDrawalsLogs);
		HashMap<String, String> map = new HashMap<String, String>();
		if (placeWithDrawalsLogs == null) {
			return map;
		}
		PlaceWithDrawalsLogs withDrawalsLogs = placeWithDrawalsLogsService.getOne(placeWithDrawalsLogs.getId());
		if (remsg.getResultCode().equals(ResultInfo.SUCCESSCODE)) {
			map.put("result", ResultInfo.SUCCESSCODE);
			map.put("message", remsg.getMessage());

			// 返现后给用户推送微信消息
			if (placeWithDrawalsLogs.getStatus() == 2) { // 审核通过
				if (withDrawalsLogs != null && StringUtils.isNotEmpty(withDrawalsLogs.getOpenid())
						&& withDrawalsLogs.getWithDrawalsNum() > 0) {
					Member member = memberService.getMemberByUserOpenId(withDrawalsLogs.getOpenid());
				}
			} else if (placeWithDrawalsLogs.getStatus() == 3) { // 审核不通过
				if (withDrawalsLogs != null && StringUtils.isNotEmpty(withDrawalsLogs.getOpenid())
						&& withDrawalsLogs.getWithDrawalsNum() > 0) {
					try {
						Member member = memberService.getMemberByUserOpenId(withDrawalsLogs.getOpenid());
						String temp = ResultInfo.INCOMEREMINDTEMP;
						temp = temp.replaceFirst("firstValueIamberry", ResultInfo.INCOMEREJECTMESSAGE)
								.replaceFirst("accountValueIamberry",
										URLDecoder.decode(member.getUserNickname(), "UTF-8"))
								.replaceFirst("timeValueIamberry",
										DateTimeUtil.format(new Date(), NameUtils.getConfig("DATE_TIME_FORMAT")))
								.replaceFirst("typeValueIamberry", "申请提现:"
										+ new Double(withDrawalsLogs.getWithDrawalsNum() / 100.0).toString() + "元")
								.replaceFirst("remarkValueIamberry", ResultInfo.INTOSHOP);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} else {
			map.put("result", ResultInfo.ERRORCODE);
			map.put("message", NameUtils.getConfig("ERRORINFO"));
		}
		return map;
	}

	// ===============================分销收支记录管理========================================
	/**
	 * 现金记录页面
	 * 
	 * @param str
	 * @return
	 */
	@RequestMapping("/initlogs")
	public String logs() {
		return "/admin/drp/placeLogslist";
	}

	/**
	 * 初始化订单表格
	 * 
	 * @param str
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/logsTable")
	public Map orderTable(@RequestBody PageBeanPlaceLogs tmp) {
		PageBean page = new PageBean();
		page.setCondition(tmp.getCondition());
		page.setPageNumber(tmp.getPageNumber());
		page.setPageSize(tmp.getPageSize());
		PlaceLogs pLogs = new PlaceLogs();
		if (page.getCondition() == null) {
			page.setCondition(pLogs);
		}
		Map map = placeLogsService.SearchPlaceLogsPage(page);
		return map;
	}

	// =================================分销订单收入记录===================================

	/**
	 * 分销订单收入记录
	 * 
	 * @param str
	 * @return
	 */
	@RequestMapping("/initOrderlogs")
	public String initOrderlogs() {
		return "/admin/drp/orderEarningLogslist";
	}

	/**
	 * 初始化订单表格
	 * 
	 * @param str
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/orderEarningTable")
	public Map orderEarningTable(@RequestBody PageBeanEarningLogs tmp) {

		PageBean page = new PageBean();
		page.setCondition(tmp.getCondition());
		page.setPageNumber(tmp.getPageNumber());
		page.setPageSize(tmp.getPageSize());

		// Map map=placeLogsService.searchDrpRecord(page);
		Map map = rebackStaticService.getSearchIncomeDetail(page);
		return map;
	}

	/**
	 * 需要下载二维码的批量打包
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/battle2w")
	public synchronized Map battle2w(HttpServletRequest request, HttpServletResponse response) {

		Map resultmap = new HashMap<String, String>();
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
		ServletContext servletContext = webApplicationContext.getServletContext();
		String realPath = servletContext.getRealPath(ResultInfo.QRCODE_IMAGE);
		String fileName = String.valueOf(new Date().getTime());
		try {
			String name = request.getParameter("name");
			String parentName = request.getParameter("supperName");
			String userName = request.getParameter("openid");
			PlaceInfo placeInfo = new PlaceInfo();
			placeInfo.setName(name);
			placeInfo.setUserName(userName);
			placeInfo.setParentName(parentName);

			List<PlaceInfo> placeList = placeInfoService.getPlaceId(placeInfo);
			ResponseEntity<byte[]> entity = null;
			if (placeList != null && placeList.size() > 0) {
				for (PlaceInfo place : placeList) {
					if (place.getQrcodeUrl() == null || "".equals(place.getQrcodeUrl())) {
						continue;
					}
					String url = place.getQrcodeUrl();
					String qrcode = realPath + "/" + place.getId() + "qrcode.png";
					// url =
					// "http://localhost:8080/iamberry/common/images/default_qrcode.png";
					Map<String, Object> map = this.selectSuperior(String.valueOf(place.getId()));
					String placeName = "";
					String imageName = String.valueOf(place.getId());
					if (map != null) {
						placeName = (String) map.get("name");
						imageName = (String) map.get("name");
					}
					String waterMark = realPath + "/" + imageName + ".png";
					File file = new File(waterMark);
					File files = new File(realPath);
					if (!files.exists()) {
						files.mkdir();
					}
					if (!file.exists()) {
						URL httpurl = new URL(url);
						org.apache.commons.io.FileUtils.copyURLToFile(httpurl, new File(qrcode));
						this.rwFile(servletContext.getRealPath(NameUtils.getConfig("WECHAT_DEFAULT_WATERMARK")),
								realPath, imageName);
						ImageUtils.press(waterMark, qrcode, placeName, -1, 170, 320, 250);
					}
				}

				/*
				 * Task2wm tasks=new Task2wm(placeList,0,placeList.size());
				 * ForkJoinPool pool=new ForkJoinPool(); pool.execute(tasks);
				 * do{
				 * System.out.println("active Thread:"+pool.getActiveThreadCount
				 * ()); }while(!tasks.isDone()); pool.shutdown();
				 */
			}
			String zipName = getZipPath(realPath, fileName, placeList);
			resultmap.put("status", "true");
			resultmap.put("fileName", fileName);
			resultmap.put("message", "success");
		} catch (Exception e) {
			e.printStackTrace();
			resultmap.put("status", "false");
			resultmap.put("fileName", fileName);
			resultmap.put("message", "fail");

		}
		return resultmap;
	}

	/**
	 * 批量下载二维码
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/downLoadList")
	public synchronized ResponseEntity<byte[]> downLoadList(HttpServletRequest request, HttpServletResponse response) {
		String filePath = request.getServletContext().getRealPath(ResultInfo.QRCODE_IMAGE);

		String zipName = filePath + "/" + request.getParameter("zipName");
		String fileName = String.valueOf(new Date().getTime());

		ResponseEntity<byte[]> entity = null;
		// 创建HttpHeaders对象
		HttpHeaders headers = new HttpHeaders();
		// 创建一个响应吗
		HttpStatus httpStatus = HttpStatus.OK;
		// 创建对象
		try {
			headers.add("Content-Disposition",
					"attachment;filename=\"" + new String((fileName + ".zip").getBytes("UTF-8"), "ISO-8859-1") + "\"");
			// 添加一个头消息
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			entity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(zipName)), headers, httpStatus);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 手动释放资源
		return entity;
	}

	/**
	 * 压缩文件方法
	 * 
	 * @param zipPath
	 *            压缩路径
	 * @param fileName
	 *            压缩后压缩包名称
	 * @return
	 * @throws Exception
	 */
	public String getZipPath(String zipPath, String fileName, List<PlaceInfo> placeList) throws Exception {
		Map searchmap = new HashMap();
		for (PlaceInfo placeInfo : placeList) {
			searchmap.put(String.valueOf(placeInfo.getId()), placeInfo);
		}

		File sourceFile = new File(zipPath);
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		// 判断该压缩文件的目录是否存在
		if (sourceFile.exists() == false) {
			// System.out.println(">>>>>> 待压缩的文件目录:" + zipPath + " 不存在.
			// <<<<<<");
			return "";
		}
		try {
			File zipFile = new File(zipPath + "/" + fileName + ".zip");
			// 如果该压缩文件已经存在,则不再进行压缩
			if (zipFile.exists()) {
				// System.out.println(">>>>>> " + zipPath + " 目录下存在名字为:" +
				// fileName + ".zip" + " 打包文件. <<<<<<");
				return zipPath + "/" + fileName + ".zip";
			}
			File[] sourceFiles = sourceFile.listFiles();
			fos = new FileOutputStream(zipFile);
			zos = new ZipOutputStream(new BufferedOutputStream(fos));
			byte[] buffer = new byte[1024 * 10];
			if (null == sourceFiles || sourceFiles.length < 1) {
				// System.out.println(">>>>>> 待压缩的文件目录:" + zipPath + "
				// 里面不存在文件,无需压缩. <<<<<<");
				return "";
			}
			for (int i = 0; i < sourceFiles.length; i++) {

				String picName = sourceFiles[i].getName();
				// System.out.println("picName"+picName);
				String picNo = "";
				try {
					picNo = picName.substring(0, picName.indexOf("-"));
				} catch (Exception ex) {
					ex.printStackTrace();
					continue;
				}

				if (searchmap.get(picNo) == null) {
					continue;
				}
				if (!sourceFiles[i].getName().endsWith("qrcode.png")) {
					// 创建ZIP实体,并添加进压缩包
					ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
					zos.putNextEntry(zipEntry);
					// 读取待压缩的文件并写进压缩包里
					fis = new FileInputStream(sourceFiles[i]);
					bis = new BufferedInputStream(fis, 1024 * 10);
					int read = 0;
					while ((read = bis.read(buffer, 0, 1024 * 10)) != -1) {
						zos.write(buffer, 0, read);
					}
					searchmap.remove(picNo);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != bis)
					bis.close();
				if (null != zos)
					zos.close();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		return zipPath + "/" + fileName + ".zip";
	}

	/**
	 * 分销商下载二维码功能
	 * 
	 * @param request
	 * @param url
	 */
	@RequestMapping(value = "/downLoad")
	public synchronized ResponseEntity<byte[]> downLoad(HttpServletRequest request, HttpServletResponse response) {
		try {
			String openId = request.getParameter("openId");
			WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
			ServletContext servletContext = webApplicationContext.getServletContext();
			String realPath = servletContext.getRealPath(ResultInfo.QRCODE_IMAGE);
			String url = request.getParameter("url");
			String qrcode = realPath + "/" + openId + "qrcode.png";
			// url =
			// "http://localhost:8080/watero/common/images/default_qrcode.png";
			Map<String, Object> map = this.selectSuperior(openId);
			String name = "";
			String code = "";
			String imageName = openId;
			String imageCode = "";
			if (map != null) {
				name = (String) map.get("name");
				code = (String) map.get("code");
				imageName = (String) map.get("imageName");
				imageCode = (String) map.get("imageCode");
			}

			String waterMark = realPath + "/" + imageName + ".png";
			File file = new File(waterMark);
			File files = new File(realPath);
			if (!files.exists()) {
				files.mkdir();
			}
			if (!file.exists()) {
				HttpClient431Util.downloadFile(url, qrcode);
				this.rwFile(servletContext.getRealPath(NameUtils.getConfig("WECHAT_DEFAULT_WATERMARK")), realPath,
						imageName);
				ImageUtils.press(waterMark, qrcode, name, -1, 150, 320, 250);
			}
			if(code != null && !code.equals("")){
				ImageUtils.press(waterMark, qrcode, "门店激活码:"+code, -1, 180, 320, 250);
			}
			if(imageCode != null && !imageCode.equals("")){
				ImageUtils.press(waterMark, qrcode, "当前商户激活码:"+imageCode, -1, 210, 320, 250);
			}
			
			// 创建HttpHeaders对象
			HttpHeaders headers = new HttpHeaders();
			// 添加一个头消息
			headers.add("Content-Disposition",
					"attachment;filename=\"" + new String((imageName + ".png").getBytes("UTF-8"), "ISO-8859-1") + "\"");
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			// 创建一个响应吗
			HttpStatus httpStatus = HttpStatus.OK;
			// 创建对象
			ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(
					FileUtils.readFileToByteArray(new File(waterMark)), headers, httpStatus);
			// 手动释放资源
			return entity;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 查询线下上级,拼接名称
	public Map<String, Object> selectSuperior(String openId) {
		if (null == openId || "".equals(openId)) {
			return null;
		}
		String imageName = "";
		Map<String, Object> map = new HashMap<String, Object>();
		PlaceInfo palceInfo1 = new PlaceInfo();
		palceInfo1.setId(Integer.parseInt(openId));
		StringBuffer name = new StringBuffer();
		PlaceInfo placeInfo = this.placeInfoService.getOnePlaceInfoByInitcode(palceInfo1);
		if (placeInfo == null) {
			return null;
		}
		imageName = openId + "-" + placeInfo.getName();
		map.put("imageName", imageName);
		map.put("imageCode", placeInfo.getInitCode());
		PlaceRoleInfo placeRoleInfo = new PlaceRoleInfo();
		PlaceInfo parentPlace = null;
		PlaceInfo superPlace = null;
		PlaceInfo threePlace = null;
		PlaceInfo fourPlace = null;
		PlaceInfo fivePlace = null;
		// 查询自己的角色信息
		placeRoleInfo.setRoleId(placeInfo.getRoleId());
		placeRoleInfo = drpRoleInfoService.selectDrpRoleInfo(placeRoleInfo);
		if (placeInfo != null && placeRoleInfo != null && placeInfo.getUserName() != null
				&& placeRoleInfo.getRoleName() != null) {
			// System.out.println(placeInfo.getUserName()+" roleName:" +
			// placeRoleInfo.getRoleName());
			name.append(placeInfo.getUserName() + placeRoleInfo.getRoleName());
			// 查询第一级上级角色信息
			if (!"".equals(String.valueOf(placeInfo.getPlacePid()))) {
				parentPlace = this.placeInfoService.getPlaceInfoById(placeInfo.getPlacePid());
				if (null != parentPlace) {
					placeRoleInfo.setRoleId(parentPlace.getRoleId());
					placeRoleInfo = drpRoleInfoService.selectDrpRoleInfo(placeRoleInfo);
					name.insert(0, parentPlace.getUserName() + placeRoleInfo.getRoleName() + "—");
					map.put("code", parentPlace.getInitCode());
					map.put("name", name.toString());
					return map;
				}
			}
			// 查询第二级上级角色信息
			if (null != parentPlace && !"".equals(String.valueOf(parentPlace.getPlacePid()))) {
				superPlace = this.placeInfoService.getPlaceInfoById(parentPlace.getPlacePid());
				if (null != superPlace) {
					placeRoleInfo.setRoleId(superPlace.getRoleId());
					placeRoleInfo = drpRoleInfoService.selectDrpRoleInfo(placeRoleInfo);
					name.insert(0, superPlace.getUserName() + placeRoleInfo.getRoleName() + "—");
					map.put("code", superPlace.getInitCode());
					map.put("name", name.toString());
					return map;
				}
				
			}
			// 查询第三级上级角色信息
			if (null != superPlace && !"".equals(String.valueOf(superPlace.getPlacePid()))) {
				threePlace = this.placeInfoService.getPlaceInfoById(superPlace.getPlacePid());
				if (null != threePlace) {
					placeRoleInfo.setRoleId(threePlace.getRoleId());
					placeRoleInfo = drpRoleInfoService.selectDrpRoleInfo(placeRoleInfo);
					name.insert(0, threePlace.getUserName() + placeRoleInfo.getRoleName() + "—");
					map.put("code", threePlace.getInitCode());
					map.put("name", name.toString());
					return map;
				}
			
			}
			// 查询第四级上级角色信息
			if (null != threePlace && !"".equals(String.valueOf(threePlace.getPlacePid()))) {
				fourPlace = this.placeInfoService.getPlaceInfoById(threePlace.getPlacePid());
				if (null != fourPlace) {
					placeRoleInfo.setRoleId(fourPlace.getRoleId());
					placeRoleInfo = drpRoleInfoService.selectDrpRoleInfo(placeRoleInfo);
					name.insert(0, fourPlace.getUserName() + placeRoleInfo.getRoleName() + "—");
					map.put("code", fourPlace.getInitCode());
					map.put("name", name.toString());
					return map;
				}
				
			}
			// 查询第五级上级角色信息
			if (null != fourPlace && !"".equals(String.valueOf(fourPlace.getPlacePid()))) {
				fivePlace = this.placeInfoService.getPlaceInfoById(fourPlace.getPlacePid());
				if (null != fivePlace) {
					placeRoleInfo.setRoleId(fivePlace.getRoleId());
					placeRoleInfo = drpRoleInfoService.selectDrpRoleInfo(placeRoleInfo);
					name.insert(0, fivePlace.getUserName() + placeRoleInfo.getRoleName() + "—");
					map.put("code", fivePlace.getInitCode());
					map.put("name", name.toString());
					return map;
				}
			
			}
			map.put("name", name.toString());
			return map;
		}
		return null;
	}

	// 从本地获取添加水印的背景图片
	public void rwFile(String str1, String str2, String openId) {
		try {
			File f2 = new File(str2);
			File f1 = new File(str1);
			if (f2.exists()) {
				FileInputStream fis = new FileInputStream(f1);
				FileOutputStream fos = new FileOutputStream(f2 + "\\" + openId + ".png");
				byte[] b = new byte[1024];
				int i = fis.read(b);
				while (i != -1) {
					fos.write(b, 0, i);
					i = fis.read(b);
				}
				fis.close();
				fos.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 分页查询分销角色表数据
	 * 
	 * @param request
	 * @param response
	 * @param pageSize
	 * @param pageNO
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getDrpRoleList")
	public ModelAndView getDrpRoleList(HttpServletRequest request,
			@RequestParam(value = "pageSize", defaultValue = "6", required = false) Integer pageSize,
			@RequestParam(value = "pageNO", defaultValue = "1", required = false) Integer pageNO) throws Exception {
		ModelAndView mv = new ModelAndView("admin/drp/roleList");
		String text = request.getParameter("text");
		StringBuffer url = new StringBuffer("/admin/drp/getDrpRoleList?pageSize=" + pageSize);
		PlaceRoleInfo drpRoleInfo = new PlaceRoleInfo();
		if (null != text && !"".equals(text)) {
			if (!request.getMethod().equalsIgnoreCase("post")) {
				text = new String(text.getBytes("ISO-8859-1"), "UTF-8");
			}
			drpRoleInfo.setRoleName(text);
			url.append("&text=" + text);
		}
		url.append("&pageNO=");
		drpRoleInfo.getPage().setPageSize(pageSize);
		drpRoleInfo.getPage().setPageNumber(pageNO);
		drpRoleInfo.getPage().initRecordBegin();
		List<PlaceRoleInfo> drpRoleList = drpRoleInfoService.getDrpRoleList(drpRoleInfo);
		mv.addObject("text", text);
		mv.addObject("drpRoleList", drpRoleList);
		mv.addObject("pageNO", pageNO);
		mv.addObject("url", url.toString());
		mv.addObject("pageSize", drpRoleInfoService.selectDrpRoleCount(drpRoleInfo));
		return mv;
	}

	/**
	 * 进入分销角色添加页面
	 * 
	 * @param request
	 * @param drpRoleInfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addDrpRole")
	public ModelAndView addDrpRole(HttpServletRequest request) throws Exception {
		ModelAndView mv = new ModelAndView("admin/drp/addDrpRoleInfo");
		return mv;
	}

	/**
	 * 添加角色信息
	 * 
	 * @param request
	 * @param drpRoleInfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addDrpRoleInfo")
	public ModelAndView addDrpRoleInfo(HttpServletRequest request, PlaceRoleInfo drpRoleInfo) throws Exception {
		ModelAndView mv = new ModelAndView("admin/msg/msg");
		Integer num = drpRoleInfoService.addDrpRoleInfo(drpRoleInfo);
		if (num > 0) {
			mv.addObject("msgObj", new MessageDTO(true, "恭喜您,操作成功", "分销角色已添加成功,刷新即可!"));
		} else {
			mv.addObject("msgObj", new MessageDTO(false, "对不起,操作有误", "对不起,您刚才的操作流程有误,请按规定填写数据!"));
		}
		return mv;
	}

	/**
	 * 跳转到修改分销角色信息页面
	 * 
	 * @param request
	 * @param roleId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateDrpRole")
	public ModelAndView updateDrpRole(HttpServletRequest request,
			@RequestParam(value = "roleId", defaultValue = "", required = false) Integer roleId) throws Exception {
		ModelAndView mv = new ModelAndView("admin/drp/updateDrpRoleInfo");
		if ("".equals(roleId.toString())) {
			return mv;
		}
		PlaceRoleInfo drpRoleInfo = new PlaceRoleInfo();
		drpRoleInfo.setRoleId(roleId);
		drpRoleInfo = drpRoleInfoService.selectDrpRoleInfo(drpRoleInfo);
		mv.addObject("drpRoleInfo", drpRoleInfo);
		return mv;
	}

	/**
	 * 修改分销角色数据
	 * 
	 * @param request
	 * @param drpRoleInfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateDrpRoleInfo")
	public ModelAndView updateDrpRoleInfo(HttpServletRequest request, PlaceRoleInfo placeRoleInfo) throws Exception {
		ModelAndView mv = new ModelAndView("admin/msg/msg");
		if (null == placeRoleInfo.getRoleId() || "".equals(placeRoleInfo.getRoleId().toString())) {
			mv.addObject("msgObj", new MessageDTO(false, "对不起,操作有误", "对不起,您刚才的操作流程有误,请按规定填写数据!"));
			return mv;
		}
		Integer num = drpRoleInfoService.updateDrpRoleInfo(placeRoleInfo);
		if (num > 0) {
			mv.addObject("msgObj", new MessageDTO(true, "恭喜您,操作成功", "分销角色已修改成功,刷新即可!"));
		} else {
			mv.addObject("msgObj", new MessageDTO(false, "对不起,操作有误", "对不起,您刚才的操作流程有误,请按规定填写数据!"));
		}
		return mv;
	}

	/**
	 * 修改分销角色状态
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/updateDrpRoleStatus")
	public String updateDrpRoleStatus(HttpServletRequest request) throws Exception {
		String roleId = request.getParameter("roleId");
		String roleStatus = request.getParameter("roleStatus");
		if (null == roleId || "".equals(roleId)) {
			return "{\"status\":\"修改失败!\"}";
		}
		if ("1".equals(roleStatus)) {
			roleStatus = "2";
		} else if ("2".equals(roleStatus)) {
			roleStatus = "1";
		} else {
			return "{\"status\":\"修改失败!\"}";
		}
		PlaceRoleInfo placeRoleInfo = new PlaceRoleInfo();
		placeRoleInfo.setRoleId(Integer.parseInt(roleId));
		placeRoleInfo.setRoleStatus(Integer.parseInt(roleStatus));
		Integer num = drpRoleInfoService.updateDrpRoleStatus(placeRoleInfo);
		if (num > 0) {
			return "{\"status\":\"修改成功!\"}";
		} else {
			return "{\"status\":\"修改失败!\"}";
		}
	}

	/**
	 * 上传Excel 用于批量修改excel
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/upLoadExcel")
	public void upLoadExcel(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception {

		String path = request.getSession().getServletContext().getRealPath("/common/excelUpload");
		String fileName = file.getOriginalFilename();
		// System.out.println(path);
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		// 保存
		try {
			file.transferTo(targetFile);
			List<PlaceInfo> placeInfos = readExcel(path + File.separator + fileName);
			System.err.println(placeInfos);
			int i = placeInfoService.batchUpdate(placeInfos);
			targetFile.delete();
			response.getWriter().write("<script>parent.msg('导入成功!')</script>");
		} catch (Exception e) {
			response.getWriter().write("<script>parent.msg('导入失败!')</script>");
			e.printStackTrace();
		}
	}

	// 通过路径读取excel表的数据
	public List<PlaceInfo> readExcel(String pathname) {
		List<PlaceInfo> placeInfos = new ArrayList<PlaceInfo>();
		// String pathname="D:/Backup/Downloads/iamberry.xls";
		List list = new ArrayList();
		try {
			Workbook rwb = Workbook.getWorkbook(new File(pathname));
			Sheet rs = rwb.getSheet(0);// 或者rwb.getSheet("iamberry-sheet")
			int clos = rs.getColumns();// 得到所有的列
			int rows = rs.getRows();// 得到所有的行

			// System.out.println(clos+" rows:"+rows);
			for (int i = 1; i < rows; i++) {
				PlaceInfo placeInfo = new PlaceInfo();
				for (int j = 0; j < clos; j++) {
					placeInfo.setId(Integer.parseInt(rs.getCell(j, i).getContents()));
					placeInfo.setName(rs.getCell(j + 1, i).getContents());
					placeInfo.setUserName(rs.getCell(j + 2, i).getContents());
					String areaName = rs.getCell(j + 3, i).getContents();
					placeInfo.setAreaName(areaName.endsWith("") ? null : areaName);
					/*
					 * placeInfo.setHasQrcode(Integer.parseInt(rs.getCell(j+4,
					 * i).getContents()));
					 * placeInfo.setPlacePid(Integer.parseInt(rs.getCell(j+5,
					 * i).getContents()));
					 * placeInfo.setRoleId(Integer.parseInt(rs.getCell(j+6,
					 * i).getContents()));
					 */
					placeInfo.setTel(rs.getCell(j + 4, i).getContents());
					placeInfo.setAddr(rs.getCell(j + 5, i).getContents());
					placeInfo.setRemark(rs.getCell(j + 7, i).getContents());

					// System.out.println(placeInfo.toString());
					break;
				}

				placeInfos.add(placeInfo);
			}
			rwb.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return placeInfos;
	}

	
	
	/**
	 * 上传Excel 用于批量添加excel
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/addLoadExcel")
	public void addLoadExcel(@RequestParam(value = "file2", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception {

		String path = request.getSession().getServletContext().getRealPath("/common/excelUpload");
		String fileName = file.getOriginalFilename();
		// System.out.println(path);
		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		// 保存
		try {
			file.transferTo(targetFile);
			boolean msg = readExcel2(path + File.separator + fileName);
			if(msg){
				targetFile.delete();
				response.getWriter().write("<script>parent.msg('导入成功!')</script>");
			}else{
				response.getWriter().write("<script>parent.msg('导入失败!')</script>");
			}
		} catch (Exception e) {
			response.getWriter().write("<script>parent.msg('导入失败!')</script>");
			e.printStackTrace();
		}
	}
	// 通过路径读取excel表的数据
		public boolean readExcel2(String pathname) {
			List<PlaceInfo> placeInfos = new ArrayList<PlaceInfo>();
			try {
				Workbook rwb = Workbook.getWorkbook(new File(pathname));
				Sheet rs = rwb.getSheet(0);// 或者rwb.getSheet("iamberry-sheet")
				int clos = rs.getColumns();// 得到所有的列
				int rows = rs.getRows();// 得到所有的行
				String partnerId = "";//合夥人id
				Integer storeId  = 0;//門店id
				partnerId = rs.getCell(0, 0).getContents();//得到合夥人id
				for (int i = 1; i < rows; i++) {
					PlaceInfo placeInfo = new PlaceInfo();
					for (int j = 0; j < clos; j++) {
						//获取某一列所有数据
						//获取一列的第一格数据判断是否是门店或vip会员
						String isStoresMembers = rs.getCell(j, i).getContents();
						String name = rs.getCell(j+1, i).getContents();//门店名称/vip会员名称
						//如果第二格为空这表示此行无数据并不在往后取数据
						if(name  == null || name.equals("")){
							break;
						}
						String nickName = rs.getCell(j+2, i).getContents();//门店姓名/vip会员姓名
						String tel = rs.getCell(j+3, i).getContents();//门店手机号/vip会员手机号
						Integer isPerfect = Integer.valueOf(rs.getCell(j+4, i).getContents());//是否已完善信息
						String city = rs.getCell(j+5, i).getContents();//门店地址/vip会员地址
						String note = rs.getCell(j+6, i).getContents();//门店备注/vip会员备注
						//如果不为空表示为门店、反之为vip会员
						placeInfo.setName(name);
						placeInfo.setUserName(nickName);
						placeInfo.setAddr(city);
						placeInfo.setTemplateId(23);
						placeInfo.setTel(tel);
						placeInfo.setStatus(1);
						placeInfo.setCreateDate(new Date());
						placeInfo.setRemark(note);
						placeInfo.setPlaceInfoStus(isPerfect);
						if(isStoresMembers != null&& !isStoresMembers.equals("")){
							//完善门店信息
							placeInfo.setPlacePid(Integer.valueOf(partnerId));
							placeInfo.setHasQrcode(1);// 1表示没有二维码
							placeInfo.setRoleId(48);
							Map<String, Object> msgMap = addPlaceInfoDeal(placeInfo);//添加门店
							PlaceInfo Info = (PlaceInfo) msgMap.get("data");
							storeId = Info.getId();//保存门店id为全局变量 
							
						}else{//vip会员
							placeInfo.setPlacePid(storeId);//门店id
							placeInfo.setHasQrcode(2);// 2表示有二维码
							placeInfo.setRoleId(51);
							addPlaceInfoDeal(placeInfo);//添加vip会员
						}
						break;
					}
				
				}
				rwb.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return true;
		}
	/**
	 * list view
	 * 
	 * @return
	 */
	@RequestMapping("/apply/list")
	public ModelAndView list(@RequestParam(value = "pageNO", defaultValue = "1") Integer pageNO,
			@RequestParam(value = "pageSize", required = false) Integer pageSize, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("admin/drp/applyList");

		// 分页查找
		List<ApplyPlaceLogs> news = placeInfoService.selectApplyPlaceLogs(pageNO, 10);
		mv.addObject("list", news);

		// 是否已经get过pageSize了?
		if (pageSize == null) {
			pageSize = placeInfoService.getCount(10);
		}

		// 分页数据
		mv.addObject("pageNO", pageNO);
		mv.addObject("pageSize", pageSize);
		mv.addObject("url",
				new StringBuilder(StringUtils.replace(request.getRequestURI(), request.getContextPath(), ""))
						.append("?pageSize=").append(pageSize).append("&pageNO="));
		return mv;
	}

	/**
	 * 审核操作
	 * 
	 * @return
	 */
	@RequestMapping(value = "/apply/{id}/{status}", method = RequestMethod.POST)
	@ResponseBody
	public JsonBack updatePlaceInfo(@PathVariable("id") Integer id, @PathVariable("status") Integer status) {
		JsonBack back = new JsonBack();

		if (status == 2 || status == 3) {
			back.setSuccess(placeInfoService.handlerApplyLogs(id, status));
		} else {
			back.setSuccess(false);
			back.setResponseData("状态不对!");
		}

		return back;
	}
	
	
	
	/**
	 * 分页查询我要代理申请记录
	 * 
	 * @param request
	 * @param response
	 * @param pageSize
	 * @param pageNO
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/applyAgentList")
	public ModelAndView applyAgentList(HttpServletRequest request,
			@RequestParam(value = "pageSize", defaultValue = "6", required = false) Integer pageSize,
			@RequestParam(value = "pageNO", defaultValue = "1", required = false) Integer pageNO) throws Exception {
		ModelAndView mv = new ModelAndView("admin/drp/applyAgentList");
		String text = request.getParameter("text");
		StringBuffer url = new StringBuffer("/admin/drp/applyAgentList?pageSize=" + pageSize);
		ApplyUserInfo applyUserInfo = new ApplyUserInfo();
		if (null != text && !"".equals(text)) {
			if (!request.getMethod().equalsIgnoreCase("post")) {
				text = new String(text.getBytes("ISO-8859-1"), "UTF-8");
			}
			applyUserInfo.setUserName(text);
			url.append("&text=" + text);
		}
		url.append("&pageNO=");
		applyUserInfo.getPage().setPageSize(pageSize);
		applyUserInfo.getPage().setPageNumber(pageNO);
		applyUserInfo.getPage().initRecordBegin();
		List<ApplyUserInfo> applyUserList = placeInfoService.getApplyAgentList(applyUserInfo);
		mv.addObject("text", text);
		mv.addObject("applyUserList", applyUserList);
		mv.addObject("pageNO", pageNO);
		mv.addObject("url", url.toString());
		mv.addObject("pageSize", placeInfoService.getApplyAgentCount(applyUserInfo));
		return mv;
	}
}