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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

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.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.order.ProbationOrderDto;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.order.AdminOrderService;
import com.iamberry.wechat.face.qrcode.QrcodeService;
import com.iamberry.wechat.face.reback.RebackStaticService;
import com.iamberry.wechat.tools.NameUtils;
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 PlaceInfoService placeInfoService;
	@Autowired
	private QrcodeService qrcodeService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private RebackStaticService rebackStaticService;
	@Autowired
	private AdminOrderService adminOrderService;
	/**
	 * 获取二维码
	 * 
	 * @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(NameUtils.getConfig("SUCCESSINFO"));
		remsg.setStatus(true);
		return remsg;
	}

	@ResponseBody
	@RequestMapping("/showPlaceInfoCenter")
	public ResultMsg showPlaceInfoResult(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		ResultMsg msg = getSuccessResult();
		
		String openid = WechatUtils.getUserBySession(request).getUserOpenid();
		
		ShopSystemRule agencySystemRule = adminOrderService.getReluByRid(206);
		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 HashMap<String, Object>();
		if (null != openid) {
			//openid 加密
			MD5 md5=new MD5("fenxiao");
			String shareOpenid = "";
			try {
				shareOpenid = md5.encrypt(member.getUserOpenid());
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			if (agencySystemRule.getRuleNum().intValue() == placeInfo.getId()) {
				data.put("salesName", true);
			} else {
				data.put("salesName", false);
			}
			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");  //是否有二维码功能
          //获取已销售台数
            Integer salesNum  = rebackStaticService.getBeauticianAllCount(openid);
            data.put("salesNum",salesNum);  //已销售台数
            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(NameUtils.getConfig("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 = WechatUtils.getUserBySession(request).getUserOpenid();
		
		try {
			String path = request.getSession().getServletContext().getRealPath("upload\\img\\");
			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){
			return WechatUtils.getUserBySession(request).getUserOpenid();
	}
	
	/**
	 * 获取当前用户的商户信息（详情页面）
	 * 2016年10月10日
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/get_placeInfo_detail")
	public ResponseJson getPlaceInfoDetail(HttpServletRequest request){
		ResponseJson json = new ResponseJson();
		String openid = WechatUtils.getUserBySession(request).getUserOpenid();
		json = placeInfoService.selectPlaceInfoDetailByOpenId(openid);
		return json;
	}
	
	/**
	 * 查询商户下线试用订单列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/selectProbationList")
	public ResultMsg selectProbationList(HttpServletRequest request,
			@RequestParam(value= "pageSize",defaultValue= "6" ,required=false) Integer pageSize, 
			@RequestParam(value = "pageNO", defaultValue = "1",required=false) Integer pageNO) throws Exception {
		ResultMsg msg = new ResultMsg();
		ProbationOrderDto probationOrderDto = new ProbationOrderDto();
		Member member = WechatUtils.getUserBySession(request);
		//member.setUserOpenid("o-icas0W3fnu0zKAuWmR4KeAlib0");
		//通过openid查询商户信息
		PlaceInfo placeInfo = placeInfoService.getPlaceInfoByOpenId(member.getUserOpenid());
		List<ProbationOrderDto> probationList = new ArrayList<ProbationOrderDto>();
		if (placeInfo == null) {
			msg.setResultCode(ResultInfo.ERRORCODE);
			msg.setStatus(false);
			msg.setMessage("该用户不是商户");
			return msg;
		}
		probationOrderDto.setProbationOpenid(member.getUserOpenid());
		probationOrderDto.getPage().setPageNumber(pageNO);
		probationOrderDto.getPage().setPageSize(pageSize);
		probationOrderDto.getPage().initRecordBegin();
		//商户最后一层 VIP会员和金牌会员
		if (placeInfo.getRoleId() == 51 || placeInfo.getRoleId() == 52) {
			probationList = placeInfoService.selectVipProbationList(probationOrderDto);
		} else if (placeInfo.getRoleId() == 53 || placeInfo.getRoleId() == 48) {
			//钻石会员和门店
			probationList = placeInfoService.selectStoreProbationList(probationOrderDto);
		} else if (placeInfo.getRoleId() == 47) {
			//合伙人
			probationList = placeInfoService.selectPartnerProbationList(probationOrderDto);
		}
		msg.setData(probationList);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		return msg;
	}
	
	/**
	 * 查询商户下线试用订单数量
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/selectProbationNum")
	public ResultMsg selectProbationNum(HttpServletRequest request) throws Exception {
		ResultMsg msg = new ResultMsg();
		Member member = WechatUtils.getUserBySession(request);
		//member.setUserOpenid("o-icas0W3fnu0zKAuWmR4KeAlib0");
		//通过openid查询商户信息
		PlaceInfo placeInfo = placeInfoService.getPlaceInfoByOpenId(member.getUserOpenid());
		int probationNum = 0;
		if (placeInfo == null) {
			msg.setResultCode(ResultInfo.ERRORCODE);
			msg.setStatus(false);
			msg.setMessage("该用户不是商户");
			return msg;
		}
		//商户最后一层 VIP会员和金牌会员
		if (placeInfo.getRoleId() == 51 || placeInfo.getRoleId() == 52) {
			probationNum = placeInfoService.selectVipProbationNum(member.getUserOpenid());
		} else if (placeInfo.getRoleId() == 53 || placeInfo.getRoleId() == 48) {
			//钻石会员和门店
			probationNum = placeInfoService.selectStoreProbationNum(member.getUserOpenid());
		} else if (placeInfo.getRoleId() == 47) {
			//合伙人
			probationNum = placeInfoService.selectPartnerProbationNum(member.getUserOpenid());
		}
		msg.setData(probationNum);
		msg.setResultCode(ResultInfo.SUCCESSCODE);
		msg.setStatus(true);
		return msg;
	}
	
}
