package com.njcn.product.cnuser.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.product.cnuser.user.mapper.SysRoleMapper;
import com.njcn.product.cnuser.user.pojo.constant.RoleConst;
import com.njcn.product.cnuser.user.pojo.enums.UserResponseEnum;
import com.njcn.product.cnuser.user.pojo.param.SysRoleParam;
import com.njcn.product.cnuser.user.pojo.po.SysRole;
import com.njcn.product.cnuser.user.service.ISysRoleFunctionService;
import com.njcn.product.cnuser.user.service.ISysRoleService;
import com.njcn.product.cnuser.user.service.ISysUserRoleService;
import com.njcn.web.factory.PageFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author caozehui
 * @date 2024-11-11
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    private final ISysUserRoleService sysUserRoleService;
    private final ISysRoleFunctionService sysRoleFunctionService;

    @Override
    public Page<SysRole> listRole(SysRoleParam.QueryParam queryParam) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(queryParam)) {
            queryWrapper.like(StrUtil.isNotBlank(queryParam.getName()), "sys_role.name", queryParam.getName()).eq(StrUtil.isNotBlank(queryParam.getCode()), "sys_role.code", queryParam.getCode()).eq(ObjectUtil.isNotNull(queryParam.getType()), "sys_role.type", queryParam.getType());
        }
//        if (queryParam.getType().equals(0)) {
//            queryWrapper.in("sys_role.type", queryParam.getType(), 1);
//        } else if (queryParam.getType().equals(1)) {
//            queryWrapper.eq("sys_role.type", 2);
//        }
        queryWrapper.eq("sys_role.state", DataStateEnum.ENABLE.getCode()).orderByDesc("sys_role.Update_Time");
        return this.baseMapper.selectPage(new Page<>(PageFactory.getPageNum(queryParam), PageFactory.getPageSize(queryParam)), queryWrapper);
    }

    @Override
    @Transactional
    public boolean addRole(SysRoleParam sysRoleParam) {
        sysRoleParam.setName(sysRoleParam.getName().trim());
        checkRepeat(sysRoleParam, false);
        SysRole role = new SysRole();
        BeanUtil.copyProperties(sysRoleParam, role);
        //默认为正常状态
        role.setState(DataStateEnum.ENABLE.getCode());
        return this.save(role);
    }

    @Override
    @Transactional
    public boolean updateRole(SysRoleParam.UpdateParam updateParam) {
        updateParam.setName(updateParam.getName().trim());
        checkRepeat(updateParam, true);
        //不能修改超级管理员角色
        Integer count = this.lambdaQuery()
                .in(SysRole::getType, RoleConst.TYPE_SUPER_ADMINISTRATOR)
                .eq(SysRole::getId, updateParam.getId()).eq(SysRole::getState, DataStateEnum.ENABLE.getCode()).count();
        if (count > 0) {
            throw new BusinessException(UserResponseEnum.SUPER_ADMINSTRATOR_ROLE_CANNOT_UPDATE);
        }
        SysRole role = new SysRole();
        BeanUtil.copyProperties(updateParam, role);
        return this.updateById(role);
    }

    @Override
    @Transactional
    public boolean deleteRole(List<String> ids) {
        //不能删除超级管理员角色
        Integer count = this.lambdaQuery()
                .in(SysRole::getType, RoleConst.TYPE_SUPER_ADMINISTRATOR)
                .in(SysRole::getId, ids).eq(SysRole::getState, DataStateEnum.ENABLE.getCode()).count();
        if (count > 0) {
            throw new BusinessException(UserResponseEnum.SUPER_ADMINSTRATOR_ROLE_CANNOT_DELETE);
        }
        // 删除角色和用户的绑定
        sysUserRoleService.deleteUserRoleByRoleIds(ids);
        //删除角色和资源的绑定
        sysRoleFunctionService.deleteRoleFunctionByRoleIds(ids);
        return this.lambdaUpdate().set(SysRole::getState, DataStateEnum.DELETED.getCode()).in(SysRole::getId, ids).update();
    }

    @Override
    public List<SysRole> simpleList() {
        LambdaQueryWrapper<SysRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(SysRole::getId, SysRole::getName).eq(SysRole::getState, DataStateEnum.ENABLE.getCode());
        return this.baseMapper.selectList(lambdaQueryWrapper);
    }

    /**
     * 校验参数，检查是否存在相同名称或编码的角色
     */
    private void checkRepeat(SysRoleParam roleParam, boolean isExcludeSelf) {
        LambdaQueryWrapper<SysRole> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper
                .eq(SysRole::getState, DataStateEnum.ENABLE.getCode())
                .and(w -> w.eq(SysRole::getName, roleParam.getName()).or().eq(SysRole::getCode, roleParam.getCode()));
        //更新的时候，需排除当前记录
        if (isExcludeSelf) {
            if (roleParam instanceof SysRoleParam.UpdateParam) {
                roleLambdaQueryWrapper.ne(SysRole::getId, ((SysRoleParam.UpdateParam) roleParam).getId());
            }
        }
        int countByAccount = this.count(roleLambdaQueryWrapper);
        //大于等于1个则表示重复
        if (countByAccount >= 1) {
            throw new BusinessException(UserResponseEnum.NAME_OR_CODE_REPEAT);
        }
    }
}
