package com.hr.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.hr.param.IpAccountParam;
import com.hr.param.SwitchStatusParam;
import com.hr.repository.domain.IpAccountPO;
import com.hr.repository.jpa.IpAccountRepository;
import com.hr.repository.jpa.IpInterfaceRepository;
import com.hr.service.IpAccountService;
import com.hr.util.SnowflakeIdWorker;
import com.hr.vo.IpAccountVO;
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.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 账户表;(ip_account)表服务接口实现类
 * @author : http://www.yonsum.com
 * @date : 2025-10-10
 */
@Service
public class IpAccountServiceImpl implements IpAccountService {
    @Autowired
    private IpAccountRepository ipAccountRepository;

    @Autowired
    private IpInterfaceRepository ipInterfaceRepository;


    private static final Cache<String, IpAccountVO> QUERY_CACHE = CacheBuilder.newBuilder()
            .expireAfterWrite(1, TimeUnit.SECONDS)
            .build();

    /** 
     * 通过ID查询单条数据 
     *
     * @param id 主键
     * @return 实例对象
     */
    public IpAccountVO queryById(Long id){
        IpAccountVO vo = new IpAccountVO();
        IpAccountPO ipAccountPO = ipAccountRepository.queryById(id);
        if(ipAccountPO != null){
            BeanUtils.copyProperties(ipAccountPO, vo);
            return vo;
        }
        return null;
    }

    @Override
    public BasePageResult<IpAccountVO> paginQuery(IpAccountParam ipAccountParam, Integer current, Integer size) {
        if (StringUtils.isNotEmpty(ipAccountParam.getStatus())) {
            ipAccountParam.setStatusList(Arrays.asList(ipAccountParam.getStatus()));
        }
        PageHelper.startPage(current, size);
        BasePageResult<IpAccountVO> resultList = ipAccountRepository.queryList(ipAccountParam.getAccNo(),ipAccountParam.getStatusList());
        return resultList;
    }
    
    /** 
     * 新增数据
     *
     * @param IpAccountPO 实例对象
     * @return 实例对象
     */
    public void insert(IpAccountPO IpAccountPO){
        ipAccountRepository.save(IpAccountPO);
    }
    
    /** 
     * 更新数据
     *
     * @param IpAccountPO 实例对象
     * @return 实例对象
     */
    public void update(IpAccountPO IpAccountPO){
        ipAccountRepository.save(IpAccountPO);
    }


    @Override
    public IpAccountVO queryByAccountNo(String accountNo) {
        String key = "queryByAccountNo:" + accountNo;
        IpAccountVO cacheValue = QUERY_CACHE.getIfPresent(key);
        if(cacheValue != null){
            return cacheValue;
        }else{
            IpAccountVO vo = new IpAccountVO();
            IpAccountPO accountPO = ipAccountRepository.findByAccNo(accountNo);
            BeanUtils.copyProperties(accountPO,vo);
            QUERY_CACHE.put(key, vo);
            return vo;
        }

    }

    @Override
    public Boolean switchStatus(SwitchStatusParam switchStatusParam,LoginUser user) {
        Optional<IpAccountPO> optional = ipAccountRepository.findById(switchStatusParam.getId());
        if(!optional.isPresent()){
            throw new RuntimeException("接口不存在");
        }
        IpAccountPO ipAccountPO = optional.get();
        ipAccountPO.setUpdateTime(new Date());
        ipAccountPO.setUpdateUserId(user.getUserid());
        ipAccountPO.setUpdateUserName(user.getUsername());
        ipAccountPO.setStatus(switchStatusParam.getStatus());
        ipAccountRepository.save(ipAccountPO);
        return true;
    }

    @Override
    public void saveOrUpdate(IpAccountParam accountParam, String userName, Long userId) {
        IpAccountPO ipAccountPO ;
        if(accountParam.getId() == null){
            ipAccountPO = ipAccountRepository.findByAccNo(accountParam.getAccNo());
            if(ipAccountPO != null){
                throw new RuntimeException("账户编号已存在");
            }
            ipAccountPO = new IpAccountPO();
            ipAccountPO.setAccNo(accountParam.getAccNo());
            ipAccountPO.setStatus("normal");
        }else{
            ipAccountPO = ipAccountRepository.findById(accountParam.getId()).get();
        }
        if(accountParam.getId() == null){
            ipAccountPO.setId(SnowflakeIdWorker.nextId());
            ipAccountPO.setAddTime(new Date());
            ipAccountPO.setAddUserId(userId);
            ipAccountPO.setAddUserName(userName);
        }
        ipAccountPO.setStatus(accountParam.getStatus());
        ipAccountPO.setRemark(accountParam.getRemark());
        ipAccountPO.setUpdateTime(new Date());
        ipAccountPO.setUpdateUserId(userId);
        ipAccountPO.setUpdateUserName(userName);
        ipAccountRepository.save(ipAccountPO);

    }

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