package com.xxfc.platform.activity.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.activity.entity.IntegralUserStatus;
import com.xxfc.platform.activity.mapper.IntegralUserStatusMapper;
import com.xxfc.platform.activity.util.IntegralToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@Slf4j
public class IntegralUserStatusBiz extends BaseBiz<IntegralUserStatusMapper, IntegralUserStatus> {

    public ObjectRestResponse save(IntegralUserStatus integralUserStatus) {
        if(integralUserStatus != null) {
            List<IntegralUserStatus> oldValue = selectByUserAndCode(integralUserStatus.getIntegralRuleCode(), integralUserStatus.getUserId());
            if(oldValue != null && oldValue.size() > 0) {
                BeanUtil.copyProperties(integralUserStatus, oldValue.get(0), CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                updateSelectiveById(oldValue.get(0));
            }
            insertSelective(integralUserStatus);
        }
        return ObjectRestResponse.succ();
    }

    public List<IntegralUserStatus> selectByUserAndCode(String code, Integer userId) {
        if(!StringUtils.isAllBlank(code, userId + "")) {
            IntegralUserStatus integralUserStatus = new IntegralUserStatus();
            integralUserStatus.setIntegralRuleCode(code);
            integralUserStatus.setUserId(userId);
            if(!"REGISTER".equals(code) && !"CRETIFICATION".equals(code) && !"BINDWECHAT".equals(code)) {
                integralUserStatus.setStartTime(IntegralToolsUtils.getDayStart());
                integralUserStatus.setEndTime(IntegralToolsUtils.getDayStart() + 24 * 60 * 60 * 1000);
            }
            log.info("获取用户积分状态：" + integralUserStatus.toString());
            return mapper.selectByUserAndCode(integralUserStatus);
        }
        return null;
    }

}
