package com.iamberry.wechat.handles.thanksgiving;

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.coupon.CouponType;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.thanksgiving.ThanksGiving;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.coupon.CouponTypeService;
import com.iamberry.wechat.face.home.HomeService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.order.CodeService;
import com.iamberry.wechat.face.thanksgiving.ThanksGivingService;
import com.iamberry.wechat.service.ImberryConfig;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.payUtil.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 感恩活动
 */
@Controller
@RequestMapping("/wechat/tanksgiv")
public class ThanksGivingHandler {

    private Logger logger = LoggerFactory.getLogger(ThanksGivingHandler.class);

    @Autowired
    private CodeService codeService;
    @Autowired
    private ThanksGivingService thanksGivingService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private HomeService homeService;

    /**
     * 免费送滤芯
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/free_collection", method = RequestMethod.GET)
    public void freeCollection(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher(NameUtils.getConfig("WECHAT_GO_FREE_COLLECTION")).forward(request, response);return;
    }
    /**
     * 免费领取滤芯
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/receiving_filter", method = RequestMethod.GET)
    public void receivingFilter(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher(NameUtils.getConfig("WECHAT_GO_RECEIVING_FILTER_CARTRIDGE")).forward(request, response);return;
    }


    /**
     * 发送验证码
     * 2016年4月21日
     * @author 穆再兴
     * @return
     */
    @ResponseBody
    @RequestMapping("/attention_veri")
    public ResultMsg attentionVeri(HttpServletRequest requeste){
        ResultMsg rm = new ResultMsg();
        Member member =  WechatUtils.getUserBySession(requeste);

        member = memberService.getMemberByUserOpenId(member.getUserOpenid());
        if(member == null){
            // 创建新的用户
            member = new Member();
            member.setUserOpenid(member.getUserOpenid());
            member.setUserSex(0);
            member.setUserStatus(1);
            int flag = homeService.insertMemberInfo(member);
            if (flag < 1) {
                return new ResultMsg(false, ResultMsg.ERROR, "请先关注“Watero水时代”公众号，并联系客服添加用户!",null);
            }
        }
        rm.setMessage(ResultMsg.SUCCESS);
        rm.setStatus(true);
        return rm;
    }


    /**
     * 发送验证码
     * 2016年4月21日
     * @author 穆再兴
     * @return
     */
    @ResponseBody
    @RequestMapping("/send_veri")
    public ResultMsg sendPhone(HttpServletRequest request,String phone){
        ResultMsg rm = new ResultMsg();
        Member member =  WechatUtils.getUserBySession(request);

        if(phone.length() != 11){
            rm.setMessage(ResultMsg.ERROR);
            rm.setMessage("电话号码错误!");
            logger.info("openid="+member.getUserOpenid()+"phone："+phone+"==电话号码错误!");
            System.out.println("openid="+member.getUserOpenid()+"phone："+phone+"==电话号码错误!");
            return rm;
        }

        member = memberService.getMemberByUserOpenId(member.getUserOpenid());
        if(member == null){
            // 创建新的用户
            member = new Member();
            member.setUserOpenid(member.getUserOpenid());
            member.setUserSex(0);
            member.setUserStatus(1);
            int flag = homeService.insertMemberInfo(member);
            if (flag < 1) {
                logger.info("openid="+member.getUserOpenid()+"phone："+phone+"==请先关注“Watero水时代”公众号，并联系客服添加用户!");
                System.out.println("openid="+member.getUserOpenid()+"phone："+phone+"==请先关注“Watero水时代”公众号，并联系客服添加用户!");
                return new ResultMsg(false, ResultMsg.ERROR, "请先关注“Watero水时代”公众号，并联系客服添加用户!",null);
            }
        }

        ThanksGiving thanksGiving = new ThanksGiving();
        thanksGiving.setThanksGivingPhone(phone);
        List<ThanksGiving> thanksGivingList = thanksGivingService.getThanksGivingList(thanksGiving);
        if(thanksGivingList == null || thanksGivingList.size() < 1){
            logger.info("openid="+member.getUserOpenid()+"phone："+phone+"=您的手机号码未录入到老客户行列，暂时无法领取，详情请联系客服人员!");
            System.out.println("openid="+member.getUserOpenid()+"phone："+phone+"==您的手机号码未录入到老客户行列，暂时无法领取，详情请联系客服人员!");
            return new ResultMsg(false, ResultMsg.ERROR, "您的手机号码未录入到老客户行列，暂时无法领取，详情请联系客服人员!",null);
        }

        //获取验证码
        String num = RandomUtil.getRandom();
        //使用request对象的getSession()获取session，如果session不存在则创建一个
        HttpSession session = request.getSession();
        String text = MessageFormat.format(ImberryConfig.PROBATION_VERIFICATION_CODE, num);
        String result = codeService.sendOtherCMS(phone, text);

        //将数据存储到session中
        session.setAttribute("verification_code",num );
        session.setAttribute("verification_tel",phone );
        session.setAttribute("verification_date",new Date());

        rm.setMessage(ResultMsg.SUCCESS);
        rm.setStatus(true);
        return rm;
    }

    /**
     * 领取优惠券
     * 2016年4月21日
     * @author 穆再兴
     * @return
     */
    @ResponseBody
    @RequestMapping("/receive_coupon")
    public ResultMsg receiveCoupon(HttpServletRequest request,String phone,String code){
        ResultMsg rm = new ResultMsg();
        Member member =  WechatUtils.getUserBySession(request);
        member = memberService.getMemberByUserOpenId(member.getUserOpenid());
        if(member == null){
            // 创建新的用户
            member = new Member();
            member.setUserOpenid(member.getUserOpenid());
            member.setUserSex(0);
            member.setUserStatus(1);
            int flag = homeService.insertMemberInfo(member);
            if (flag < 1) {
                logger.info("openid="+member.getUserOpenid()+"phone："+phone+"=请先关注“Watero水时代”公众号，并联系客服添加用户!");
                return new ResultMsg(false, ResultMsg.ERROR, "请先关注“Watero水时代”公众号，并联系客服添加用户!",null);
            }
        }
        //判断验证码
        //使用request对象的getSession()获取session，如果session不存在则创建一个
        HttpSession session = request.getSession();
        String verificationTel = (String) session.getAttribute("verification_tel");
        String verificationCode = (String) session.getAttribute("verification_code");
        Date verificationDate = (Date) session.getAttribute("verification_date");
        if(verificationTel == null || verificationCode == null || verificationDate == null){
            logger.info("openid="+member.getUserOpenid()+"phone："+phone+"=领取出错，请重新获取验证码");
            return new ResultMsg(false, ResultMsg.ERROR, "领取出错，请重新获取验证码!",null);
        }
        if(phone.length() != 11 && phone.equals(verificationTel)){
            rm.setMessage(ResultMsg.ERROR);
            rm.setMessage("电话号码错误!");
            return rm;
        }
        if(code == null || "".equals(code)){
            return new ResultMsg(false, ResultMsg.ERROR, "验证码为空!",null);
        }
        Calendar nowTime = Calendar.getInstance();
        nowTime.setTime(verificationDate);
        nowTime.add(Calendar.MINUTE, 5);
        Date verData = nowTime.getTime();
        if(!verificationCode.equals(code)){
            logger.info("openid="+member.getUserOpenid()+"phone："+phone+"=验证码不正确，请重新输入");
            return new ResultMsg(false,  ResultMsg.ERROR, "验证码不正确，请重新输入!",null);
        }
        if((verData.getTime() < System.currentTimeMillis())){
            return new ResultMsg(false,  ResultMsg.ERROR, "验证码已失效，请重新获取!",null);
        }

        ThanksGiving thanksGiving = new ThanksGiving();
        thanksGiving.setThanksGivingPhone(phone);
        List<ThanksGiving> thanksGivingList = thanksGivingService.getThanksGivingList(thanksGiving);
        if(thanksGivingList == null){
            logger.info("openid="+member.getUserOpenid()+"phone："+phone+"=您的手机号码未录入到老客户行列，暂时无法领取，详情请联系客服人员");
            return new ResultMsg(false, ResultMsg.ERROR, "您的手机号码未录入到老客户行列，暂时无法领取，详情请联系客服人员!",null);
        }
        thanksGiving = thanksGivingList.get(0);
        if(thanksGiving.getThanksGivingStatus() != 1 ){
            logger.info("openid="+member.getUserOpenid()+"phone："+phone+"=领取失败，该电话号码已领取优惠券!==="+thanksGiving.getThanksGivingStatus());
            return new ResultMsg(false, ResultMsg.ERROR, "领取失败，该电话号码已领取优惠券!",null);
        }

        ThanksGiving tg = new ThanksGiving();
        tg.setThanksGivingPhone(phone);
        tg.setThanksGivingId(thanksGivingList.get(0).getThanksGivingId());
        tg.setThanksGivingOpenId(member.getUserOpenid());
        Integer flag = 0;
        try{
            flag = thanksGivingService.update(tg);
        }catch (Exception e){
            e.printStackTrace();
            return new ResultMsg(false, ResultMsg.ERROR, e.getMessage(),null);
        }
        if(flag < 1){
            logger.info("openid="+member.getUserOpenid()+"phone："+phone+"=领取失败，请重新领取!");
            return new ResultMsg(false, ResultMsg.ERROR, "领取失败，请重新领取!",null);
        }

        //领取成功 验证码失效，
        session.setAttribute("verification_code",null );
        session.setAttribute("verification_tel",null );
        session.setAttribute("verification_date",null );

        return new ResultMsg(true, ResultMsg.SUCCESS, "领取成功!",null);
    }

}
