package com.reyun.saas.mob.user.service.impl;

import cn.hutool.core.date.DateUtil;
import com.reyun.saas.common.constants.AfficheEnumType;
import com.reyun.saas.common.util.IPUtils;
import com.reyun.saas.mob.user.dao.AfficheAckMapper;
import com.reyun.saas.mob.user.domain.AfficheAck;
import com.reyun.saas.mob.user.domain.User;
import com.reyun.saas.mob.user.service.AfficheSerivce;
import com.reyun.saas.mob.user.service.UserService;
import com.reyun.saas.mob.util.IPAddrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: hanzepeng
 * @Date: 2022/03/03/18:42
 * @Description: 公告业务层
 */
@Slf4j
@Service
@Transactional
public class AfficheSerivceImpl implements AfficheSerivce {

    @Autowired
    private UserService userService;

    @Autowired
    private AfficheAckMapper afficheAckMapper;

    /**
     * 根据用户id 查询公告确认情况
     */
    @Override
    public List<AfficheAck> findAckByUserId(Long userId) {
        if(userId == null ){
            return null;
        }
        Example example = new Example(AfficheAck.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        return afficheAckMapper.selectByExample(example);
    }

    /**
     * 创建公告确认记录
     */
    @Override
    public AfficheAck createAfficheAck(Long loginUserId, String afficheName, HttpServletRequest request) {
        User user = userService.findById(loginUserId);
        if(user == null){
            return null;
        }
        if (!AfficheEnumType.afficheExists(afficheName)) {
            return null;
        }
        AfficheAck afficheAck = new AfficheAck();
        afficheAck.setUserId(loginUserId);
        afficheAck.setAfficheName(afficheName);
        afficheAck.setAckTime(DateUtil.now());
        String ipAddr = IPUtils.getIpAddr(request);//获取真实ip
        afficheAck.setIp(ipAddr);
        String locationFromIpAddr = IPAddrUtil.getLocationFromIpAddr(request);//获取ip归属地
        afficheAck.setAddress(locationFromIpAddr);
        afficheAckMapper.insertSelective(afficheAck);
        return afficheAck;
    }
}
