package com.hr.service.impl;

import com.github.pagehelper.PageHelper;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.hr.param.InterfaceConfigParam;
import com.hr.param.IpInterfaceParam;
import com.hr.param.SwitchStatusParam;
import com.hr.repository.domain.IpInterfacePO;
import com.hr.repository.jpa.IpInterfaceRepository;
import com.hr.service.IpInterfaceService;
import com.hr.util.SnowflakeIdWorker;
import com.hr.vo.IpInterfaceVO;
import com.hr.vo.NameValueVO;
import com.yy.basedevelop.common.data.BasePageResult;
import com.yy.basedevelop.dto.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 接口表;(ip_interface)表服务接口实现类
 * @author : http://www.yonsum.com
 * @date : 2025-10-10
 */
@Service
public class IpInterfaceServiceImpl implements IpInterfaceService {
    @Autowired
    private IpInterfaceRepository ipInterfaceRepository;

    private static final Cache<String, IpInterfaceVO> QUERY_CACHE = CacheBuilder.newBuilder()
            .expireAfterWrite(1, TimeUnit.SECONDS)
            .build();
    
    /** 
     * 通过ID查询单条数据 
     *
     * @param id 主键
     * @return 实例对象
     */
    public IpInterfaceVO queryById(Long id){
//        IpInterfacePO ipInterfacePO = ipInterfaceRepository.findById(id).get();
        Optional<IpInterfacePO> optional = ipInterfaceRepository.findById(id);
        if(optional.isPresent()) {
            IpInterfacePO ipInterfacePO=optional.get();
            IpInterfaceVO ipInterfaceVO = new IpInterfaceVO();
            if (ipInterfacePO != null) {
                BeanUtils.copyProperties(ipInterfacePO, ipInterfaceVO);
                return ipInterfaceVO;
            }
        }
        return null;
    }

     @Override
     public BasePageResult<IpInterfaceVO> paginQuery(IpInterfaceParam interfaceParam, Integer current, Integer size) {
         PageHelper.startPage(interfaceParam.getPageNum(), interfaceParam.getPageSize());
         if (StringUtils.isNotEmpty(interfaceParam.getStatus())) {
             interfaceParam.setStatusList(Arrays.asList(interfaceParam.getStatus()));
         }
         BasePageResult<IpInterfaceVO> dbList = ipInterfaceRepository.queryPage(interfaceParam.getInterfaceName(), interfaceParam.getStatusList());
         return dbList;
     }

     /**
     * 新增数据
     *
     * @param IpInterfacePO 实例对象
     * @return 实例对象
     */
    public void insert(IpInterfacePO IpInterfacePO){
        ipInterfaceRepository.save(IpInterfacePO);
    }
    
    /** 
     * 更新数据
     * @param IpInterfacePO 实例对象
     * @return 实例对象
     */
    public void  update(IpInterfacePO IpInterfacePO){
        ipInterfaceRepository.save(IpInterfacePO);
    }

    @Override
    public IpInterfaceVO queryByInterfaceCode(String interfaceCode) {
        String key = "queryByInterfaceCode:" + interfaceCode;
        IpInterfaceVO vo = QUERY_CACHE.getIfPresent(key);
        if(vo != null){
            return vo;
        }else{
            vo = new IpInterfaceVO();
            IpInterfacePO interfaceNo = ipInterfaceRepository.findByInterfaceNo(interfaceCode);
            BeanUtils.copyProperties(interfaceNo,vo);
            QUERY_CACHE.put(key, vo);
        }
        return vo;
    }

    @Override
    public void interfaceConfig(InterfaceConfigParam param) {

    }

    @Override
    public List<NameValueVO> optionList() {
        List<IpInterfacePO> list = ipInterfaceRepository.findAll();
        List<IpInterfacePO> resultList = list.stream().filter(item -> !item.getStatus().equals("delete")).collect(Collectors.toList());
        List<NameValueVO> result = new ArrayList<>();
        resultList.forEach(item -> {
            NameValueVO vo = new NameValueVO();
            vo.setName(item.getInterfaceName());
            vo.setId(item.getId());
            result.add(vo);
        });
        return result;
    }

    @Override
    public Boolean switchStatus(SwitchStatusParam switchStatusParam) {
        Optional<IpInterfacePO> optional = ipInterfaceRepository.findById(switchStatusParam.getId());
        if(!optional.isPresent()){
            throw new RuntimeException("接口不存在");
        }
        IpInterfacePO ipInterfacePO = optional.get();

        ipInterfacePO.setStatus(switchStatusParam.getStatus());
        ipInterfaceRepository.save(ipInterfacePO);
        return true;
    }

    @Override
    public void saveOrUpdate(IpInterfaceParam ipInterfaceParam, String username, Long userid) {
        IpInterfacePO ipInterfacePO ;
        if(ipInterfaceParam.getId() == null){
            ipInterfacePO = ipInterfaceRepository.findByInterfaceName(ipInterfaceParam.getInterfaceName());
            if(ipInterfacePO != null){
                throw new RuntimeException("接口名称已存在");
            }
            ipInterfacePO = ipInterfaceRepository.findByInterfaceNo(ipInterfaceParam.getInterfaceNo());
            if(ipInterfacePO != null){
                throw new RuntimeException("接口编号已存在");
            }
            ipInterfacePO = new IpInterfacePO();
        }else{
            ipInterfacePO = ipInterfaceRepository.findByInterfaceName(ipInterfaceParam.getInterfaceName());
            if(ipInterfacePO != null && ipInterfacePO.getInterfaceName().equals(ipInterfaceParam.getInterfaceName()) && !ipInterfacePO.getId().equals(ipInterfaceParam.getId())){
                throw new RuntimeException("接口名称已存在");
            }
            ipInterfacePO = ipInterfaceRepository.findByInterfaceNo(ipInterfaceParam.getInterfaceNo());
            if(ipInterfacePO != null && ipInterfacePO.getInterfaceNo().equals(ipInterfaceParam.getInterfaceNo()) && !ipInterfacePO.getId().equals(ipInterfaceParam.getId())){
                throw new RuntimeException("接口编号已存在");
            }
        }
        if(ipInterfaceParam.getId() == null){
            ipInterfacePO.setId(SnowflakeIdWorker.nextId());
            ipInterfacePO.setAddTime(new Date());
            ipInterfacePO.setAddUserId(userid);
            ipInterfacePO.setAddUserName(username);
        }else{
            ipInterfacePO = ipInterfaceRepository.findById(ipInterfaceParam.getId()).get();
        }
        com.yy.basedevelop.common.BeanUtils.copyPropertiesIgnoreNullAndEmptyStr(ipInterfaceParam, ipInterfacePO);
        ipInterfacePO.setUpdateTime(new Date());
        ipInterfacePO.setUpdateUserId(userid);
        ipInterfacePO.setUpdateUserName(username);
        ipInterfaceRepository.save(ipInterfacePO);
    }

    /**
     * 通过主键删除数据
     *
     * @param iid  主键
     * @param user
     * @return 是否成功
     */
    public boolean deleteById(Long iid, LoginUser user){
        IpInterfacePO ipInterfacePO = ipInterfaceRepository.findById(iid).get();
        if(ipInterfacePO == null){
            return false;
        }
        Integer countNum = ipInterfaceRepository.countEnableInterfaceRef(iid);
        if(countNum > 0){
            throw new RuntimeException("存在激活的接口关联，请先停用关联的接口");
        }
        ipInterfacePO.setStatus("delete");
        ipInterfacePO.setUpdateTime(new Date());
        ipInterfacePO.setUpdateUserId(user.getUserid());
        ipInterfacePO.setUpdateUserName(user.getUsername());
        ipInterfaceRepository.save(ipInterfacePO);
        return true;
    }
}