package cn.gintone.service;

import cn.gintone.ErrorInfo;
import cn.gintone.config.IotDbConfig;
import cn.gintone.controller.vo.VisitInfoPageReqVO;
import cn.gintone.controller.vo.VisitInfoRespVO;
import cn.gintone.controller.vo.VisitInfoSaveReqVO;
import cn.gintone.dal.VisitInfoMapper;
import cn.gintone.dto.WebIllLogInfo;
import cn.gintone.dto.WebLogInfo;
import cn.gintone.entity.VisitInfoDO;
import cn.gintone.iotdbUtils.MyIotDbUtils;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.UserRoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.permission.RoleMapper;
import cn.iocoder.yudao.module.system.dal.mysql.permission.UserRoleMapper;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 访问规则配置 Service 实现类
 *
 * @author 胡懿
 */
@Service
@Validated
public class VisitInfoServiceImpl implements VisitInfoService {

    @Resource
    private VisitInfoMapper visitInfoMapper;
    @Autowired
    private IotDbConfig iotDbConfig;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Long createVisitInfo(VisitInfoSaveReqVO createReqVO) {
        // 插入
        VisitInfoDO visitInfo = BeanUtils.toBean(createReqVO, VisitInfoDO.class);
        visitInfoMapper.insert(visitInfo);
        // 返回
        return visitInfo.getId();
    }

    @Override
    public void updateVisitInfo(VisitInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateVisitInfoExists(updateReqVO.getId());
        // 更新
        VisitInfoDO updateObj = BeanUtils.toBean(updateReqVO, VisitInfoDO.class);
        visitInfoMapper.updateById(updateObj);
    }

    @Override
    public void deleteVisitInfo(Long id) {
        // 校验存在
        validateVisitInfoExists(id);
        // 删除
        visitInfoMapper.deleteById(id);
    }

    private void validateVisitInfoExists(Long id) {
        if (visitInfoMapper.selectById(id) == null) {
            throw exception(ErrorInfo.VISIT_INFO_NOT_EXISTS);
        }
    }

    @Override
    public VisitInfoDO getVisitInfo(Long id) {
        return visitInfoMapper.selectById(id);
    }

    @Override
    public PageResult<VisitInfoDO> getVisitInfoPage(VisitInfoPageReqVO pageReqVO) {
        return visitInfoMapper.selectPage(pageReqVO);
    }

    public List<VisitInfoDO> getList(VisitInfoPageReqVO reqVo) {
        return visitInfoMapper.selectList(reqVo);
    }

    @Override
    public Boolean saveAllVisitInfo(List<VisitInfoSaveReqVO> visitInfoSaveReqVOList) {
        if (visitInfoSaveReqVOList != null && !visitInfoSaveReqVOList.isEmpty()) {
            List<VisitInfoDO> visitInfoDOList = new ArrayList<>();
            for (VisitInfoSaveReqVO visitInfoSaveReqVO : visitInfoSaveReqVOList) {
                VisitInfoDO visitInfo = BeanUtils.toBean(visitInfoSaveReqVO, VisitInfoDO.class);
                visitInfoDOList.add(visitInfo);
            }
            return visitInfoMapper.insertBatch(visitInfoDOList);
        }

        return false;
    }

    @Override
    public void deleteByVisitId(Long visitId) {
        visitInfoMapper.delete(new QueryWrapper<VisitInfoDO>().lambda().eq(VisitInfoDO::getVisitId, visitId));
    }

    @Override
    public boolean updateAllVisitInfo(List<VisitInfoSaveReqVO> visitInfoSaveReqVOList) {
        if (visitInfoSaveReqVOList != null && !visitInfoSaveReqVOList.isEmpty()) {
            VisitInfoSaveReqVO visitInfoSaveReqVO1 = visitInfoSaveReqVOList.get(0);
            visitInfoMapper.delete(new QueryWrapper<VisitInfoDO>().lambda().eq(VisitInfoDO::getVisitId, visitInfoSaveReqVO1.getVisitId()));
            List<VisitInfoDO> visitInfoDOList = new ArrayList<>();
            for (VisitInfoSaveReqVO visitInfoSaveReqVO : visitInfoSaveReqVOList) {
                VisitInfoDO visitInfo = BeanUtils.toBean(visitInfoSaveReqVO, VisitInfoDO.class);
                visitInfoDOList.add(visitInfo);
            }
            return visitInfoMapper.insertBatch(visitInfoDOList);
        }

        return false;
    }

    @Override
    public void checkWebLogInfo(WebLogInfo webLogInfo) {
        String userId = webLogInfo.getUserId();
        if (null == userId || "".equals(userId)) {
            WebIllLogInfo webIllLogInfo = new WebIllLogInfo();
            webIllLogInfo.setUserId(webLogInfo.getUserId());
            webIllLogInfo.setUserId(webLogInfo.getUsername());
            webIllLogInfo.setSysAbbre(webLogInfo.getSysAbbre());
            webIllLogInfo.setUrl(webLogInfo.getUrl());
            webIllLogInfo.setAccessed(webLogInfo.getAccessed());
            webIllLogInfo.setType(webLogInfo.getType());
            webIllLogInfo.setClientIp(webLogInfo.getClientIp());
            webIllLogInfo.setRemark(webLogInfo.getRemark());
            webIllLogInfo.setIllType("noRule");
            MyIotDbUtils.inserOne_Ill(iotDbConfig, webIllLogInfo);
            return;
        }
        // 获取用户信息和角色信息------需要调用平台的接口
        List<UserRoleDO> userRoleDOS = userRoleMapper.selectListByUserId(Long.parseLong(userId));

        boolean isLegal = false; // 是否合法。false:不合法，true：合法
        // 先查询角色规则
        if (null != userRoleDOS && !userRoleDOS.isEmpty()) {
            for (UserRoleDO  userRoleDO : userRoleDOS) {
                List<VisitInfoDO> visitInfoDOS = visitInfoMapper.selectList(new LambdaQueryWrapper<VisitInfoDO>()
                        .eq(VisitInfoDO::getRoleId, userRoleDO.getRoleId())
                        .like(VisitInfoDO::getUrl, webLogInfo.getUrl())
                );
                if (null != visitInfoDOS && visitInfoDOS.size() > 0) {
                    isLegal = true;
                }
            }

        }

        // 查询用户规则，如果配置了用户规则，则按照用户规则走
        List<VisitInfoDO> visitInfoDOS = visitInfoMapper.selectList(new LambdaQueryWrapper<VisitInfoDO>()
                .like(VisitInfoDO::getUrl, webLogInfo.getUrl())
        );
        if (null != visitInfoDOS && visitInfoDOS.size() > 0) {
            isLegal = false;
            List<VisitInfoDO> visitInfoDOS2 = visitInfoMapper.selectList(new LambdaQueryWrapper<VisitInfoDO>()
                    .eq(VisitInfoDO::getUserId, userId)
                    .like(VisitInfoDO::getUrl, webLogInfo.getUrl())
            );
            if (null != visitInfoDOS2 && visitInfoDOS2.size() > 0) {
                isLegal = true;
            }
        }

        if (!isLegal) {
            WebIllLogInfo webIllLogInfo = new WebIllLogInfo();
            webIllLogInfo.setUserId(webLogInfo.getUserId());
            webIllLogInfo.setUserId(webLogInfo.getUsername());
            webIllLogInfo.setSysAbbre(webLogInfo.getSysAbbre());
            webIllLogInfo.setUrl(webLogInfo.getUrl());
            webIllLogInfo.setAccessed(webLogInfo.getAccessed());
            webIllLogInfo.setType(webLogInfo.getType());
            webIllLogInfo.setClientIp(webLogInfo.getClientIp());
            webIllLogInfo.setRemark(webLogInfo.getRemark());
            webIllLogInfo.setIllType("noRule");
            MyIotDbUtils.inserOne_Ill(iotDbConfig, webIllLogInfo);
        }

    }

}