package com.qmth.themis.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.themis.business.cache.ExamRecordCacheUtil;
import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.dao.TIpRegionMapper;
import com.qmth.themis.business.entity.TIpRegion;
import com.qmth.themis.business.service.TIpRegionService;
import com.qmth.themis.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * ip信息表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2022-08-18
 */
@Service
public class TIpRegionServiceImpl extends ServiceImpl<TIpRegionMapper, TIpRegion> implements TIpRegionService {
    private final static Logger log = LoggerFactory.getLogger(TIpRegionServiceImpl.class);

    /**
     * 保存ip信息
     *
     * @param examRecordId
     */
    @Override
    public void saveIpRegion(Long examRecordId) {
        try {
            String[] strs = SystemConstant.getIpInfo(ExamRecordCacheUtil.getClientCurrentIp(examRecordId));
            if (Objects.nonNull(strs) && strs.length > 0) {
                QueryWrapper<TIpRegion> tIpRegionQueryWrapper = new QueryWrapper<>();
                tIpRegionQueryWrapper.lambda().eq(TIpRegion::getExamRecordId, examRecordId);
                TIpRegion tIpRegion = this.getOne(tIpRegionQueryWrapper);
                if (Objects.isNull(tIpRegion)) {
                    tIpRegion = new TIpRegion(examRecordId, strs[0], strs[1], strs[2], strs[3], strs[4]);
                    this.save(tIpRegion);
                } else {
                    if (!Objects.equals(tIpRegion.getCountry(), strs[0])
                            || !Objects.equals(tIpRegion.getRegion(), strs[1])
                            || !Objects.equals(tIpRegion.getProvince(), strs[2])
                            || !Objects.equals(tIpRegion.getCity(), strs[3])
                            || !Objects.equals(tIpRegion.getIsp(), strs[4])) {
                        tIpRegion.updateInfo(strs[0], strs[1], strs[2], strs[3], strs[4]);
                        this.updateById(tIpRegion);
                    }
                }
            }
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            if (e instanceof BusinessException) {
                throw new BusinessException(e.getMessage());
            } else {
                throw new RuntimeException(e);
            }
        }
    }
}
