package com.iamberry.wechat.handles.binding;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

import org.apache.commons.io.FileUtils;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.bindingApp.BindingMac;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.relationship.DealerRelation;
import com.iamberry.wechat.face.bindingapp.BindingMacService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.relationship.DealerRelationService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;

/**
 * @description 用户app绑定微信商城的微信用户
 * @author 欧阳明
 * @date  2016-06-08
 */
@Controller
@RequestMapping("/wechat/qrcode")
public class BindingAppHandler {

	@Autowired
	private WechatUtils wechatUtils;
	@Autowired
	private RatFWLogger logger;
	
	@Autowired
	private BindingMacService bindingMacMapper;
	@Autowired
	private MemberService  memberService;
	@Autowired
	private DealerRelationService dealerRelationService;
	
	/**
	 * 
	 * @param request
	 * @param macId  请求的mac码
	 * @return 
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/{macId}")
	public void getMACDownLoad(@PathVariable String macId, HttpServletResponse response,HttpServletRequest requestion) throws Exception{
		
		try {
			requestion.getRequestDispatcher(NameUtils.BINDINGDOWNLOD).forward(requestion,response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
		
		
	}
	
	/**
	 * 
	 * @param request
	 * @param macId  请求的mac码
	 * @return 
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/binding")
	public ResultMsg bingdingMac(HttpServletResponse response,HttpServletRequest request) throws Exception{
		
		ResultMsg rm=getSuccessResult();
		String macId=request.getParameter("macId");
		String openid=getOpenid(request);
		
		if(macId.equals("0000000000001606120000")){
			 rm.setStatus(false);
			 return rm;
		}
		
		Pattern pattern = Pattern.compile("^[0-9a-zA-Z-]{22,28}$");
		Matcher matcher = pattern.matcher(macId);
		if(!matcher.matches()){
			rm.setMessage("机器码无效，请确认是否是真实有效的机器码");
			return rm;
		}
		
		if(macId==null || macId.equals("")){
			rm.setMessage("机器码丢失，请重新扫描");
			return rm;
		}
		if(openid.equals("false")){
		   rm.setMessage("若需绑定app与微信端的信息，请通过微信端扫码，本页面可供下载！");
		   return rm;
		}
		
		Member member=memberService.getMemberByUserOpenId(openid);
		//System.out.println(member==null?"没有会员信息":"有会员信息");
		if(member==null){
		  rm.setMessage("请先关注爱贝源，再绑定关系");
		  return rm;
		}
		Date date=new Date();
		BindingMac bindingMac=new BindingMac();
		bindingMac.setCreateDate(date);
		bindingMac.setUpdateDate(date);
		bindingMac.setMacId(macId);
		bindingMac.setOpenid(openid);
		if(member.getUserResType()==3 && member.getUserDealers()>0){
			DealerRelation dealerRelation = dealerRelationService.getDealerRelationById(member.getUserDealers());
		   
			int drpId=0;
			switch(dealerRelation.getDealerCount()){
			  case 1:  
				  drpId=dealerRelation.getDealerFirst();
				  break;
			  case 2:  
				  drpId=dealerRelation.getDealerSecond();
				  break;
			  case 3:  
				  drpId=dealerRelation.getDealerThird();
				  break;
			  case 4:  
				  drpId=dealerRelation.getDealerFourth();
				  break;
			  case 5:  
				  drpId=dealerRelation.getDealerFifth();
				  break;
			  case 6:  
				  drpId=dealerRelation.getDealerSixth();
				  break;
			}
			bindingMac.setDrpId(drpId);
		}
		
		
		int num=bindingMacMapper.testExist(macId);
		if(num>0){
			rm.setMessage("关系已经绑定，若需要重新绑定，请联系公众号客服");
			return rm;
		}
		
		num=bindingMacMapper.insert(bindingMac);
		if(num>0){
			rm.setMessage("设备绑定成功！");
		}else{
			rm.setMessage("设备绑定失败！");
		}

		return rm;
	}
	
	/**
	 * App下载
	 * @param request
	 * @param url
	 */
	@RequestMapping(value="/downLoad")
	public synchronized ResponseEntity<byte[]>  downLoad(HttpServletRequest request,HttpServletResponse response) {
		
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContext servletContext = webApplicationContext.getServletContext();
        String path1="/common/downLoad/iamberry_release.apk";
        String name="bibimeng.apk";
        String realPath = servletContext.getRealPath(path1);
        
        try{
			//创建HttpHeaders对象
			HttpHeaders headers = new HttpHeaders();
			//添加一个头消息
			headers.add("Content-Disposition", "attachment;filename=\"" + new String((name).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(realPath)), headers, httpStatus);
			//手动释放资源
			return entity;
		}catch(Exception e) {
			e.printStackTrace();
		}
        return null;
	
	}
	
	//获取openid
	public String getOpenid(HttpServletRequest request){
		try {
			return wechatUtils.getUserBySession(request).getUserOpenid();
		} catch (Exception e) {
			//e.printStackTrace();
			System.out.println("无法获取openid，可能是其他浏览器打开！");
			return "false";
		}
	}
	
	//返回处理结果
	 public ResultMsg getSuccessResult(){
		ResultMsg remsg=new ResultMsg();
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setMessage(ResultInfo.SUCCESSINFO);
		remsg.setStatus(true);
		return remsg;
	 }
}
