package com.xxfc.platform.summit.biz;


import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.summit.entity.Activity;
import com.xxfc.platform.summit.entity.ActivityBm;
import com.xxfc.platform.summit.entity.User;
import com.xxfc.platform.summit.mapper.UserMapper;
import com.xxfc.platform.summit.service.WeixinService;
import com.xxfc.platform.summit.vo.MeepoActivityVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.mockito.internal.util.collections.Sets;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * @author Administrator
 */
@Service
@Slf4j
public class UserBiz extends BaseBiz<UserMapper, User> {

    @Autowired
    private  ActivityBiz activityBiz;

    @Autowired
    private  ActivityBmBiz activityBmBiz;

    @Autowired
    WeixinService weixinService;

    @Autowired
    UserBiz userBiz;

    public static final String frontSessionKey = "frontWeixKey";




    public Integer  addMeepoUser(User user,Integer activityId){
        Integer userId=0;
        log.info("-----activityId===="+activityId);
        if (user==null|| StringUtils.isBlank(user.getOpenId())||activityId==null||activityId==0){
            log.info("-----参数为空----");
            return  userId;
        }
        Activity activity=activityBiz.selectById(activityId);
        if (activity==null){
            log.info("-----活动不存在----");
            return  userId;
        }
        Integer rId=activity.getRId();
        if (rId==null||rId==0){
            log.info("-----没设置小程序抽奖活动id----");
            return  userId;
        }
        List<MeepoActivityVo> list=activityBmBiz.getMeepoActivitys(rId);
        if (list.size()==0){
            log.info("-----小程序抽奖活动id不存在----");
            return  userId;
        }
        MeepoActivityVo meepoActivityVo=list.get(0);
        Integer weId=meepoActivityVo.getWeId();
        String openId=user.getOpenId();
        Example example=new Example(User.class);
        example.createCriteria().andEqualTo("weId",weId).andEqualTo("rId",rId).andEqualTo("openId",openId);
        List<User> uses=mapper.selectByExample(example);
        if (uses.size()>0){
            userId=uses.get(0).getId();
            user.setId(userId);
        }else {
            user.setWeId(weId);
            user.setRId(rId);
            insertSelective(user);
            userId=user.getId();
        }
        return userId;
    }

    public  void  authUser(String code,String key, HttpServletRequest request){
        if (StringUtils.isBlank(code)){
            log.info("----code为空---");
            throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("code为空"));
        }
        String openid = null;
        String access_token = null;
        try {
            JSONObject jsonData = weixinService.getAccessToken(code);
            openid = jsonData.getString("openid");
            access_token = jsonData.getString("access_token");
            String refresh_token = jsonData.getString("refresh_token");
            log.info("-----微信回调userInfo---openid=="+openid+"----access_token==="+access_token);
            //验证access_token是否失效
            JSONObject validateData = weixinService.getValidateData(access_token, openid);
            if (!"0".equals(validateData.getString("errcode"))){
                //刷新access_token
                JSONObject refreshData= weixinService.getRefreshToken(refresh_token);
                access_token = refreshData.getString("access_token");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.info("网络异常===" + e.getMessage());
            throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("网络异常"));
        }
        try {
            // 获取微信用户基本信息
            JSONObject userinfo_json = weixinService.getUserInfo(access_token,openid);
            if (userinfo_json == null || StringUtils.isNotBlank(userinfo_json.getString("errcode"))) {
                log.info("调用微信用户基本信息接口失败");
                throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("调用微信用户基本信息接口失败"));
            }
            log.info("微信用户基本信息---user===" +userinfo_json.toJSONString());
            ActivityBm activityBm=activityBmBiz.userInfo(key);
            if (activityBm==null){
                log.info("redis的报名信息为空");
                throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("redis的报名信息为空"));
            }
            Integer activityId=activityBm.getActivityId();
            if (activityId==null||activityId==0){
                log.info("redis的报名信息activityId---为空");
                throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("redis的报名信息activityId---为空"));
            }
            User userInfo=new User();
            String nickName = userinfo_json.getString("nickname");
            String headimgurl = userinfo_json.getString("headimgurl");
            String sex = userinfo_json.getString("sex");
            if (StringUtils.isBlank(sex)){
                sex="0";
            }
            userInfo.setOpenId(openid);
            userInfo.setNickName(nickName);
            userInfo.setAvatar(headimgurl);
            userInfo.setSex(sex);
            Integer userId=userBiz.addMeepoUser(userInfo,activityId);
            log.info("小程序用户---userId===" +userId);
            if (userId==null||userId==0){
                log.info("小程序用户---userId---为空");
                throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("小程序用户---userId---为空"));
            }
            String encode = Base64.encode(JSONObject.toJSONString(userInfo));
            HttpSession session = request.getSession();
            session.removeAttribute(frontSessionKey);
            session.setAttribute(frontSessionKey, encode);
        } catch (Exception e) {
            log.info("调用微信用户基本信息接口失败", e);
            throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("调用微信用户基本信息接口失败"));
        }
    }

    //获取缓存
    public  User getSession(HttpServletRequest request){
        try {
            HttpSession session = request.getSession();
            String frontSessionValue1 = (String) session.getAttribute(frontSessionKey);
            if (StringUtils.isBlank(frontSessionValue1)) {
                return  null;
            }
            JSONObject jsonObject=JSONObject.parseObject(frontSessionValue1);
            User user=new User();
            BeanUtils.copyProperties(jsonObject,user);
            return user;
        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }

    }

    public  User getUserInfo(HttpServletRequest request,Integer activityId){
        User user=getSession(request);
        if (user!=null){
           Integer userId=addMeepoUser(user,activityId);
           if (userId==null||userId==0){
               return  null;
           }
           return  user;
        }
        return  null;
    }





}
