package com.github.wxiaoqi.security.admin.biz;

import com.ace.cache.annotation.Cache;
import com.ace.cache.annotation.CacheClear;
import com.github.wxiaoqi.security.admin.dto.BaseUserMemberVO;
import com.github.wxiaoqi.security.admin.dto.UserMemberDTO;
import com.github.wxiaoqi.security.admin.vo.AppUserVo;
import com.github.wxiaoqi.security.admin.vo.UserMemberVo;
import com.github.wxiaoqi.security.common.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import com.github.wxiaoqi.security.admin.entity.BaseUserMember;
import com.github.wxiaoqi.security.admin.mapper.BaseUserMemberMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;

import java.lang.reflect.InvocationTargetException;

import java.util.List;

/**
 * 用户会员表
 *
 * @author zjw
 * @email nishijjo@qq.com
 * @date 2019-06-18 19:38:56
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class BaseUserMemberBiz extends BaseBiz<BaseUserMemberMapper,BaseUserMember> {

    @Autowired
    AppUserDetailBiz detailBiz;

    @Autowired
    private TaskExecutor taskExecutor;

    @Autowired
    private UserMemberLevelBiz userMemberLevelBiz;

    @Autowired
    private AppUserLoginBiz appUserLoginBiz;

   //获取用户会员信息
   @Cache(key = "user:member{1}")
    public UserMemberVo getMemberInfoByUserId(Integer userId){
        return  mapper.getInfoByUserId(userId);
    }

    //更新会员信息
    @Override
    @CacheClear(key = "user:member{1.userId}")
    public  void  updateSelectiveById(BaseUserMember userMember){  super.updateSelectiveById(userMember);}


    //用户购买会员信息更新
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public  void  updUserMemberByUserId(UserMemberDTO userMemberDTO)throws  Exception{
        if(userMemberDTO==null){
            log.error("updUserMemberByUserId----参数为空");
             return;
        }
        Integer userId=userMemberDTO.getUserId();
        UserMemberVo userMemberVo=getMemberInfoByUserId(userId);
        BaseUserMember baseUserMember=new BaseUserMember();
        BeanUtils.copyProperties(baseUserMember,userMemberDTO);
        Integer freeDays= baseUserMember.getRentFreeDays();
        Integer totalNumber=baseUserMember.getTotalNumber()==null?0:baseUserMember.getTotalNumber();
        if(freeDays==null||freeDays==0){
            freeDays=totalNumber;
        }
        Integer buyCount=1;
        if(userMemberDTO.getBuyCount()!=null){
            buyCount=userMemberDTO.getBuyCount();
        }
        if(userMemberVo==null){
            baseUserMember.setRentFreeDays(freeDays);
            baseUserMember.setBuyCount(buyCount);
            insertSelective(baseUserMember);
        }else {
            Integer discount=userMemberVo.getDiscount()==null?0:userMemberVo.getDiscount();
            Integer discount1=baseUserMember.getDiscount()==null?0:baseUserMember.getDiscount();
            if(discount<discount1){
                baseUserMember.setDiscount(discount);
            }
            Integer level=userMemberVo.getMemberLevel()==null?0:userMemberVo.getMemberLevel();
            Integer level1=baseUserMember.getMemberLevel()==null?0:baseUserMember.getMemberLevel();
            if(level>level1){
                baseUserMember.setMemberLevel(level);
            }
            baseUserMember.setId(userMemberVo.getId());
            totalNumber+=userMemberVo.getTotalNumber()==null?0:userMemberVo.getTotalNumber();
            freeDays+=userMemberVo.getRentFreeDays()==null?0:userMemberVo.getRentFreeDays();
            baseUserMember.setBuyCount(userMemberVo.getBuyCount()+buyCount);
            baseUserMember.setTotalNumber(totalNumber);
            baseUserMember.setRentFreeDays(freeDays);
            getMyBiz().updateSelectiveById(baseUserMember);
        }
        AppUserVo userVo= detailBiz.getUserInfoById(userId);
        if(userVo!=null&&(userVo.getIsMember()==null||userVo.getIsMember()==0)){
            AppUserVo userVo1=new AppUserVo();
            userVo1.setId(userVo.getId());
            userVo1.setUserid(userId);
            userVo1.setIsMember(1);
            detailBiz.updUuserInfoById(userVo1);
        }

    }
    /**
     * //
     * @param userId
     * @param days
     * @param type;1-用户锁定下单；2-购买下单;3-取消订单
     * @return
     */
    public  int  upMemberDays(Integer userId,Integer days,Integer type){
        int num=-1;
        UserMemberVo userMemberVo=getMemberInfoByUserId(userId);
        if(userMemberVo!=null){
            days=days==null?0:days;
            Integer freeDays=userMemberVo.getRentFreeDays()==null?0:userMemberVo.getRentFreeDays();
           // Integer lockDays=userMemberVo.getLockDays()==null?userMemberVo.getLockDays():0;
            Integer totalNumber=userMemberVo.getTotalNumber()==null?0:userMemberVo.getTotalNumber();
            BaseUserMember baseUserMember=new BaseUserMember();
            baseUserMember.setId(userMemberVo.getId());
            baseUserMember.setUserId(userId);
            if(type==1){
                /*if((freeDays-lockDays)>0&&(freeDays-lockDays)>=days){
                    baseUserMember.setLockDays(lockDays+days);
                    updateSelectiveById(baseUserMember);
                    num=freeDays-(lockDays+days);
                }*/
                if(freeDays>0&&freeDays>=days){
                    freeDays=freeDays-days;
                    baseUserMember.setRentFreeDays(freeDays);
                    Integer payCount=userMemberVo.getPayCount()==null?0:userMemberVo.getPayCount();
                    if(days>0){
                        payCount=payCount+1;
                    }
                    baseUserMember.setPayCount(payCount);
                    getMyBiz().updateSelectiveById(baseUserMember);
                    num=freeDays;
                }
            }else if(type==2){
                    /*Integer payCount=userMemberVo.getPayCount()==null?0:userMemberVo.getPayCount();
                    payCount=payCount+1;
                    freeDays=(freeDays-days)>0?(freeDays-days):0;
                    lockDays=lockDays>0?(lockDays-days)>0?(lockDays-days):0:0;
                    baseUserMember.setRentFreeDays(freeDays);
                    baseUserMember.setPayCount(payCount);
                    baseUserMember.setLockDays(lockDays);
                    updateSelectiveById(baseUserMember);
                    num=freeDays-lockDays;*/
                /*Integer payCount=userMemberVo.getPayCount()==null?0:userMemberVo.getPayCount();
                if(days>0){
                    payCount=payCount+1;
                }
                baseUserMember.setPayCount(payCount);
                getMyBiz().updateSelectiveById(baseUserMember);*/
                num=freeDays;
            }else {
                /*lockDays=lockDays>0?(lockDays-days)>0?(lockDays-days):0:0;
                baseUserMember.setLockDays(lockDays);
                getMyBiz().updateSelectiveById(baseUserMember);
                num=freeDays-lockDays;*/
                freeDays=(freeDays+days)>0?(freeDays+days):0;
                freeDays=freeDays>totalNumber?totalNumber:freeDays;
                baseUserMember.setRentFreeDays(freeDays);
                getMyBiz().updateSelectiveById(baseUserMember);
                num=freeDays;
            }

        }
        return  num;
    }

    private BaseUserMemberBiz getMyBiz() {
        return AopContext.currentProxy() != null ? (BaseUserMemberBiz) AopContext.currentProxy() : this;
    }

    /**
     * 获取用户会员信息
     * @param userId
     * @return
     */
    public BaseUserMemberVO findOneByUserId(Integer userId) {
        BaseUserMemberVO baseUserMemberVO=  mapper.getBaseUserMemberVOByUserId(userId);
        if (baseUserMemberVO!=null) {
            return baseUserMemberVO;
        }
        return new BaseUserMemberVO();

    }


    /**
     * 设置用户会员
     * @param baseUserMemberVO
     */
    @Transactional(rollbackFor = Exception.class)
    public void UpdateUserMember(BaseUserMemberVO baseUserMemberVO) throws InvocationTargetException, IllegalAccessException {

        Example exa = Example.builder(BaseUserMember.class).where(
                WeekendSqls.<BaseUserMember>custom()
                        .andEqualTo(BaseUserMember::getUserId, baseUserMemberVO.getUserId())
        ).build();

        List<BaseUserMember> baseUserMembers = mapper.selectByExample(exa);

        BaseUserMember baseUserMember = new BaseUserMember();
        BeanUtilsBean.getInstance().copyProperties(baseUserMember,baseUserMemberVO);
        if (baseUserMembers==null||baseUserMembers.size()==0) {
            if (baseUserMemberVO.getMemberLevel()==null||baseUserMember.getValidTime()==null) return;
            baseUserMember.setCrtTime(System.currentTimeMillis());
            baseUserMember.setIsDel(0);
            baseUserMember.setPayCount(0);
            baseUserMember.setCardLeave(1);
            baseUserMember.setRecentRecharge(System.currentTimeMillis());
          Integer  buyCount = baseUserMember.getBuyCount()==null? 0:baseUserMember.getBuyCount();
           baseUserMember.setBuyCount(buyCount+1);
            insertSelective(baseUserMember);
            return;
        }else if (baseUserMembers.size()==1){
         baseUserMember.setUpdTime(System.currentTimeMillis());
            getMyBiz().updateSelectiveById(baseUserMember);
        }else {
            throw new BaseException("Member purchase repeat!");
        }
    }

}