/*
 *
 *      Copyright (c) 2018-2025, hnqz All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: hnqz
 *
 */

package com.qunzhixinxi.hnqz.admin.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
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.qunzhixinxi.hnqz.admin.api.entity.SysRole;
import com.qunzhixinxi.hnqz.admin.api.vo.RoleVO;
import com.qunzhixinxi.hnqz.admin.service.SysRoleMenuService;
import com.qunzhixinxi.hnqz.admin.service.SysRoleService;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.log.annotation.SysLog;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author hnqz
 * @date 2020-02-10
 */
@RestController
@AllArgsConstructor
@RequestMapping("/role")
@Api(value = "role", tags = "角色管理模块")
public class SysRoleController {

	private final SysRoleService sysRoleService;

	private final SysRoleMenuService sysRoleMenuService;

	/**
	 * 通过ID查询角色信息
	 *
	 * @param id ID
	 * @return 角色信息
	 */
	@GetMapping("/{id}")
	public R getById(@PathVariable Integer id) {
		return R.ok(sysRoleService.getById(id));
	}

	/**
	 * 添加角色
	 *
	 * @param sysRole 角色信息
	 * @return success、false
	 */
	@SysLog("添加角色")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys_role_add')")
	public R save(@Valid @RequestBody SysRole sysRole) {
		return R.ok(sysRoleService.save(sysRole));
	}

	/**
	 * 修改角色
	 *
	 * @param sysRole 角色信息
	 * @return success/false
	 */
	@SysLog("修改角色")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys_role_edit')")
	public R update(@Valid @RequestBody SysRole sysRole) {
		return R.ok(sysRoleService.updateById(sysRole));
	}

	/**
	 * 删除角色
	 *
	 * @param id
	 * @return
	 */
	@SysLog("删除角色")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('sys_role_del')")
	public R removeById(@PathVariable Integer id) {
		return R.ok(sysRoleService.removeRoleById(id));
	}

	/**
	 * 获取角色列表
	 *
	 * @return 角色列表
	 */
	@GetMapping("/list")
	public R listRoles() {
		List<SysRole> roleList = sysRoleService.list(Wrappers.emptyWrapper());
		roleList.remove(0);
		List<Integer> roles = SecurityUtils.getRoles();
		if (roles.contains(3)) {
			roleList.remove(0);
		}

		if (roles.contains(4)) {
			roleList.remove(0);
			roleList.remove(0);
		}

		if (roles.contains(9)) {
			roleList.remove(0);
			roleList.remove(0);
			roleList.remove(0);
		}

		if (roles.contains(11)) {
			// 如果是患教管理员，则移除admin、平台管理员、药企
			roleList.remove(0);
			roleList.remove(0);
			roleList.remove(0);
		}
		return R.ok(roleList);
	}

	/**
	 * 获取角色列表（不包含admin管理员角色）
	 *
	 * 1.药企管理员：可见：
	 * 药企管理员
	 * CSO管理员
	 * 全职学术信息沟通专员
	 * 兼职学术信息沟通专员
	 * 财务管理员
	 *
	 *
	 * 2.CSO管理员：可见：
	 * CSO管理员
	 * 全职学术信息沟通专员
	 * 兼职学术信息沟通专员
	 * 财务管理员
	 *
	 *
	 * 3.CRO管理员：可见：
	 * CRO管理员
	 * 兼职CRC
	 * 财务管理员
	 *
	 *
	 * 4.患教管理员：可见：
	 * 患教管理员
	 * HCP
	 * 财务管理员
	 *
	 * 5.财务管理：可见：
	 * 财务管理员
	 *
	 * 6.平台管理员都可以看到
	 * @return 角色列表
	 */
	@GetMapping("/listRoleExcludeAdmin")
	public R listRoleExcludeAdmin() {

		// 获取当前登陆用户的角色列表
		List<Integer> rolesIdList = SecurityUtils.getRoles();

		// 平台管理员
		LambdaQueryWrapper<SysRole> queryWrapper = Wrappers.<SysRole>lambdaQuery();
		if (rolesIdList.contains(2)){
			queryWrapper.ne(SysRole::getRoleId, 1).orderByAsc(SysRole::getRoleId);
		} else if (rolesIdList.contains(1)){
			queryWrapper.orderByAsc(SysRole::getRoleId);
		} else {
			List<Integer> drugEntAdmin = Stream.of(3,4,5,6,7).collect(Collectors.toList());
			List<Integer> CSOAdmin = Stream.of(4,5,6,7).collect(Collectors.toList());
			List<Integer> CROAdmin = Stream.of(7,9,10).collect(Collectors.toList());
			List<Integer> HCPAdmin = Stream.of(7,11,13).collect(Collectors.toList());
			List<Integer> CFOAdmin = Stream.of(7).collect(Collectors.toList());

			Set<Integer> queryRoleIdSet = new HashSet<>();

			rolesIdList.forEach(id ->{
				switch (id){
					case 3:
						queryRoleIdSet.addAll(drugEntAdmin);
						break;
					case 4:
						queryRoleIdSet.addAll(CSOAdmin);
						break;
					case 7:
						queryRoleIdSet.addAll(CFOAdmin);
						break;
					case 9:
						queryRoleIdSet.addAll(CROAdmin);
						break;
					case 11:
						queryRoleIdSet.addAll(HCPAdmin);
						break;
				}
			});
			queryWrapper.in(SysRole::getRoleId, queryRoleIdSet).orderByAsc(SysRole::getRoleId);
		}

		List<SysRole> list = sysRoleService.list(queryWrapper);
		return R.ok(list);
	}

	/**
	 * 分页查询角色信息
	 *
	 * @param page 分页对象
	 * @return 分页对象
	 */
	@GetMapping("/page")
	public R getRolePage(Page page) {
		return R.ok(sysRoleService.page(page, Wrappers.emptyWrapper()));
	}

	/**
	 * 更新角色菜单
	 *
	 * @param roleVo 角色对象
	 * @return success、false
	 */
	@SysLog("更新角色菜单")
	@PutMapping("/menu")
	@PreAuthorize("@pms.hasPermission('sys_role_perm')")
	public R saveRoleMenus(@RequestBody RoleVO roleVo) {
		SysRole sysRole = sysRoleService.getById(roleVo.getRoleId());
		return R.ok(sysRoleMenuService.saveRoleMenus(sysRole.getRoleCode(), roleVo.getRoleId(), roleVo.getMenuIds()));
	}

	/**
	 * 通过角色ID 查询角色列表
	 *
	 * @param roleIdList 角色ID
	 * @return
	 */
	@PostMapping("/getRoleList")
	public R getRoleList(@RequestBody List<String> roleIdList) {
		return R.ok(sysRoleService.listByIds(roleIdList));
	}

}
