package com.huatek.busi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.huatek.busi.entity.SftpConnectConfig;
import com.huatek.busi.mapper.SftpConnectConfigMapper;
import com.huatek.busi.service.ISftpConnectConfigService;
import com.huatek.busi.vo.SftpConnectConfigVo;
import com.huatek.frame.base.util.BeanUtils;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;
import com.huatek.torch.sql.beans.LocalUser;
import com.huatek.torch.sql.dao.impl.BaseDao;
import com.huatek.torch.util.tools.UserUtil;
import com.huatek.torch.util.uuid.Uuid;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;

@Component
@Service(interfaceClass = ISftpConnectConfigService.class)
@Transactional(rollbackFor = Exception.class)
public class SftpConnectConfigServiceImpl extends BaseDao<SftpConnectConfig, String> implements ISftpConnectConfigService {

    @Resource
    private SftpConnectConfigMapper sftpConnectConfigMapper;

    @Override
    public SftpConnectConfig findOne() {
        return sftpConnectConfigMapper.findOne();
    }

    @Override
    public Map<String, Object> saveOrUpdate(String token, SftpConnectConfigVo sftpConnectConfigVo) {
        if(StrUtil.isEmpty(token)){
            return ResultUtil.put(ConstantUtil.JWT_CODE_FAIL, "BUSINESS.TOKEN", "");
        }

        // 初始化数据
        sftpConnectConfigMapper.delete();
        LocalUser user = UserUtil.getLocalUser(token);
        sftpConnectConfigVo.setId(Uuid.getUUID());
        if(user != null){
            sftpConnectConfigVo.setCreateUser(user.getUid());
            sftpConnectConfigVo.setCreateTime(LocalDateTime.now());
        }

        SftpConnectConfig sftp = new SftpConnectConfig();
        BeanUtils.copyProperties(sftpConnectConfigVo, sftp);
        this.add(sftp);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.INSERT.SUCCESS", sftp);
    }
}
