/*
 * Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yifu.cloud.plus.v1.yifu.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.plugin.excel.vo.ErrorMessage;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysRole;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysRoleMenu;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysUserRole;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.BusinessRoleMenuVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.RoleExcelVO;
import com.yifu.cloud.plus.v1.yifu.admin.mapper.SysRoleMapper;
import com.yifu.cloud.plus.v1.yifu.admin.mapper.SysRoleMenuMapper;
import com.yifu.cloud.plus.v1.yifu.admin.mapper.SysUserRoleMapper;
import com.yifu.cloud.plus.v1.yifu.admin.service.SysRoleService;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.ErrorCodes;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.MsgUtils;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.mybatis.base.BaseEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lengleng
 * @since 2019/2/1
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

	private final SysRoleMenuMapper sysRoleMenuMapper;

	private final SysUserRoleMapper sysUserRoleMapper;

	/**
	 * 通过角色ID，删除角色,并清空角色菜单缓存
	 * @param id
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
	public R<Boolean> removeRoleById(Long id) {
		SysRole sysRole = this.getById(id);
		if (Common.isEmpty(sysRole)){
			return R.failed();
		}
		SysUserRole userRole =sysUserRoleMapper.selectOne(Wrappers.<SysUserRole>query().lambda()
				.eq(SysUserRole::getRoleId,sysRole.getRoleId()).last(CommonConstants.LAST_ONE_SQL));
		//已存在用户
		if (!Common.isEmpty(userRole)){
			return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_ROLE_DELETE_EXIST_USER));
		}
		//系统内置
		if (CommonConstants.ZERO_STRING.equals(sysRole.getSystemFlag())){
			return  R.failed(MsgUtils.getMessage(ErrorCodes.SYS_ROLE_DELETE_SYSTEM));
		}
		sysRoleMenuMapper.delete(Wrappers.<SysRoleMenu>update().lambda().eq(SysRoleMenu::getRoleId, id));
		this.removeById(id);
		return R.ok();
	}

	/**
	 * 导入角色
	 * @param excelVOList 角色列表
	 * @param bindingResult 错误信息列表
	 * @return ok fail
	 */
	@Override
	public R importRole(List<RoleExcelVO> excelVOList, BindingResult bindingResult) {
		// 通用校验获取失败的数据
		List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();

		// 个性化校验逻辑
		List<SysRole> roleList = this.list();

		// 执行数据插入操作 组装 RoleDto
		for (int i = 0; i < excelVOList.size(); i++) {
			RoleExcelVO excel = excelVOList.get(i);
			Set<String> errorMsg = new HashSet<>();
			// 检验角色名称或者角色编码是否存在
			boolean existRole = roleList.stream().anyMatch(sysRole -> excel.getRoleName().equals(sysRole.getRoleName())
					|| excel.getRoleCode().equals(sysRole.getRoleCode()));

			if (existRole) {
				errorMsg.add(MsgUtils.getMessage(ErrorCodes.SYS_ROLE_NAMEORCODE_EXISTING, excel.getRoleName(),
						excel.getRoleCode()));
			}

			// 数据合法情况
			if (CollUtil.isEmpty(errorMsg)) {
				insertExcelRole(excel);
			}
			else {
				// 数据不合法情况
				errorMessageList.add(new ErrorMessage((long) (i + 2), errorMsg));
			}
		}
		if (CollUtil.isNotEmpty(errorMessageList)) {
			return R.failed(errorMessageList);
		}
		return R.ok();
	}

	/**
	 * 查询全部的角色
	 * @return list
	 */
	@Override
	public List<RoleExcelVO> listRole() {
		List<SysRole> roleList = this.list(Wrappers.emptyWrapper());
		// 转换成execl 对象输出
		return roleList.stream().map(role -> {
			RoleExcelVO roleExcelVO = new RoleExcelVO();
			BeanUtil.copyProperties(role, roleExcelVO);
			return roleExcelVO;
		}).collect(Collectors.toList());
	}

	@Override
	public Page<SysRole> getSysRoleByPage(Page page, SysRole sysRole) {
		return baseMapper.selectPage(page, buildQueryWrapper(sysRole));
	}
	/**
	 * 构建查询的 wrapper
	 * @param sysRole 查询条件
	 * @return LambdaQueryWrapper
	 */
	private LambdaQueryWrapper buildQueryWrapper(SysRole sysRole) {
		LambdaQueryWrapper<SysRole> wrapper = Wrappers.lambdaQuery();
		if (StrUtil.isNotBlank(sysRole.getRoleName())){
			wrapper.likeRight(SysRole::getRoleName,sysRole.getRoleName());
		}
		wrapper.orderByDesc(BaseEntity::getCreateTime);
		return wrapper;
	}
	/**
	 * 插入excel Role
	 */
	private void insertExcelRole(RoleExcelVO excel) {
		SysRole sysRole = new SysRole();
		sysRole.setRoleName(excel.getRoleName());
		sysRole.setRoleDesc(excel.getRoleDesc());
		sysRole.setRoleCode(excel.getRoleCode());
		this.save(sysRole);
	}

	@Override
	public void updateRoleById(SysRole sysRole) {
		String type = "0";
		// 系统内置
		Assert.state(!type.equals(sysRole.getSystemFlag()),
				MsgUtils.getMessage(ErrorCodes.SYS_ROLE_UPDATE_SYSTEM));
		this.updateById(sysRole);
	}
	/**
	 * @Author fxj
	 * @Description  验证角色名称和角色编码
	 * @Date 17:23 2022/6/14
	 * @Param type  0  名称 1  编码
	 * @return
	 **/
	@Override
	public R<Boolean> getBooleanR(SysRole sysRole) {
		SysRole role = baseMapper.selectOne(buildCheckQueryWrapper(sysRole,CommonConstants.ONE_STRING));

		if (Common.isNotNull(role) &&  Common.isNotNull(sysRole.getRoleCode())){
			return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_ROLE_UPDATE_ERROR_CODE_EXIST));
		}
		role = baseMapper.selectOne(buildCheckQueryWrapper(sysRole,CommonConstants.ZERO_STRING));
		if (Common.isNotNull(role) && Common.isNotNull(sysRole.getRoleName())){
			return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_ROLE_UPDATE_ERROR_NAME_EXIST));
		}
		return null;
	}
	private LambdaQueryWrapper buildCheckQueryWrapper(SysRole sysRole, String type) {
		LambdaQueryWrapper<SysRole> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(SysRole::getDelFlag,CommonConstants.ZERO_STRING);
		if (Common.isNotNull(sysRole.getRoleId())){
			wrapper.ne(SysRole::getRoleId,sysRole.getRoleId());
		}
		if (CommonConstants.ZERO_STRING.equals(type)){
			if (StrUtil.isNotBlank(sysRole.getRoleName())){
				wrapper.likeRight(SysRole::getRoleName,sysRole.getRoleName());
			}
		}
		if (CommonConstants.ONE_STRING.equals(type)){
			if (StrUtil.isNotBlank(sysRole.getRoleCode())){
				wrapper.likeRight(SysRole::getRoleCode,sysRole.getRoleCode());
			}
		}
		wrapper.last(CommonConstants.LAST_ONE_SQL);
		return wrapper;
	}

	@Override
	public List<BusinessRoleMenuVo> getRoleAndMenu(String type) {
		return baseMapper.getRoleAndMenu(type);
	}

	@Override
	public Set<String> getRoleByUserIdAndClient(Integer userId, String clientId) {
		return baseMapper.getRoleByUserIdAndClient(userId,clientId);
	}
}
