package com.iamberry.wechat.handles.drp;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

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

import org.apache.commons.collections.map.HashedMap;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.iamberry.app.tool.des.MD5;
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.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.drp.PlaceWithDrawalsLogsService;
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.tools.ResponseJson;
import com.iamberry.wechat.tools.ResultInfo;

/**
 * @description 用于主页和一些公共操作的handler
 * @author 欧阳明
 * @Date 2016-04-20
 */
@Controller
@RequestMapping("/wechat/placeInfo")
public class PlaceInfoHandler {

	@Autowired
	private WechatUtils wechatUtils;
	@Autowired
	private PlaceInfoService placeInfoService;
	@Autowired
	private QrcodeService qrcodeService;
	@Autowired
	private PlaceWithDrawalsLogsService placeWithDrawalsLogsService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private RebackStaticService rebackStaticService;
	@Autowired
	private RatFWLogger logger;
	/**
	 * 获取二维码
	 * 
	 * @param openid
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/get2Wm")
	public ResultMsg get2Wm(HttpServletRequest request) throws Exception {
		ResultMsg resultMsg = getSuccessResult();
		String openid = getOpenid(request);
		if (openid == null || openid.equals("")) {
			resultMsg.setMessage(ResultInfo.paramFormatError);
			return resultMsg;
		}
		// 获取二维码
		String qrcode = qrcodeService.selectQrcodeUrlByReplaceUser(openid);

		resultMsg.setData(qrcode);

		return resultMsg;
	}
	
	// 返回处理结果
	public ResultMsg getSuccessResult() {
		ResultMsg remsg = new ResultMsg();
		remsg.setResultCode(ResultInfo.SUCCESSCODE);
		remsg.setMessage(ResultInfo.SUCCESSINFO);
		remsg.setStatus(true);
		return remsg;
	}

	@ResponseBody
	@RequestMapping("/showPlaceInfoCenter")
	public ResultMsg showPlaceInfoResult(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		ResultMsg msg = getSuccessResult();
		
		String openid = "";
		try {
			openid = wechatUtils.getUserBySession(request).getUserOpenid();
		} catch (Exception e) {
			e.printStackTrace();
//			openid="oaH_GwHQSHd2-KxQpihr_b9Y9lOc";
		}
		
		Member member = memberService.getMemberByUserOpenId(openid);
		PlaceInfo placeInfo = placeInfoService.getPlaceInfoByOpenId(openid);
	
		if(member==null){
			msg.setResultCode(ResultInfo.ERRORCODE);
			msg.setMessage(ResultInfo.lostMemberInfo);
			msg.setStatus(false);
			return msg;
		}

		Map<String, Object> data = new HashedMap();
		if (null != openid) {
			//openid 加密
			MD5 md5=new MD5("fenxiao");
			String shareOpenid = "";
			try {
				shareOpenid = md5.encrypt(member.getUserOpenid());
			} catch (Exception e) {
				e.printStackTrace();
			}
			data.put("shareOpenid", shareOpenid);
		    data.put("totalMoney",placeInfo.getAmount() ); //可提现金额
			
			//logger.info("=============="+member.toString()+"=="+member.getUserIncome());
			data.put("nickName", URLDecoder.decode(member.getUserNickname()==null?"无昵称":member.getUserNickname(), "UTF-8")); //设置昵称
            data.put("headImg", member.getUserHead());   //头像
            String roleName=placeInfo.getRoleName();
            String areaName=placeInfo.getAreaName();
            
            if(roleName!=null && roleName.equals("省代") && areaName!=null && !areaName.equals("") ){
            	data.put("role",roleName+" ("+placeInfo.getAreaName()+")");  //用户名
            }else{
               data.put("role",roleName);  //角色名称，身份
            }
            data.put("userName",placeInfo.getUserName());  //用户名
            data.put("wm2", placeInfo.getHasQrcode()==1?"false":"true");  //是否有二维码功能
          
            int mon=0;
            try{
            	mon=rebackStaticService.getUnIncomeMoney(openid);
            }catch(Exception ex){
            	ex.printStackTrace();
            	mon=0;
            }

            data.put("unIncomeMoney", mon);
			msg.setData(data);
		} else {
			msg.setMessage(ResultInfo.ERRORINFO);
			msg.setStatus(false);
		}
		return msg;
	}

	@ResponseBody
	@RequestMapping(value="/sendImg2Share",method = RequestMethod.POST)
	public ResultMsg sendImg2Share(HttpServletRequest request
			,@RequestParam(value = "file", required = false) MultipartFile file,HttpServletResponse response) throws UnsupportedEncodingException{
		ResultMsg msg = getSuccessResult();
		
		String openid="";
		try {
			openid = wechatUtils.getUserBySession(request).getUserOpenid();
		} catch (Exception e) {
			e.printStackTrace();
//			openid="oaH_GwHQSHd2-KxQpihr_b9Y9lOc";
		}
		
		try {
			String path = request.getSession().getServletContext().getRealPath(
					"upload\\img\\");
			String fileName = file.getOriginalFilename();
			String saveFileName = openid+".png";
			File targetFile = new File(path, saveFileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			
			file.transferTo(targetFile);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		msg.setMessage("测试成功！");
		return msg;
	}
	
	//获取openid
	public String getOpenid(HttpServletRequest request){
		try {
			return wechatUtils.getUserBySession(request).getUserOpenid();
		} catch (Exception e) {
			e.printStackTrace();
			return "oaH_GwHQSHd2-KxQpihr_b9Y9lOc";
		}
	}
	
	/**
	 * 获取当前用户的商户信息（详情页面）
	 * 2016年10月10日
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/get_placeInfo_detail")
	public ResponseJson getPlaceInfoDetail(HttpServletRequest request){
		ResponseJson json = new ResponseJson();
		String openid = "";
		try {
			openid = wechatUtils.getUserBySession(request).getUserOpenid();
		} catch (Exception e) {
			json.setReturnCode(402);
			json.addResponseKeyValue("登录超时，请刷新!");
			return json;
		}
		json = placeInfoService.selectPlaceInfoDetailByOpenId(openid);
		return json;
	}
	
}
