package com.ssj.service.conch.conch.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.award.dto.VipIntegralDto;
import com.ssj.bean.conch.conch.domain.IntegralDetail;
import com.ssj.bean.weixin.libmy.domain.LibVip;
import com.ssj.dao.conch.conch.dao.IntegralDetailDao;
import com.ssj.dao.sys.award.dao.AwardQueryDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.RedisUtil;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.weixin.util.Collections3;
import com.ssj.service.conch.conch.service.HomeworkRankingService;
import com.ssj.service.conch.conch.service.IntegralDetailService;
import com.ssj.service.conch.conch.vo.SignVO;
import com.ssj.service.weixin.library.service.ILibVipService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author sh
 * @className IntegralDetailServiceImpl
 * @description 积分明细
 * @date 2020/6/2
 */
@Service
@Transactional
public class IntegralDetailServiceImpl extends BaseServiceImpl<IntegralDetail,String> implements IntegralDetailService {

    @Autowired
    private IntegralDetailDao dao;

    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private HomeworkRankingService rankingService;
    @Autowired
    private AwardQueryDao queryDao;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ILibVipService vipService;


    @Override
    public PagingAndSortingRepository<IntegralDetail, String> getDao() {
        return dao;
    }

    @Override
    public int findTodaySignData(String vipId) {
        int count = dao.findTodaySignData(vipId);
        return count==0?2:1;
    }

    @Override
    public ResponseEntity signToday(String vipId) throws Exception{
        ResponseEntity responseEntity = new ResponseEntity();
        //查询今天是否有签到
        //没签到，进行签到操作
        //查询连续签到天数
        String signData = tokenManager.getString("sign_"+vipId);
        int continueDays = 1;
        String today = DateHelper.getUserDate("yyyy-MM-dd");
        Boolean isSign = false;
        if(StringUtils.isEmpty(signData)){
            SignVO vo = new SignVO(today,1);
            tokenManager.set("sign_"+vipId,vo);
            isSign = true;
        }else{
            JSONObject json = JSONObject.parseObject(signData);
            SignVO vo = JSON.toJavaObject(json,SignVO.class);
            String signDate = vo.getSignDate();
            int signDays = vo.getDays();
            int days = DateHelper.daysOfTwo(DateHelper.parseDate(signDate,"yyyy-MM-dd"),new Date());
            //今天已经签到
            if(days == 0){
                continueDays = signDays;
            }else{
                if(days==1){
                    if(signDays>29){
                        continueDays = signDays%30 +1;
                    }else{
                        continueDays = signDays+1;
                    }
                }
                isSign = true;
                SignVO vo2 = new SignVO(today,continueDays);
                tokenManager.set("sign_"+vipId,vo2);
            }
        }
        if(isSign){
            rankingService.saveRankIntegral(vipId,getIntegral(continueDays),3,"");
        }

        Map<String,Object> data = new HashMap<>();
        data.put("signDays",continueDays);
        data.put("list",initSignData(continueDays));
        return responseEntity.success(data,"累计打卡"+continueDays+"天，积分+"+getIntegral(continueDays));
    }

    @Override
    public int findThisWeekShare(String vipId, String beginTime,String subject) {
        return dao.findThisWeekShare(vipId,beginTime,subject);
    }

    @Override
    public int findThisMonthShare(String vipId, String month) {

        return dao.findThisMonthShare(vipId, month);
    }
    @Override
    public int findPrizeShare(String vipId, String detailCategory) {
        return dao.findPrizeShare(vipId,detailCategory);
    }

    @Override
    public Page<VipIntegralDto> userIntegralList(Map<String, Object> params, Pageable pageable) {
        return queryDao.userIntegralList(params,pageable);
    }

    @Override
    public int clearTowMonthIntegral() {
        Set<String> strings =  redisUtil.keys("invalid_*");
        if(Collections3.isNotEmpty(strings)){
            for(String str:strings){
                String vipId = str.replace("invalid_","");
                //查询vip是否有绑定校区
                LibVip vip = vipService.getById(vipId);
                if(vip==null){
                    continue;
                }
                //有绑定校区则不处理，删除key
                if(StringUtils.isNotEmpty(vip.getLibId())){
                    tokenManager.delString(str);
                    continue;
                }
                //无绑定校区且超达到或超过60天则清0
                String invalidValue = tokenManager.getString(str);
                if(towMillisDays(invalidValue)>=60){
                    int total = rankingService.searchIntegralByVipId(vipId);
                    rankingService.saveRankIntegral(vipId,-total,11,"");
                }
            }
        }
        return 0;
    }

    private int towMillisDays(String minMillis){
        int days = Integer.parseInt(minMillis) - (int)System.currentTimeMillis() / (1000*3600*24);
        return days;

    }

    private int getIntegral(int continueDays){

        if(continueDays%7==0){
            return 5;
        }
        if(continueDays%30==0){
            return 15;
        }
        return 1;
    }

    private List<Map<String,Integer>> initSignData(int continueDays){
        List<Map<String,Integer>> list = new ArrayList<>();
        int count = 31;
        for (int i = 1; i < count; i++) {
            Map<String,Integer> map = new HashMap<>(2);
            map.put("whetherSignIn",2);
            map.put("integral",1);
            if(i<=continueDays){
                map.put("whetherSignIn",1);
            }
            if(i%7==0){
                map.put("integral",5);
            }
            if(i%30==0){
                map.put("integral",15);
            }
            list.add(map);
        }
        return list;
    }
}
