package com.iamberry.wechat.handles.mothMovable;

import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.WechatUtils;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.mothMovable.MothMovable;
import com.iamberry.wechat.core.entity.stati.AcceStatistics;
import com.iamberry.wechat.face.home.HomeService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.mothMovable.MothMovableService;
import com.iamberry.wechat.face.stati.AcceStatisticsService;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.WeixinUtil;
import com.iamberry.wechat.sendMsg.SendMessageUtil;
import net.sf.json.JSONObject;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * xm
 * 母亲节活动
 * @Date 2019
 */
@Controller
@RequestMapping("/wechat/moth_movable")
public class MothMovableHandler {
    private final static String ENCODE = "utf-8";

    @Autowired
    private MothMovableService mothMovableService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private HomeService homeService;
    @Autowired
    private AcceStatisticsService acceStatisticsService;
    @Autowired
    private SendMessageUtil sendMessageUtil;

    /**
     * 获取二维码
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/save_movable", method = RequestMethod.POST)
    public ResultMsg saveMvable( HttpServletResponse response,HttpServletRequest request,MothMovable mothMovable) throws Exception {
        long x = System.currentTimeMillis();
        ResultMsg msg = new ResultMsg();

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

        try{
            if(member.getUserHead() == null || "".equals(member.getUserHead())){
                JSONObject jsonObject = WeixinUtil.getUserInfo(member.getUserOpenid());
                String nickname = jsonObject.getString("nickname");
                String headimgurl = jsonObject.getString("headimgurl");
                try {
                    nickname = URLEncoder.encode(jsonObject.getString("nickname"), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    nickname = "";
                }
                member.setUserHead(headimgurl);
                member.setUserNickname(nickname);
                if(nickname != null && !"".equals(nickname)){
                    member.setUserStatus(2);
                }
                homeService.updateWechatMemberInfoByByOpenid(member);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        if(member.getUserStatus() != 2){
            return new ResultMsg(false,  ResultMsg.ERROR, "请关注“Watero水时代”公众号！",null);
        }

        if(mothMovable.getMothMovaBackType() == null){
            return new ResultMsg(false,  ResultMsg.ERROR, "未选择背景图片",null);
        }

        if(mothMovable.getMothMovaText() == null || "".equals(mothMovable.getMothMovaText())){
            return new ResultMsg(false,  ResultMsg.ERROR, "未输入文字",null);
        }

        String newString = new String(mothMovable.getMothMovaText().getBytes("GB2312"), "ISO-8859-1");
        if(newString.length() > 112){
            return new ResultMsg(false,  ResultMsg.ERROR, "文字超出限制，最大支持56个文字",null);
        }

        MothMovable mothM = new MothMovable();
        mothM.setMothMovaOpenId(member.getUserOpenid());
        List<MothMovable>mothMovableList = mothMovableService.getMothMovableList(mothM);
        if(mothMovableList != null && mothMovableList.size() > 0 ){
            return new ResultMsg(false,  ResultMsg.ERROR, "已经生成过活动图片了，请刷新页面",null);
        }

        String realPath = request.getSession().getServletContext().getRealPath("/");

        mothMovable.setMothMovaOpenId(member.getUserOpenid());
        mothMovable.setMothMovaHead(member.getUserHead());

        String name = "";
        if(member.getUserNickname() != null && !"".equals(member.getUserNickname())){
            name = java.net.URLDecoder.decode( member.getUserNickname(), ENCODE);
            name = name.trim();
        }
        mothMovable.setMothMovaName(name);
        try {
            Integer falg = mothMovableService.save(mothMovable,realPath);
        }catch (Exception e){
            return new ResultMsg(false,  ResultMsg.ERROR, e.getMessage(),null);
        }

        //判断时候领取的优惠券，有领取了优惠券，就推送信息
        if(mothMovable.getCouponItemId() != null && !"".equals(mothMovable.getCouponItemId())){
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, 7);  //有效期7天
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dataStr = "有效期至"+ formatter.format(calendar.getTime());
            try{
                sendMessageUtil.servicePush(
                        "亲爱的用户，恭喜您已领取WaterO滤芯T1/T2抵用券",
                        "WaterO滤芯T1/T2抵用券",
                        dataStr,
                        "可在“服务中心—会员中心—券包”查看，请尽快使用。",
                        member.getUserOpenid(),
                        ResultInfo.SERVICE_PUSH_URL);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        msg.setResultCode(ResultInfo.SUCCESSCODE);
        msg.setData(mothMovable);
        msg.setStatus(true);
        long y = System.currentTimeMillis();
        System.out.println("响应时间："+ (y-x));
        return msg;
    }

    /**
     * 获取自己生成图片
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/get_moth", method = RequestMethod.POST)
    public ResultMsg getMoth( HttpServletResponse response,HttpServletRequest request) throws Exception {
        ResultMsg msg = new ResultMsg();

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

        //进入活动的UV埋点
        AcceStatistics acceStatistics = new AcceStatistics();
        acceStatistics.setAcceStatOpenId(member.getUserOpenid());
        acceStatistics.setAcceStatType(1);
        acceStatistics.setJudgeTime(new Date());
        Integer count = acceStatisticsService.getAcceStatiCount(acceStatistics);
        if(count <= 0){  //添加UV访问
            Integer flag = acceStatisticsService.save(acceStatistics);

            JSONObject jsonObject = WeixinUtil.getUserInfo(member.getUserOpenid());
            String sex = jsonObject.getString("sex");//值为1时是男性，值为2时是女性，值为0时是未知
            String city = jsonObject.getString("city");
            String country = jsonObject.getString("country");
            String province = jsonObject.getString("province");
            String nickname = jsonObject.getString("nickname");
            String headimgurl = jsonObject.getString("headimgurl");
            try {
                nickname = URLEncoder.encode(jsonObject.getString("nickname"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                nickname = "";
            }

            Member mb = new Member();
            //赋值&更新会员数据
            if (member != null && member.getUserId() != null) {
                mb.setUserId(member.getUserId());
                mb.setUserOpenid(member.getUserOpenid());
                mb.setUserNickname(nickname);
                mb.setUserSex(Integer.parseInt(sex));
                mb.setUserAddr(country+"-"+province+"-"+city);
                mb.setUserHead(headimgurl);
                //userIsBought 暂存旧的关注状态
                mb.setUserIsBought(member.getUserStatus() == null ? 1 : member.getUserStatus());
                mb.setUserStatus(2); // 已关注
                homeService.updateWechatMemberInfoByByOpenid(mb);
            }
        }

        MothMovable mothMovable = new MothMovable();
        mothMovable.setMothMovaOpenId(member.getUserOpenid());
        List<MothMovable>  mothMovableList = mothMovableService.getMothMovableList(mothMovable);
        if(mothMovableList == null || mothMovableList.size() < 1){  //未参与活动
            msg = new ResultMsg(false,  ResultMsg.ERROR, "未参与活动，请参与活动！",null);
            msg.setData(member);
            return msg;
        }
        mothMovable = mothMovableList.get(0);
        msg.setData(mothMovable);
        msg.setResultCode(ResultInfo.SUCCESSCODE);
        msg.setStatus(true);
        return msg;
    }

}
