package com.xxfc.platform.summit.biz;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.constant.RestCode;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
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.ActivityBmMapper;;
import com.xxfc.platform.summit.pojo.ActivityBmQuery;
import com.xxfc.platform.summit.vo.MeepoActivityVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class ActivityBmBiz extends BaseBiz<ActivityBmMapper, ActivityBm> {

    @Autowired
    private RedisTemplate summbitRedisTemplate;

    @Autowired
    private  UserBiz userBiz;

    @Autowired
    private  ActivityBiz activityBiz;


    @Autowired
    private  MeepoUserQdBiz meepoUserQdBiz;



  //用户报名
    public  ObjectRestResponse userBmOrQd(ActivityBm activityBm,Integer meepoUserId)throws  Exception{

        if (activityBm==null||meepoUserId==null||meepoUserId==0){
            log.info("-----activityBm==="+activityBm+"-------meepoUserId==="+meepoUserId+"-----为空");
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"参数不能为空");
        }
        Integer activityId=activityBm.getActivityId();
        Integer  bmStatus=activityBm.getBmStatus()==null?0:activityBm.getBmStatus();
        Integer  qdStatus=activityBm.getQdStatus()==null?0:activityBm.getQdStatus();
        log.info("-----activityBm==="+JSONObject.toJSONString(activityBm)+"-------meepoUserId==="+meepoUserId+"----activityId==="+activityId+"---bmStatus=="+bmStatus+"---qdStatus=="+qdStatus);
        if (activityId==null||activityId==0){
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"活动不存在");
        }
        ActivityBm activityBm1=checkUserBm(meepoUserId,activityId);
        int isQd=0;
        if (activityBm1!=null){
            if (bmStatus==1&&activityBm1.getBmStatus()==1){
                log.info("----用户已报名---meepoUserId==="+meepoUserId);
                return ObjectRestResponse.createFailedResult(ResultCode.EXIST_CODE,"用户已报名");
            }else if (qdStatus==1){
                if (activityBm1.getQdStatus()==1){
                    log.info("----用户已签到---meepoUserId==="+meepoUserId);
                    return ObjectRestResponse.createFailedResult(ResultCode.EXIST_CODE,"用户已签到");
                }
                isQd=1;
            }
            activityBm.setId(activityBm1.getId());
            updateSelectiveById(activityBm);
        }else {
            activityBm.setMeepoUserId(meepoUserId);
            insertSelective(activityBm);
            if (qdStatus==1){
                isQd=1;
            }
        }
        if (isQd==1){
            meepoUserQdBiz.addUserQd(meepoUserId);
        }
        log.info("-----用户报名成功----bmId===="+activityBm.getId());
        return  ObjectRestResponse.succ();
    }

   //获取小程序峰会活动
    public List<MeepoActivityVo> getMeepoActivitys(Integer rId){
        return  mapper.getMeepoActivitys(rId);
    }

    //获取缓存内容
    public  ActivityBm userInfo(String redisLockKey)throws  Exception{
        if (StringUtils.isBlank(redisLockKey)){
            log.info("-----redisLockKey==="+redisLockKey+"-----为空");
            return null;
        }
        ActivityBm bm =new ActivityBm();
        String json = summbitRedisTemplate.opsForValue().get(redisLockKey) == null ? "" : summbitRedisTemplate.opsForValue().get(redisLockKey).toString();
        log.info("userBm接口，获取redis中的报名信息：" + json);
        if (StringUtils.isBlank(json)){
            return  null;
        }
        JSONObject jsonObject= JSONObject.parseObject(json);
        BeanUtils.copyProperties(jsonObject,bm);
        return  bm;
    }

    public  ActivityBm checkUserBm(Integer meepoUserId,Integer activityId ){
        Example example =new Example(ActivityBm.class);
        example.createCriteria().andEqualTo("meepoUserId",meepoUserId).andEqualTo("activityId",activityId).andEqualTo("isDel",0);
        List<ActivityBm> list=mapper.selectByExample(example);
        if (list.size()>0){
            return  list.get(0);
        }
        return null;
    }


    //用户报名/签到操作
    public  JSONObject  userBmOrQdByKey(String key,Integer activityId, HttpServletRequest request){
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("isbm",0);
        jsonObject.put("isqd",0);
        jsonObject.put("value","");
        try {
            User user=userBiz.getSession(request);
            //是否登录
            log.info("-----userBmByKey---activityId==="+activityId);
            if (user==null){
                log.info("-----userBmByKey---用户未登录----");
                ActivityBm activityBm= userInfo(key);
                if (activityBm!=null){
                    log.info("-----userBmByKey---key已存在----");
                    jsonObject.put("value",activityBm);
                    // 获取到缓存的验证码后要先清空缓存对应键的值
                    summbitRedisTemplate.delete(key);
                }
            }else {
                Integer userId=user.getId();
                log.info("-----userBmByKey---用户登录--userId==="+userId);
                ActivityBm activityBm= userInfo(key);
                if (activityBm==null){
                    log.info("-----userBmByKey---key不存在判断用户是否报名/签到----");
                    ActivityBm activityBm1=checkUserBm(userId,activityId);
                    if (activityBm1!=null){
                        log.info("-----userBmByKey---key不存在用户已报名/签到----");
                        jsonObject.put("isbm",activityBm1.getBmStatus());
                        jsonObject.put("isqd",activityBm1.getQdStatus());
                    }
                }else {
                    log.info("-----userBmByKey---key已存在去报名/签到----");
                    ObjectRestResponse restResponse=userBmOrQd(activityBm,userId);
                    if (restResponse.getStatus()==RestCode.SUCCESS.getStatus()){
                        log.info("-----userBmByKey---key已存在去报名/签到----报名/签到成功");
                        if (activityBm.getBmStatus()==1){
                            jsonObject.put("isbm",1);
                            jsonObject.put("bm_status",1);
                        }else if (activityBm.getQdStatus()==1){
                            jsonObject.put("isqd",1);
                            jsonObject.put("qd_status",1);
                        }
                    }else {
                        log.info("-----userBmByKey---key已存在去报名/签到----报名/签到失败");
                        if (activityBm.getBmStatus()==1){
                            jsonObject.put("bm_status",2);
                        }else if (activityBm.getQdStatus()==1){
                            jsonObject.put("qd_status",2);
                        }
                    }
                    summbitRedisTemplate.delete(key);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return  jsonObject;
    }

    //获取峰会活动详情
    public ObjectRestResponse  getActivityById(Integer activityId,String key,HttpServletRequest request){
        if (activityId==0||activityId==null){
            return  ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE,"参数为空");
        }
        Example   example=new Example(Activity.class);
        example.createCriteria().andEqualTo("id",activityId).andEqualTo("isDel",0);
        List<Activity> list=activityBiz.selectByExample(example);
        if (list.size()==0){
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"活动不存在");
        }
        Activity activity=list.get(0);
        if (activity.getIsShow()==null||activity.getIsShow()==0){
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"活动已下架");
        }
        if (activity.getIsPublish()==null||activity.getIsPublish()==0){
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE,"活动未发布");
        }
        Integer status=activity.getStatus();
        if (status==null){
            status=0;
        }
        if (status==0){
            Long nowTime=System.currentTimeMillis();
            Long startTime=activity.getStartTime();
            Long endTime=activity.getEndTime();
            if (nowTime<startTime){
                status=1;
            }else if (nowTime>=startTime&&nowTime<endTime){
                status=2;
            }else {
                status=3;
            }
            activity.setStatus(status);
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("activity",activity);
        JSONObject userBm=userBmOrQdByKey(key,activityId,request);
        jsonObject.put("bmInfo",userBm);
        return  ObjectRestResponse.succ(jsonObject);
    }


    public PageInfo<ActivityBm> list(ActivityBmQuery query) {
         Example exa = new Example(ActivityBm.class);
        Example.Criteria criteria = exa.createCriteria();
        if (StringUtils.isNotBlank(query.getInviter())) {
            criteria.andEqualTo("inviter",String.format("%%%s%%",query.getInviter().trim()));
        }

        if (StringUtils.isNotBlank(query.getName())) {
            criteria.andLike("name",String.format("%%%s%%",query.getName().trim()));
        }

        if (query.getQdStatus()!=null) {
            criteria.andEqualTo("qdStatus",query.getQdStatus());
        }
        criteria.andEqualTo("isDel",0).andEqualTo("activityId",query.getActivityId());
        exa.orderBy("crtTime").desc();
        PageHelper.startPage(query.getPage(),query.getLimit());
        List<ActivityBm> activityBms = mapper.selectByExample(exa);
        return PageInfo.of(activityBms);
    }

    public ActivityBm userBm(ActivityBm activityBm, Integer id) {
        return null;
    }
}
