package com.huiju.estateagents.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.entity.TaPersonMessageRule;
import com.huiju.estateagents.mapper.TaPersonMessageRuleMapper;
import com.huiju.estateagents.service.ITaPersonMessageRuleService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 楼盘户型对应图片表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-05-10
 */
@Service
public class TaPersonMessageRuleImpl extends ServiceImpl<TaPersonMessageRuleMapper, TaPersonMessageRule> implements ITaPersonMessageRuleService {
    @Autowired
    private TaPersonMessageRuleMapper taPersonMessageRuleMapper;

    @Override
    public TaPersonMessageRule getByPersonAndType(String personId, String messageType, String contentType, Integer orgId) {
        return taPersonMessageRuleMapper.getByPersonAndType(personId, messageType, contentType, orgId);
    }

    @Override
    public TaPersonMessageRule saveOrUpdateByPersonAndMessage(String personId, String messageType, String contentType, Integer orgId) {
        boolean success = false;
        LocalDateTime now = LocalDateTime.now();
        TaPersonMessageRule rule = getByPersonAndType(personId, messageType, contentType, orgId);

        if (null == rule) {
            // 没有信息则插入新记录
            TaPersonMessageRule data = new TaPersonMessageRule();
            data.setPersonId(personId);
            data.setMessageType(messageType);
            data.setContentType(contentType);
            data.setOrgId(orgId);
            data.setLimitNum(-1);   // 暂定 -1 是不限制
            data.setLastSendTime(now);

            success = save(data);
            return success ? data : null;
        } else {
            // 有的话则更新记录
            rule.setLastSendTime(now);

            if (rule.getLimitNum() > -1) {
                Integer left = rule.getLeftNum();
                if (null == left || left <= 0) {
                    left = 0;
                } else {
                    left -= 1;
                }
                rule.setLeftNum(left);
            }

            success = updateById(rule);
            return success ? rule : null;
        }
    }
}
