package com.cyksj.web.controller.manage.cms;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.manage.cms.CmsRoleMapper;
import com.cyksj.mapper.manage.cms.CmsRoleMenuMapper;
import com.cyksj.model.entity.CmsRole;
import com.cyksj.model.entity.CmsRoleMenu;
import com.cyksj.model.entity.CmsUser;
import com.cyksj.model.request.CmsRoleReq;
import com.cyksj.service.mange.cms.CmsUserManager;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/*
 *项目名: netflix
 *文件名: CmsRoleController
 *创建者: JavaZou
 *创建时间:2023/1/11 14:26
 */
@RestController
@RequestMapping("/manage/role")
@RequiredArgsConstructor
@Slf4j
public class CmsRoleController {
	private final CmsRoleMapper cmsRoleMapper;

	private final CmsRoleMenuMapper cmsRoleMenuMapper;

	private final CmsUserManager cmsUserManager;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	@PostMapping("/post")
	public Result<String> addRole(@RequestBody @Validated CmsRoleReq cmsRoleReq) {
		try {
			CmsRole cmsRole = new CmsRole();
			BeanUtils.copyProperties(cmsRoleReq, cmsRole);
			cmsRoleMapper.insert(cmsRole);
			cmsRoleReq.setId(cmsRole.getId());
			if (StrUtil.isNotEmpty(cmsRoleReq.getMenuIds())) {
				saveRoleMenuRelation(cmsRoleReq);
			}
		} catch (DuplicateKeyException keyEx) {
			throw BusinessRuntimeException.getInstance("角色名重复");
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult("新增角色成功");
	}

	@PostMapping("/put")
	public Result<String> putRole(@RequestBody CmsRoleReq cmsRoleReq) throws Exception {
		if (cmsRoleReq.getId() == null || cmsRoleReq.getId() < 0) {
			throw BusinessRuntimeException.getInstance("角色不存在");
		}
		if (StrUtil.isEmpty(cmsRoleReq.getMenuIds())) {
			throw BusinessRuntimeException.getInstance("请选择对应的菜单");
		}
		CmsRole cmsRole = cmsRoleMapper.selectById(cmsRoleReq.getId());
		Boolean isFlag = false;
		if (StrUtil.isNotBlank(cmsRoleReq.getRoleName())) {
			cmsRole.setRoleName(cmsRoleReq.getRoleName());
			isFlag = true;
		}
		if (StrUtil.isNotBlank(cmsRoleReq.getRemark())) {
			cmsRole.setRemark(cmsRoleReq.getRemark());
			isFlag = true;
		}
		if (isFlag) {
			cmsRoleMapper.updateById(cmsRole);
		}
		cmsRoleMenuMapper.delete(Wrappers.lambdaQuery(CmsRoleMenu.class).eq(CmsRoleMenu::getRoleId, cmsRoleReq.getId()));
		if (StrUtil.isNotBlank(cmsRoleReq.getMenuIds())) {
			this.saveRoleMenuRelation(cmsRoleReq);
		}
		//查出所关联该角色的所有用户
		List<CmsUser> cmsUserList = cmsRoleMapper.getAllCmsUserByRoleId(cmsRoleReq.getId());
		if (cmsUserList != null) {
			for (CmsUser cmsUser : cmsUserList) {
				//更新缓存
				cmsUserManager.loadUserRedisCache(cmsUser);
			}
		}
		return GatewayResponse.SUCCESS.newBuilder().toResult("更新角色成功");
	}

	@DeleteMapping("/delete/{id}")
	public Result<String> delRoleById(@PathVariable("id") Long id) {
		if (id == null || id < 0) {
			throw BusinessRuntimeException.getInstance("角色不存在");
		}
		List<CmsUser> cmsUserList = cmsRoleMapper.getAllCmsUserByRoleId(id);
		if (null != cmsUserList && !cmsUserList.isEmpty()) {
			throw BusinessRuntimeException.getInstance("请先删除该角色关联下的用户");
		}
		cmsRoleMenuMapper.delete(Wrappers.lambdaQuery(CmsRoleMenu.class).eq(CmsRoleMenu::getRoleId, id));
		cmsRoleMapper.deleteById(id);
		return GatewayResponse.SUCCESS.newBuilder().toResult("删除角色成功");
	}


	@GetMapping("/get")
	public Result<SearchResult<CmsRole>> getRoleList() {
		SearchResult<CmsRole> search = beanSearcher.search(CmsRole.class, MapUtils.flatBuilder(request.getParameterMap()).build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}
	@GetMapping("/get/menu")
	public Result<List<String>> getMenuByRoleId(String roleId) {
		if (StrUtil.isEmpty(roleId)) {
			throw BusinessRuntimeException.getInstance("角色不存在");
		}
		//目前是单个角色
		List<String> menus = cmsRoleMapper.getAllMenusByRoleIds(roleId.split(","));
		return GatewayResponse.SUCCESS.newBuilder().toResult(menus);
	}

	@GetMapping("/get/detail/{roleId}")
	public Result<CmsRole> getDetailByRoleId(@PathVariable("roleId") Integer roleId) {
		return GatewayResponse.SUCCESS.newBuilder().toResult(cmsRoleMapper.selectById(roleId));
	}

	private void saveRoleMenuRelation(CmsRoleReq cmsRoleReq) {
		Arrays.stream(cmsRoleReq.getMenuIds().split(",")).forEach(menuId -> {
			cmsRoleMenuMapper.insert(new CmsRoleMenu(cmsRoleReq.getId(), Long.valueOf(menuId)));
		});
	}
}
