package com.huatek.busi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.huatek.busi.entity.GlobalSettingItem;
import com.huatek.busi.mapper.GlobalSettingItemMapper;
import com.huatek.busi.service.IGlobalSettingItemService;
import com.huatek.busi.vo.GlobalSettingItemVo;
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 = IGlobalSettingItemService.class)
@Transactional(rollbackFor = Exception.class)
public class GlobalSettingItemServiceImpl extends BaseDao<GlobalSettingItem, String> implements IGlobalSettingItemService {

    @Resource
    private GlobalSettingItemMapper globalSettingItemMapper;

    @Override
    public GlobalSettingItem findOne() {
        return globalSettingItemMapper.findOne();
    }

    @Override
    public Map<String, Object> saveOrUpdate(String token, GlobalSettingItemVo globalSettingItemVo){

        if(StrUtil.isEmpty(token)){
            return ResultUtil.put(ConstantUtil.JWT_CODE_FAIL, "BUSINESS.TOKEN", "");
        }

        // 初始化数据
        globalSettingItemMapper.delete();

        LocalUser user = UserUtil.getLocalUser(token);

        globalSettingItemVo.setId(Uuid.getUUID());
        if(user != null){
            globalSettingItemVo.setCreateUser(user.getUid());
            globalSettingItemVo.setCreateTime(LocalDateTime.now());
        }

        GlobalSettingItem gsi = new GlobalSettingItem();
        BeanUtils.copyProperties(globalSettingItemVo, gsi);
        this.add(gsi);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.INSERT.SUCCESS", gsi);
    }
}
