package com.changfa.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changfa.enums.StatusEnum;
import com.changfa.dto.SaveUserDto;
import com.changfa.entity.TUser;
import com.changfa.entity.TUserRole;
import com.changfa.exception.BuzEx;
import com.changfa.mapper.TUserMapper;
import com.changfa.mapper.TUserRoleMapper;
import com.changfa.service.ITUserService;
import com.changfa.utils.BCrypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wwz
 * @since 2022-06-24
 */
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService {

    @Autowired
    private TUserRoleMapper userRoleMapper;

    /**
     * 删除对应的用户以及角色
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public boolean deleteUser(Integer userId) {
        if(this.baseMapper.deleteById(userId) > 0){
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("user_id",userId);
            userRoleMapper.delete(wrapper);
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveUser(SaveUserDto saveUserDto) {
        TUser tUser = new TUser();
        String salt =  BCrypt.gensalt();
        BeanUtils.copyProperties(saveUserDto,tUser);
        tUser.setSalt(salt);
        tUser.setPassword(BCrypt.hashpw( saveUserDto.getPassword(),salt));
        tUser.fillCreated();
        tUser.setId(saveUserDto.getUserId());
        if(saveOrUpdate(tUser)){
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("user_id",tUser.getId());
            int result =  userRoleMapper.selectCount(wrapper);
            if(result != 0){
                userRoleMapper.delete(wrapper);
            }
            TUserRole userRole = new TUserRole();
            userRole.fillCreated();
            userRole.setUserId(tUser.getId());
            userRole.setRoleId(saveUserDto.getRoleId());
            if(retBool(userRoleMapper.insert(userRole))){
                return true;
            }
            throw new BuzEx(StatusEnum.FAIL);
        }
        return false;
    }

    @Override
    public Page selectUserPage(Page page, Wrapper wrapper) {
        page.setRecords(this.baseMapper.selectUserPage(page,wrapper));
        return page;
    }

    @Override
    @Transactional
    public void saveBatchByImport(List<?> list,boolean isBackMap){
       /* String defaultPwd = "123456";
        if(!ObjectUtils.isEmpty(list)){
            List<Map<String,Object>> dictList =  dictService.listByCache(DictConstants.DEFAULT_PASSWORD);
            if (!ObjectUtils.isEmpty(dictList)) {
                defaultPwd  = dictList.get(0).getOrDefault("value",defaultPwd).toString();
            }
            for(Object userVo:list){
                LinkedHashMap<String,Object>  linkedHashMap = (LinkedHashMap<String,Object>) userVo;
                TUser user = new TUser();
                List<String> collection = new ArrayList(linkedHashMap.values());
                user.setAccount(collection.get(1));
                user.setUserName(collection.get(0));
                String salt = BCrypt.gensalt();
                user.setSalt(salt);
                user.setPassword(BCrypt.hashpw(defaultPwd,salt));
                user.setStatus(1);
                user.fillCreated();
                QueryWrapper wrapper = new QueryWrapper();
                wrapper.eq("account",user.getAccount());
                if(this.baseMapper.selectCount(wrapper)>0){
                    logger.debug("存在相同用户，暂不处理");
                    continue;
                }
                if(this.baseMapper.insert(user) > 0){
                    wrapper = new QueryWrapper();
                    wrapper.eq("role_name",collection.get(2));
                    List<TRole> roles = this.roleMapper.selectList(wrapper);
                    if(!ObjectUtils.isEmpty(roles)){
                        TUserRole userRole = new TUserRole();
                        userRole.fillCreated();
                        userRole.setUserId(user.getId());
                        userRole.setRoleId(roles.get(0).getId());
                        userRoleMapper.insert(userRole);
                    }
                }
            }
        }*/
    }
}
