package com.oauth.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.framework.core.exception.StarBosException;
import com.framework.core.response.StarBosResult;
import com.framework.core.utils.PrincipalUtil;
import com.oauth.system.dto.AuthAccountDTO;
import com.oauth.system.entity.SysUserAccount;
import com.oauth.system.entity.SysUserRole;
import com.oauth.system.service.ISysUserRoleService;
import com.oauth.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author
 * @date 2022/7/15
 */
@Component
@Slf4j
public class AccountServiceImpl{

    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    public PasswordEncoder passwordEncoder;


    @Transactional(rollbackFor = Exception.class)
    public StarBosResult<Long> save(AuthAccountDTO authAccountDTO) {
//        生成分布式id
//        StarBosResult<Long> segmentIdResponse = segmentFeignClient.getSegmentId(SysUserAccount.DISTRIBUTED_ID_KEY);
//        if (!segmentIdResponse.isSuccess()) {
//            throw new StarBosException(StarBosResultEnum.EXCEPTION);
//        }

        StarBosResult<SysUserAccount> verify = verify(authAccountDTO);
        if (!verify.isSuccess()) {
            return StarBosResult.transform(verify);
        }
        SysUserAccount data = verify.getData();
        sysUserService.save(data);

        return StarBosResult.success(data.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    public StarBosResult<Void> deleteByUserId(Long userId) {
        sysUserRoleService.deleteRoleUserRelation(userId);
        boolean b = sysUserService.removeById(userId);
        if (!b) {
            throw new StarBosException("账号删除失败");
        }
        return StarBosResult.success();
    }

    @Transactional(rollbackFor = Exception.class)
    public StarBosResult<Void> editUserRole(Long userid, List<String> roles) {
//        try {
            sysUserRoleService.getBaseMapper().delete(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, userid));
            if (null != roles) {
                for (String roleId : roles) {
                    SysUserRole userRole = new SysUserRole(userid, Long.valueOf(roleId));
                    sysUserRoleService.getBaseMapper().insert(userRole);
                }
            }
//        } catch (Exception e) {
////            捕捉异常回滚
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
////
//            throw new StarBosException("绑定角色失败");
//        } finally {
//
//        }
        return StarBosResult.success();
    }

    private StarBosResult<SysUserAccount> verify(AuthAccountDTO authAccountDTO) {
        // 账号名
        if (!PrincipalUtil.isUserName(authAccountDTO.getUsername())) {
            return StarBosResult.fail("账号格式不正确");
        }
        SysUserAccount userNameBo = sysUserService.findByUsername(authAccountDTO.getUsername());
        if (userNameBo != null) {
            return StarBosResult.fail("账号已存在，请更换账号名再次尝试");
        }
        SysUserAccount authAccount = mapperFacade.map(authAccountDTO, SysUserAccount.class);

        if (StrUtil.isNotBlank(authAccount.getPassword())) {
            authAccount.setPassword(passwordEncoder.encode(authAccount.getPassword()));
        }
        return StarBosResult.success(authAccount);
    }
}
