package com.iamberry.wechat.handles.activity;

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.activity.Activity;
import com.iamberry.wechat.core.entity.activity.ActivityHelp;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.wx.QRCJson;
import com.iamberry.wechat.face.activity.ActivityHelpService;
import com.iamberry.wechat.face.activity.ActivityService;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.file.FileUtils;
import com.iamberry.wechat.tools.*;
import com.iamberry.wechat.utils.DownloadWXCodeUtil;
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.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author wxm
 * Class Description: 618活动
 */
@Controller
@RequestMapping("/wechat/activity")
public class ActivityHandler {


	private static String ditupath = "";

	@Autowired
	private MemberService memberService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private ActivityHelpService activityHelpService;
	@Autowired
	private PosterNumUtils posterNumUtils;
	@Autowired
	private SystemService systemService;
	@Autowired
	private CouponItemService couponItemService;
	@Autowired
	private SendMessageUtil sendMessageUtil;
	@Autowired
	private RatFWLogger logger;


	/**
	 * 进入活动页面判断该用户是否可以参加
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/to_activity")
	public ResultMsg toActivity(HttpServletRequest req){
		ResultMsg rm = ResultMsg.getSuccess();

		Member member = WechatUtils.getUserBySession(req);
		member = memberService.getMemberByUserOpenId(member.getUserOpenid());

		/*不能参与*/
		if(member.getUserIdentity() == 2 ){	//1:会员   2:微信用户
			rm = ResultMsg.getError();
			rm.setMessage("此活动仅限soodo上朵会员参与，请购买并注册后参与");
			rm.addData("member",member);
			return rm;
		}

		/*未参与过的*/
		Activity activity = new Activity();
		activity.setUserOpenId(member.getUserOpenid());
		List<Activity> activityList = activityService.getActivityList(activity);
		if(activityList == null || activityList.size() < 1){
			rm.addData("status",-1);
			rm.addData("member",member);
			rm.addData("msg","未参与，请点击立即参与");
			return rm;
		}

		activity = activityList.get(0);
		ActivityHelp activityHelp = new ActivityHelp();
		activityHelp.setActivityId(activity.getActivityId());
		List<ActivityHelp> activityHelpList = activityHelpService.getActivityHelpList(activityHelp);

		//状态：1：助力中 2：助力成功 3：已领取优惠券 4：取消
		if(activity.getActivityStatus() == 1){
			/*参与中的*/
			rm.addData("status",1);
			rm.addData("msg","正在助力中");
			rm.addData("member",member);
			rm.addData("activity",activity);
			rm.addData("activityHelpList",activityHelpList);
			return rm;
		}else if(activity.getActivityStatus() == 2){
			/*已成功*/
			rm.addData("status",2);
			rm.addData("msg","助力成功");
			rm.addData("member",member);
			rm.addData("activity",activity);
			rm.addData("activityHelpList",activityHelpList);
			return rm;
		}else if(activity.getActivityStatus() == 3){
			/*已领取*/
			rm.addData("status",3);
			rm.addData("msg","已领取优惠券");
			rm.addData("member",member);
			rm.addData("activity",activity);
			rm.addData("activityHelpList",activityHelpList);
			return rm;
		}else{
			rm = ResultMsg.getError();
			rm.setMessage("查询失败，请重试");
			return rm;
		}
	}

	/**
	 * 参与活动
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/participate_activity")
	public synchronized ResultMsg getColorPatterns(HttpServletRequest req){
		ResultMsg rm = ResultMsg.getSuccess();

		Member member = WechatUtils.getUserBySession(req);
		member = memberService.getMemberByUserOpenId(member.getUserOpenid());

		/*不能参与*/
		if(member.getUserIdentity() == 2 ){	//1:会员   2:微信用户
			rm = ResultMsg.getError();
			rm.setMessage("此活动仅限soodo上朵会员参与，请购买并注册后参与");
			return rm;
		}

		/*未参与过的*/
		Activity activity = new Activity();
		activity.setUserOpenId(member.getUserOpenid());
		List<Activity> activityList = activityService.getActivityList(activity);
		if(activityList == null || activityList.size() < 1){
			String dataStaing = new SimpleDateFormat("yyyyMMdd").format(new Date());
			String codePath = posterNumUtils.IMG_PATH + dataStaing + "/";
			String filePath = req.getSession().getServletContext().getRealPath("/") + codePath ;

			ditupath =  req.getSession().getServletContext().getRealPath("/") + PosterNumUtils.OLD_IMG_PATH;

			String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
			// 生成文件名
			String codeName = name + "Code.png";
			String headName = name + "Head.png";
			String imgName = name  + ".png";

			long start = new Date().getTime();
			boolean flag = generatePoster(member,filePath,codeName,imgName,headName);
			long end = new Date().getTime();
			System.out.println("生成时间为："+ (end-start));

			if(!flag){
				rm = ResultMsg.getError();
				rm.setMessage("生成图片失败");
				return rm;
			}

			String codeImgPath = codePath + codeName;
			String imgPath = codePath + imgName;

			String element = systemService.selectOneShopRuleById(257).getRuleDesc();
			Integer num = Integer.valueOf(element);
			if(num == 0){
				num =10;
			}
			activity.setActivityAllHelp(num);
			activity.setActivityCodeImg(codeImgPath);
			activity.setActivityImg(imgPath);
			activity.setActivityStatus(1);
			List<Activity> acList = activityService.getActivityList(activity);
			Integer f = 0;
			if(acList==null || acList.size() < 1 ){
				f = activityService.save(activity);
				try {
					sendMessageUtil.participateInSuccess(
							ResultInfo.ACTIVITY_SUCCESS,
							ResultInfo.HELP_NAME,
							ResultInfo.ACTIVITY_DATE,
							ResultInfo.SOODO_NAME,
							ResultInfo.ACTIVITY_REM,
							ResultInfo.ACTIVITY_USER_REM,
							member.getUserOpenid(),
							ResultInfo.help_url
					);
				} catch (Exception e) {
					logger.info("============助力成功信息发送失败============");
					e.printStackTrace();
				}
			}
			if(f < 1){
				return rm;
			}else{
				rm = ResultMsg.getSuccess();
				rm.addData("imgPath",imgPath);
				return rm;
			}
		}else{
			rm = ResultMsg.getError();
			rm.setMessage("已参与助力活动");
			return rm;
		}
	}

	/**
	 * 获取活动信息
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/get_activity")
	public ResultMsg getActivity(HttpServletRequest req){
		ResultMsg rm = ResultMsg.getSuccess();

		Member member = WechatUtils.getUserBySession(req);
		member = memberService.getMemberByUserOpenId(member.getUserOpenid());

		/*未参与过的*/
		Activity activity = new Activity();
		activity.setUserOpenId(member.getUserOpenid());
		List<Activity> activityList = activityService.getActivityList(activity);
		if(activityList != null && activityList.size() >  0){
			rm.addData("activity",activityList.get(0));
			return rm;
		}else{
			rm = ResultMsg.getError();
			rm.setMessage("未参与活动");
			return rm;
		}
	}


	/**
	 * 生成海报
	 * @param member
	 * @param path 路径
	 * @param codeName 二维码名称
	 * @param imgName 图片名称
	 * @param headName 头像名称
	 * @return
	 */
	public boolean generatePoster(Member member,String path,String codeName,String imgName,String headName){
		File imgfile = new File(path); //全路径
		if (!imgfile.exists()){
			imgfile.mkdirs();
		}
		String name = member.getUserNickname();
		if(name == null){
			name = "";
		}

		//生成机器二维码
		String json = String.format(NameUtils.QR_SCENE_STR, 2592000, ResultInfo.barCodeActivity + member.getUserOpenid());
		QRCJson qrc = WeixinUtil.createQrcode(json);
		try {
			/*下载二维码*/
			DownloadWXCodeUtil.downloadByNIO2(qrc.getUrl(),codeName,path,PosterNumUtils.CODE_WIDTH,PosterNumUtils.CODE_HEIGHT,false);
			DownloadWXCodeUtil.downloadByNIO2(member.getUserHead(),headName,path,PosterNumUtils.HEAD_WIDTH,PosterNumUtils.HEAD_HEIGHT,false);

			/*海报位置*/
			String newImg = path+imgName;
			/*二维码位置*/
			String codeImg = path + codeName;
			/*头像位置*/
			String headImg = path + headName;

			/*复制海报*/ //common/images/activity/ditu.jpg
			FileUtils.copyFile(ditupath,newImg);

			  /*添加文字*/
			ImageUtils.pressPost(newImg,
					headImg,PosterNumUtils.HEAD_X,PosterNumUtils.HEAD_Y,
					codeImg,PosterNumUtils.CODE_X,PosterNumUtils.CODE_Y,
					name,PosterNumUtils.TEXT_X,PosterNumUtils.TEXT_Y,new Color(129,129,129),PosterNumUtils.TEXT_FONT_SIZE
			);
			/*添加文字*/
//			ImageUtils.pressImage(newImg,headImg,PosterNumUtils.HEAD_X,PosterNumUtils.HEAD_Y,1);
//			ImageUtils.pressImage(newImg,codeImg,PosterNumUtils.CODE_X,PosterNumUtils.CODE_Y,1);
//			ImageUtils.pressText(newImg,name,PosterNumUtils.TEXT_X,PosterNumUtils.TEXT_Y,Color.black,PosterNumUtils.TEXT_FONT_SIZE);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}



	/**
	 * 领取优惠券
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/receive_coupon")
	public ResultMsg receiveCoupon(HttpServletRequest req){
		ResultMsg rm = ResultMsg.getSuccess();

		Member member = WechatUtils.getUserBySession(req);
		member = memberService.getMemberByUserOpenId(member.getUserOpenid());

		/*不能参与*/
		if(member.getUserIdentity() == 2 ){	//1:会员   2:微信用户
			rm = ResultMsg.getError();
			rm.setMessage("此活动仅限soodo上朵会员参与，请购买并注册后参与");
			return rm;
		}

		/*未参与过的*/
		Activity activity = new Activity();
		activity.setUserOpenId(member.getUserOpenid());
		List<Activity> activityList = activityService.getActivityList(activity);

		if(activityList != null && activityList.size() > 0){
			activity = activityList.get(0);
			if(activity.getActivityAlreadyHelp() >= activity.getActivityAllHelp() && activity.getActivityStatus()==2 ){
				activityService.update(activity);
				rm.setMessage("领取优惠券成功");
				return rm;
			}else{
				rm = ResultMsg.getError();
				rm.setMessage("领取失败");
				return rm;
			}
		}else{
			rm = ResultMsg.getError();
			rm.setMessage("领取失败");
			return rm;
		}
	}





}
