package cn.gintone.service;

import cn.gintone.ErrorInfo;
import cn.gintone.controller.vo.WebReqConfListReqVO;
import cn.gintone.controller.vo.WebReqConfSaveReqVO;
import cn.gintone.dal.VisitInfoMapper;
import cn.gintone.dal.WebReqConfMapper;
import cn.gintone.entity.VisitInfoDO;
import cn.gintone.entity.WebReqConfDO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

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


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

/**
 * web请求配置 Service 实现类
 *
 * @author 安全系统管理
 */
@Service
@Validated
public class WebReqConfServiceImpl implements WebReqConfService {

    @Resource
    private WebReqConfMapper webReqConfMapper;
    @Resource
    private VisitInfoMapper visitInfoMapper;

    @Override
    public Long createWebReqConf(WebReqConfSaveReqVO createReqVO) {
        // 校验父级id的有效性
        validateParentWebReqConf(null, createReqVO.getParentId());
        // 校验api名称的唯一性
        validateWebReqConfApiNameUnique(null, createReqVO.getParentId(), createReqVO.getApiName());

        // 插入
        WebReqConfDO webReqConf = BeanUtils.toBean(createReqVO, WebReqConfDO.class);
        webReqConfMapper.insert(webReqConf);
        // 返回
        return webReqConf.getId();
    }

    @Override
    public void updateWebReqConf(WebReqConfSaveReqVO updateReqVO) {
        // 校验存在
        validateWebReqConfExists(updateReqVO.getId());
        // 校验父级id的有效性
        validateParentWebReqConf(updateReqVO.getId(), updateReqVO.getParentId());
        // 校验api名称的唯一性
        validateWebReqConfApiNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getApiName());

        visitInfoMapper.update(new UpdateWrapper<VisitInfoDO>()
                .lambda()
                .eq(VisitInfoDO::getUrlId, updateReqVO.getId())
                .set(VisitInfoDO::getUrlName, updateReqVO.getApiName())
                .set(VisitInfoDO::getUrl, updateReqVO.getApiUrl())
        );
        // 更新
        WebReqConfDO updateObj = BeanUtils.toBean(updateReqVO, WebReqConfDO.class);
        webReqConfMapper.updateById(updateObj);
    }

    @Override
    public void deleteWebReqConf(Long id) {
        // 校验存在
        validateWebReqConfExists(id);
        // 校验是否有子web请求配置
        if (webReqConfMapper.selectCountByParentId(id) > 0) {
            throw exception(ErrorInfo.WEB_REQ_CONF_EXITS_CHILDREN);
        }
        // 删除
        webReqConfMapper.deleteById(id);
    }

    private void validateWebReqConfExists(Long id) {
        if (webReqConfMapper.selectById(id) == null) {
            throw exception(ErrorInfo.WEB_REQ_CONF_NOT_EXISTS);
        }
    }

    private void validateParentWebReqConf(Long id, Long parentId) {
        if (parentId == null || WebReqConfDO.PARENT_ID_ROOT.equals(parentId)) {
            return;
        }
        // 1. 不能设置自己为父web请求配置
        if (Objects.equals(id, parentId)) {
            throw exception(ErrorInfo.WEB_REQ_CONF_PARENT_ERROR);
        }
        // 2. 父web请求配置不存在
        WebReqConfDO parentWebReqConf = webReqConfMapper.selectById(parentId);
        if (parentWebReqConf == null) {
            throw exception(ErrorInfo.WEB_REQ_CONF_PARENT_NOT_EXITS);
        }
        // 3. 递归校验父web请求配置，如果父web请求配置是自己的子web请求配置，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            parentId = parentWebReqConf.getParentId();
            if (Objects.equals(id, parentId)) {
                throw exception(ErrorInfo.WEB_REQ_CONF_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父web请求配置
            if (parentId == null || WebReqConfDO.PARENT_ID_ROOT.equals(parentId)) {
                break;
            }
            parentWebReqConf = webReqConfMapper.selectById(parentId);
            if (parentWebReqConf == null) {
                break;
            }
        }
    }

    private void validateWebReqConfApiNameUnique(Long id, Long parentId, String apiName) {
        WebReqConfDO webReqConf = webReqConfMapper.selectByParentIdAndApiName(parentId, apiName);
        if (webReqConf == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的web请求配置
        if (id == null) {
            throw exception(ErrorInfo.WEB_REQ_CONF_API_NAME_DUPLICATE);
        }
        if (!Objects.equals(webReqConf.getId(), id)) {
            throw exception(ErrorInfo.WEB_REQ_CONF_API_NAME_DUPLICATE);
        }
    }

    @Override
    public WebReqConfDO getWebReqConf(Long id) {
        return webReqConfMapper.selectById(id);
    }

    @Override
    public List<WebReqConfDO> getWebReqConfList(WebReqConfListReqVO listReqVO) {
        return webReqConfMapper.selectList(listReqVO);
    }

    @Override
    public Long myCreateWebReqConf(WebReqConfSaveReqVO createReqVO) {

        List<WebReqConfDO> webReqConfDOS = webReqConfMapper.selectList(new QueryWrapper<WebReqConfDO>()
                .lambda()
                .eq(WebReqConfDO::getApiId, createReqVO.getApiId())
        );
        if (webReqConfDOS != null && webReqConfDOS.size() > 0) {
            for (WebReqConfDO webReqConfDO : webReqConfDOS) {
                webReqConfDO.setApiUrl(createReqVO.getApiUrl());
                webReqConfDO.setApiName(createReqVO.getApiName());
                webReqConfMapper.updateById(webReqConfDO);
            }
            return 0L;
        } else {
            // 校验父级id的有效性
//            validateParentWebReqConf(null, createReqVO.getParentId());
            // 校验api名称的唯一性
//            validateWebReqConfApiNameUnique(null, createReqVO.getParentId(), createReqVO.getApiName());
            // 插入
            WebReqConfDO webReqConf = BeanUtils.toBean(createReqVO, WebReqConfDO.class);
            webReqConfMapper.insert(webReqConf);
            return webReqConf.getId();
        }
    }

}