package com.iamberry.wechat.handles.member;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
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 sun.misc.BASE64Decoder;

import com.iamberry.app.tool.des.MD5;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.coupon.CouponItemDto;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.member.ShareInfo;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.member.ShareInfoService;
import com.iamberry.wechat.face.qrcode.QrcodeService;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.StrUtils;
import com.iamberry.wechat.tools.TextFilterUtil;


/**
 * 分享链接 Controller
 * create date 2016年5月27日
 * @author 穆再兴
 *
 */
@Controller
@RequestMapping("/wechat/share")
public class ShareInfoHandler {
	@Autowired
	private WechatUtils wechatUtils;
	@Autowired
	private MemberService memberService;			//会员service
	@Autowired
	public ShareInfoService shareInfoService;
	@Autowired
	public QrcodeService qrcodeService; 
	@Autowired
	public PlaceInfoService  placeInfoService;
	@Autowired
	private SystemService  systemService;
	@Autowired
	private TextFilterUtil textFilterUtil;
	@Autowired
	private CouponItemService couponItemService;
	
	/**
	 * 添加一个分享信息
	 * create date 2016年5月27日
	 * @author 穆再兴
	 * @param shareInfo
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping("/add")
	public ResultMsg addShareInfo(HttpServletRequest req) throws IOException{
		ResultMsg rm = new ResultMsg();
		Member member = null;
		/*member = new Member();
		member.setUserId(9558);
		member.setUserOpenid("o3dG7wViuhImN5I0w6N0upIUVw_0");
		member=memberService.getMemberByUserOpenId("o3dG7wViuhImN5I0w6N0upIUVw_0");*/
		try {
			member = wechatUtils.getUserBySession(req);
			if(member == null){
				rm.setMessage(ResultInfo.loginOutError);
				rm.setStatus(false);
				rm.setResultCode(ResultInfo.ERRORCODE);
				rm.setMessage(ResultInfo.ERRORINFO);
				return rm;
			}
			member=memberService.getMemberByUserOpenId(member.getUserOpenid());
			//if(member == null){ member = new Member();}
		} catch (Exception e) {
			e.printStackTrace();
			rm.setMessage(ResultInfo.loginOutError);
			rm.setStatus(false);
			rm.setResultCode(ResultInfo.ERRORCODE);
			rm.setMessage(ResultInfo.ERRORINFO);
			return rm;
		}
		
		//取到前台传过来的 base64图片 并创建要存放在项目中的路径
		/*WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();    
        ServletContext servletContext = webApplicationContext.getServletContext(); 
        String realPath = servletContext.getRealPath("/");
		String imgFilePath = realPath + ResultInfo.imagePath;
		try {
			isExitsPath(imgFilePath);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}*/
		
		//创建分享对象 并存入数据库
		/*String postParams = StrUtils.getPostParamsStr(req);		//data:image/png;base64,iVBORw0
		String[] shareImgUrlArr = org.apache.commons.lang3.StringUtils.split(postParams, ",");
		ShareInfo shareInfo = new ShareInfo();
		if(shareImgUrlArr != null && shareImgUrlArr.length > 0){
			String suffixName = shareImgUrlArr[0].split(";")[0].split("/")[1];
			String shareImgUrl = shareImgUrlArr[1];
			String fileName = getFileName(member.getUserOpenid(),suffixName);
			boolean flag = generateImage(shareImgUrl, imgFilePath + "/" + fileName);
			String imgUrl = "";
			if(flag){
				imgUrl = ResultInfo.imagePath + "/" + fileName;
			}else{
				imgUrl = ResultInfo.defautImagePath;
			}
			shareInfo.setShareImgUrl(imgUrl);
		}
		String message = req.getQueryString();		//获取分享内容
		if(StringUtils.isNotEmpty(message) && message.indexOf("=") > 0){
			shareInfo.setShareMessage(message.split("=")[1]);
		}*/
		
		ShareInfo shareInfo = new ShareInfo();
		String message=req.getParameter("message");
		
		if(message!=null && !message.trim().equals("")){
			//过滤敏感的词库
			textFilterUtil.readSensitiveWords();
			List<String> list=textFilterUtil.checkSensitiveWord(message);
			if(list.size()>0){
				rm.setStatus(false);
				rm.setResultCode(ResultInfo.SUCCESSCODE);
				rm.setMessage("您好，评价内容被检测到有敏感字词，请更换！");
			   //rm.setData(textFilterUtil.checkAndReplaceSensitiveWord(message));
				return rm;
			}
		}else{
			String contentId=req.getParameter("contentId");
			  switch(contentId) {
		        case "shareOne":
		        	message=ResultInfo.shareOne;
		            break;
		        case "shareTwo":
		        	message=ResultInfo.shareTwo;
		            break;
		        case "shareThree":
		            message=ResultInfo.shareThree;
		            break;
		        default:
//System.out.println("default");
		            rm.setStatus(false);
					rm.setResultCode(ResultInfo.SUCCESSCODE);
					rm.setMessage(ResultInfo.ERRORINFO);
				   //rm.setData(textFilterUtil.checkAndReplaceSensitiveWord(message));
					return rm;
		        }
		}
		
		shareInfo.setShareMessage(message);
		String imgUrl=req.getParameter("imgUrl");
		shareInfo.setShareImgUrl(imgUrl);
		shareInfo.setShareUserOpenid(member.getUserOpenid());
		shareInfo.setShareUserType(member.getUserIdentity());
		shareInfo.setCreateDate(new Date());
		int i = shareInfoService.addShareInfo(shareInfo);
		
		HashMap<String,Object> map =new HashMap<String,Object>();
		map.put("shareId", i);
		
		//openid 加密
		MD5 md5=new MD5("fenxiang");
		String openid=null;
		try {
			openid = md5.encrypt(member.getUserOpenid());
		} catch (Exception e) {
			e.printStackTrace();
//System.out.println("openid加密异常");
			rm.setStatus(false);
			rm.setResultCode(ResultInfo.ERRORCODE);
			rm.setMessage(ResultInfo.ERRORINFO);
			return rm;
		}
		
		map.put("openid", openid);
		if(i > 0){
			rm.setStatus(true);
			rm.setResultCode(ResultInfo.SUCCESSCODE);
			rm.setMessage(ResultInfo.SUCCESSINFO);
			rm.setData(map);
		}else{
			rm.setStatus(false);
			rm.setResultCode(ResultInfo.ERRORCODE);
			rm.setMessage(ResultInfo.ERRORINFO);
		}
		return rm;
	}
	
	/**
	 * 获取 file 的文件名
	 * create date 2016年6月1日
	 * @author 穆再兴
	 * @param realPath
	 * @param openid
	 * @return
	 */
	private String getFileName(String openid,String suffixName){
		long time = new Date().getTime();
		Long timeStr = new Long(time);
		return openid + timeStr + "." + suffixName;
	}
	
	/**
	 * 判断路径是否存在 不存在则创建
	 * create date 2016年6月1日
	 * @author 穆再兴
	 * @param path
	 * @return
	 * @throws InterruptedException
	 */
	public boolean isExitsPath(String path)throws InterruptedException{
		String [] paths=path.split("/");
		StringBuffer fullPath=new StringBuffer();
		for (int i = 0; i < paths.length; i++) {
			fullPath.append(paths[i]).append("/");
			File file=new File(fullPath.toString());
			if(!file.exists()){
				file.mkdir();
//System.out.println("创建目录为："+fullPath.toString());
			}
		}
		File file=new File(fullPath.toString());//目录全路径
		if (!file.exists()) {
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 对字节数组字符串进行Base64解码生成图片 并存入对应的路径
	 * create date 2016年6月1日
	 * @author 穆再兴
	 * @param imgStr Base64字符串
	 * @param imgFilePath 存入的路径
	 * @return
	 */
	private boolean generateImage(String imgStr, String imgFilePath) {  
		if (imgStr == null) {return false;}// 图像数据为空
		BASE64Decoder decoder = new BASE64Decoder();  
		try {
			// Base64解码  
			byte[] bytes = decoder.decodeBuffer(imgStr);  
			for (int i = 0; i < bytes.length; ++i) {  
				if (bytes[i] < 0) {// 调整异常数据  
					bytes[i] += 256;  
				}  
			}  
			// 生成图片  
			FileUtils.writeByteArrayToFile(new File(imgFilePath), bytes);
			return true;  
		} catch (Exception e) {
			e.printStackTrace();
			return false;  
		}  
	}  
	
	/**
	 * 分享链接绑定关系	<微代理>
	 * create date 2016年6月1日
	 * @author 穆再兴
	 * @return
	 */
	@RequestMapping("/toShare")
	@ResponseBody
	public ResultMsg getShareInfo(HttpServletRequest req, 
			@RequestParam(value="openid",defaultValue= "", required=false)String openid,
			@RequestParam(value="shareId",defaultValue= "", required=false)String shareId){
		ResultMsg rm = new ResultMsg();
		if(StringUtils.isEmpty(openid)){
			rm.setStatus(false);
			rm.setResultCode(ResultInfo.ERRORCODE);
			rm.setMessage(ResultInfo.ERRORINFO);
			return rm;
		}
		
		//String orginOpenid="o3dG7wVF9LSHZY7zHgnm6_-HrKjU";
		/*String orginOpenid="";
		try {
			orginOpenid= wechatUtils.getUserBySession(req).getUserOpenid();
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		
		//openid 解密
		MD5 md5=new MD5("fenxiang");
		try {
			openid = md5.decrypt(openid);
		} catch (Exception e) {
			e.printStackTrace();
//System.out.println("openid加密异常");
			rm.setStatus(false);
			rm.setResultCode(ResultInfo.ERRORCODE);
			rm.setMessage(ResultInfo.ERRORINFO);
			return rm;
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		
		//当前用户信息
		Member member = null;
		try {
			member = wechatUtils.getUserBySession(req);
			//member=memberService.getMemberByUserOpenId("o3dG7wRH6xsHwWrRIg9xb9O89PWo");
		} catch (Exception e) {
			e.printStackTrace();
			rm.setStatus(false);
			rm.setResultCode(ResultInfo.ERRORCODE);
			rm.setMessage(ResultInfo.ERRORINFO);
			return rm;
		}
		Member member1 = memberService.getMemberByUserOpenId(member.getUserOpenid());
		/*if(member1 == null){
			map.put("member", member);
		}else{
			map.put("member", member1);
		}*/
		
		//判断分享人和查看分享人是不是同一人
		String orginOpenid=member.getUserOpenid();
		if(!orginOpenid.equals(openid)){
			map.put("isShow", "true");	
		}else{
			map.put("isShow", "false");
		}
		Integer couponId=systemService.selectOneShopRuleById(105).getRuleNum().intValue();
		CouponItemDto couponItemDto=new CouponItemDto();
		couponItemDto.setCouponId(couponId);
		couponItemDto.setUseropenid(orginOpenid);
		Integer countNo=couponItemService.getCouponItemCount(couponItemDto);
		if(countNo!=null && countNo>0){
			map.put("hasGet", "true");
		}else{
			map.put("hasGet", "false");
		}
		
		//分享人信息
		Member shareMember = memberService.getMemberByUserOpenId(openid);
		map.put("shareMember", shareMember);
		ShareInfo info = null;
		if(StringUtils.isNotEmpty(shareId)){
			info = shareInfoService.getShareInfoById(Integer.parseInt(shareId));
		}
		map.put("shareInfo", info);
//		PlaceInfo placeInfo = placeInfoService.getPlaceInfoByOpenId(openid);
//		绑定关系
//		if(!openid.equals(member.getUserOpenid())){
//			if(placeInfo == null){
//				qrcodeService.bulidUser(member.getUserOpenid(), openid, 1);
//			}else{
//				qrcodeService.bulidUser(member.getUserOpenid(), placeInfo.getId(), 2);
//			}
//			memberService.updateUserFlagByOpenId(member.getUserOpenid());		// 绑定用户关系
//		}
		
		map.put("couponId",couponId);
		rm.setData(map);
		rm.setStatus(true);
		rm.setResultCode(ResultInfo.SUCCESSCODE);
		rm.setMessage(ResultInfo.SUCCESSINFO);
		return rm;
	}
}
