package com.xxfc.platform.summit.biz;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.google.common.collect.Lists;
import com.xxfc.platform.summit.entity.Activity;
import com.xxfc.platform.summit.entity.ActivityBm;
import com.xxfc.platform.summit.entity.ActivityTemporary;
import com.xxfc.platform.summit.entity.User;
import com.xxfc.platform.summit.mapper.ActivityBmMapper;;
import com.xxfc.platform.summit.pojo.ActivityBmExcel;
import com.xxfc.platform.summit.pojo.ActivityBmQuery;
import com.xxfc.platform.summit.vo.MeepoActivityVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.lang3.StringUtils;
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.LinkedList;
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;

    @Autowired
    private ActivityTemporaryBiz activityTemporaryBiz;



    //用户报名
    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;
        }
        return  JSON.parseObject(json,ActivityBm.class);
    }

    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()!=null&&activityBm.getBmStatus()==1){
                            jsonObject.put("isbm",1);
                            jsonObject.put("bmStatus",1);
                        }else if (activityBm.getQdStatus()!=null&&activityBm.getQdStatus()==1){
                            jsonObject.put("isqd",1);
                            jsonObject.put("qdStatus",1);
                        }
                    }else if (restResponse.getStatus()==ResultCode.EXIST_CODE){
                        log.info("-----userBmByKey---key已存在已报名/签到----");
                        if (activityBm.getBmStatus()!=null&&activityBm.getBmStatus()==1){
                            jsonObject.put("isbm",1);
                        }else if (activityBm.getQdStatus()!=null&&activityBm.getQdStatus()==1){
                            jsonObject.put("isqd",1);
                        }
                        jsonObject.put("value",activityBm);
                    } else {
                        log.info("-----userBmByKey---key已存在去报名/签到----报名/签到失败");
                        if (activityBm.getBmStatus()!=null&&activityBm.getBmStatus()==1){
                            jsonObject.put("bmStatus",2);
                        }else if (activityBm.getQdStatus()!=null&&activityBm.getQdStatus()==1){
                            jsonObject.put("qdStatus",2);
                        }
                        jsonObject.put("value",activityBm);
                    }
                    summbitRedisTemplate.delete(key);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return  jsonObject;
    }

    //获取峰会活动详情
    public ObjectRestResponse  getActivityById(Integer activityId,String key,HttpServletRequest request){
        log.info("--getActivityById---activityId==="+activityId+"----key===="+key);
        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())) {
            String format = String.format("%%%s%%", query.getInviter().trim());
            criteria.andLike("inviter", format);
        }

        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 void userBm(ActivityTemporary activityTemporary) throws Exception {
        activityTemporaryBiz.addModifyIfPresent(activityTemporary);
    }

    public List<ActivityBmExcel> excel(ActivityBmQuery query) throws Exception {
        PageInfo<ActivityBm> pageInfo = list(query);
        LinkedList<ActivityBmExcel> activityBmExcels = Lists.newLinkedList();
        List<ActivityBm> list = pageInfo.getList();
        for (ActivityBm activityBm : list) {
            ActivityBmExcel activityBmExcel = new ActivityBmExcel();
            BeanUtilsBean.getInstance().copyProperties(activityBmExcel,activityBm);
            activityBmExcels.add(activityBmExcel);
        }

        return activityBmExcels;
    }


    public ObjectRestResponse checkSubscribe(HttpServletRequest request){
        int subscribe=-1;
        User user=userBiz.getSession(request);
        if (user!=null&&StringUtils.isNotBlank(user.getOpenId())){
            subscribe=userBiz.checkSubscribe(user.getOpenId());
        }
        return  ObjectRestResponse.succ(subscribe);
    }

    //获取用户信息
    public  ObjectRestResponse getUserInfo(Integer parentId,HttpServletRequest request){
        JSONObject obj =new JSONObject();
        obj.put("pId",0);
        obj.put("name","");
        User user=userBiz.getSession(request);
        if (user!=null){
            obj.put("pId",user.getId());
            obj.put("name",user.getNickName());
        }
        if (parentId!=null&&parentId>0){
            user=userBiz.selectById(parentId);
            if (user!=null){
                obj.put("name",user.getNickName());
            }
        }
        return  ObjectRestResponse.succ(obj);
    }

}
