package com.hotent.orgext.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.annotation.DataPermission;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.controller.BaseController;
import com.hotent.base.feign.UCFeignService;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.*;
import com.hotent.base.util.BeanUtils;
import com.hotent.base.util.StringUtil;
import com.hotent.base.util.UniqueIdUtil;
import com.hotent.orgext.manager.OrgAuthExtManager;
import com.hotent.orgext.model.OrgAuthExt;
import com.hotent.orgext.vo.AppModelVo;
import com.hotent.orgext.vo.RoleVo;
import com.hotent.orgext.vo.SysAppVo;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.manager.OrgManager;
import com.hotent.uc.manager.RoleManager;
import com.hotent.uc.model.Org;
import com.hotent.uc.model.Role;
import com.hotent.uc.util.ContextUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分级组织和角色/菜单/应用授权表
 * @author: 梁宏锦
 * @date: 2024/07/13
 **/
@RestController
@RequestMapping("/api/orgAuthExt/v1/")
@Api(tags = "分级组织和角色/菜单/应用授权表")
@ApiGroup(group= {ApiGroupConsts.GROUP_UC})
public class OrgAuthExtController extends BaseController<OrgAuthExtManager, OrgAuthExt> {
	private final Logger logger= LoggerFactory.getLogger(this.getClass());
	@Resource
	UCFeignService ucFeignService;
	@Autowired
	OrgManager orgService;
	@Autowired
	OrgAuthExtManager orgAuthExtManager;
	@Resource
	RoleManager roleService;

	/**
	 * 保存 组织和菜单关系信息
	 */
	@PostMapping(value="/saveMenu")
	@ApiOperation(value = "保存 组织和菜单关系信息", httpMethod = "POST", notes = "保存 组织和菜单关系信息")
	public CommonResult<String> saveMenu(@ApiParam(name="json", value="菜单授权json", required = true)@RequestBody String json) throws Exception{
		JSONObject jsonObj = JSONUtil.parseObj(json);
		JSONArray arrMenuAlias = jsonObj.getJSONArray("arrMenuAlias");
		String orgId = jsonObj.getStr("orgId");
		orgAuthExtManager.removeByOrgIdAndType(orgId, OrgAuthExt.AUTH_TYPE_MENU);

		List<OrgAuthExt> list = new ArrayList<>();
		LocalDateTime date = LocalDateTime.now();
		for (int i = 0; i < arrMenuAlias.size(); i++) {
			String menuAlias = arrMenuAlias.getStr(i);
			OrgAuthExt ext = new OrgAuthExt();
			ext.setId(UniqueIdUtil.getSuid());
			ext.setOrgId(orgId);
			ext.setMenuAlias(menuAlias);
			ext.setAuthType(OrgAuthExt.AUTH_TYPE_MENU);
			ext.setCreateTime(date);
			list.add(ext);
		}
		if(list.size()>0){
			orgAuthExtManager.saveBatch(list);
		}
		return new CommonResult<String>(true,"保存组织和菜单关系成功！");
	}

	/**
	 * 保存 组织和角色信息
	 */
	@PostMapping(value="/saveRole")
	@ApiOperation(value = "保存组织和角色关系信息", httpMethod = "POST", notes = "保存组织和角色关系信息")
	public CommonResult<String> saveRole(
			@ApiParam(name="orgId",value="组织id", required = true)@RequestParam(required=true) String orgId,
			@ApiParam(name="roleId",value="角色id", required = true)@RequestParam(required=true) String roleId) throws Exception{
		LambdaQueryWrapper<OrgAuthExt> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(OrgAuthExt::getAuthType, OrgAuthExt.AUTH_TYPE_ROLE);
		queryWrapper.eq(OrgAuthExt::getOrgId, orgId);
		queryWrapper.eq(OrgAuthExt::getRoleId, roleId);
		List<OrgAuthExt> list = orgAuthExtManager.list(queryWrapper);
		if(list==null || list.size()==0) {
			String id = UniqueIdUtil.getSuid();
			OrgAuthExt ext = new OrgAuthExt();
			ext.setId(id);
			ext.setOrgId(orgId);
			ext.setRoleId(roleId);
			ext.setAuthType(OrgAuthExt.AUTH_TYPE_ROLE);
			ext.setCreateTime(LocalDateTime.now());
			orgAuthExtManager.saveOrUpdate(ext);
		}
		return new CommonResult<String>(true,"保存组织和角色关系成功！");
	}

	/**
	 * 删除 组织和角色关系
	 */
	@RequestMapping(value="deleteRoleByIds",method=RequestMethod.DELETE, produces = {"application/json; charset=utf-8" })
	@ApiOperation(value = "删除 组织和角色关系", httpMethod = "DELETE", notes = "删除 组织和角色关系")
	@DataPermission
	public CommonResult<String> deleteRoleByIds(
			@ApiParam(name="extOrgId",value="扩展组织id", required = true)@RequestParam(required=false) String extOrgId,
			@ApiParam(name="ids",value="角色id（多个用,号隔开）", required = true) @RequestParam String ids) throws Exception{
		String[] idArray = ids.split(",");
		for (int i = 0; i < idArray.length; i++) {
			String id = idArray[i];
			orgAuthExtManager.removeByOrgIdAndRoleId(extOrgId, id);
		}
		return new CommonResult<String>(true,"删除 组织和角色关系成功！");
	}

	/**
	 * 保存 组织和PC/mobile/flow应用关系信息
	 */
	@PostMapping(value="/savePcApp")
	@ApiOperation(value = "保存组织和PC/mobile/flow应用关系信息", httpMethod = "POST", notes = "保存组织和PC/mobile/flow应用关系信息")
	public CommonResult<String> savePcApp(@ApiParam(name="json", value="PC应用授权json", required = true)@RequestBody String json) throws Exception{
		JSONObject jsonObj = JSONUtil.parseObj(json);
		String appId = jsonObj.getStr("appId");
		String appType = jsonObj.getStr("appType");
		JSONArray arrOrgIds = jsonObj.getJSONArray("orgIds");
		if(!OrgAuthExt.AUTH_TYPE_PC_APP.equals(appType) && !OrgAuthExt.AUTH_TYPE_MOBILE_APP.equals(appType)) {
			return new CommonResult<String>(false,"应用类型错误！");
		}
		if(StringUtil.isEmpty(appId)) {
			return new CommonResult<String>(false,"应用ID不能为空！");
		}
		orgAuthExtManager.removeByAppIdAndType(appId, appType);

		List<String> orgIdsList = new ArrayList<>();
		for (int i = 0; i < arrOrgIds.size(); i++) {
			String orgId = arrOrgIds.getStr(i);
			if (!orgIdsList.contains(orgId)) {
				orgIdsList.add(orgId);
			}
		}

		List<OrgAuthExt> list = new ArrayList<>();
		LocalDateTime date = LocalDateTime.now();
		for (int i = 0; i < orgIdsList.size(); i++) {
			String orgId = orgIdsList.get(i);
			String id = UniqueIdUtil.getSuid();
			OrgAuthExt ext = new OrgAuthExt();
			ext.setId(id);
			ext.setOrgId(orgId);
			if(OrgAuthExt.AUTH_TYPE_PC_APP.equals(appType)) {
				ext.setPcAppId(appId);
			} else if(OrgAuthExt.AUTH_TYPE_MOBILE_APP.equals(appType)) {
				ext.setMobileAppId(appId);
			}
			ext.setAuthType(appType);
			ext.setCreateTime(date);
			list.add(ext);
			//LambdaQueryWrapper<OrgAuthExt> queryWrapper = Wrappers.lambdaQuery();
			//queryWrapper.eq(OrgAuthExt::getAuthType, OrgAuthExt.AUTH_TYPE_PC_APP);
			//queryWrapper.eq(OrgAuthExt::getOrgId, orgId);
			//queryWrapper.eq(OrgAuthExt::getPcAppId, appId);
			//List<OrgAuthExt> list = orgAuthExtManager.list(queryWrapper);
			//if(list==null || list.size()==0) {
			//	String id = UniqueIdUtil.getSuid();
			//	OrgAuthExt ext = new OrgAuthExt();
			//	ext.setId(id);
			//	ext.setOrgId(orgId);
			//	ext.setPcAppId(appId);
			//	ext.setAuthType(OrgAuthExt.AUTH_TYPE_PC_APP);
			//	ext.setCreateTime(date);
			//	orgAuthExtManager.saveOrUpdate(ext);
			//}
		}
		if(list.size()>0){
			orgAuthExtManager.saveBatch(list);
		}
		return new CommonResult<String>(true,"保存组织和PC应用关系成功！");
	}

//	/**
//	 * 保存 组织和移动应用关系信息
//	 */
//	@PostMapping(value="/saveMobileApp")
//	@ApiOperation(value = "保存组织和移动应用关系信息", httpMethod = "POST", notes = "保存组织和移动应用关系信息")
//	public CommonResult<String> saveMobileApp(
//			@ApiParam(name="orgId",value="组织id", required = true)@RequestParam(required=true) String orgId,
//			@ApiParam(name="mobileAppId",value="移动应用id", required = true)@RequestParam(required=true) String mobileAppId) throws Exception{
//		String[] mobileAppArr = mobileAppId.split(",");
//		for (int i = 0; i < mobileAppArr.length ; i++) {
//			String appId = mobileAppArr[i];
//			LambdaQueryWrapper<OrgAuthExt> queryWrapper = Wrappers.lambdaQuery();
//			queryWrapper.eq(OrgAuthExt::getAuthType, OrgAuthExt.AUTH_TYPE_MOBILE_APP);
//			queryWrapper.eq(OrgAuthExt::getOrgId, orgId);
//			queryWrapper.eq(OrgAuthExt::getMobileAppId, appId);
//			List<OrgAuthExt> list = orgAuthExtManager.list(queryWrapper);
//			if (list == null || list.size() == 0) {
//				String id = UniqueIdUtil.getSuid();
//				OrgAuthExt ext = new OrgAuthExt();
//				ext.setId(id);
//				ext.setOrgId(orgId);
//				ext.setMobileAppId(appId);
//				ext.setAuthType(OrgAuthExt.AUTH_TYPE_MOBILE_APP);
//				ext.setCreateTime(LocalDateTime.now());
//				orgAuthExtManager.saveOrUpdate(ext);
//			}
//		}
//		return new CommonResult<String>(true,"保存组织和移动应用关系成功！");
//	}

	@RequestMapping(value="remove",method=RequestMethod.DELETE, produces = { "application/json; charset=utf-8" })
	@ApiOperation(value = "删除关系记录", httpMethod = "DELETE", notes = "删除关系记录")
	public CommonResult<String> remove(@ApiParam(name="ids",value="任务记录ID，多个用“,”号分隔", required = true) @RequestParam String ids) throws Exception{
		String[] aryIds = null;
		if(!StringUtil.isEmpty(ids)){
			aryIds = ids.split(",");
		}
		orgAuthExtManager.removeByIds(Arrays.asList(aryIds));
		return new CommonResult<String>(true,"删除关系成功","");
	}

	/**
	 * 查询角色(组织授权扩展)
	 */
	@RequestMapping(value="getRoleAuthExtPage",method=RequestMethod.POST, produces = {"application/json; charset=utf-8" })
	@ApiOperation(value = "获取角色分页列表(组织授权扩展)", httpMethod = "POST", notes = "获取角色分页列表(组织授权扩展)")
	//@DataPermission
	public PageList<RoleVo> getRoleAuthExtPage(@ApiParam(name = "filter", value = "查询参数", required = true) @RequestBody QueryFilter filter) throws Exception{
		PageList<RoleVo> list = orgAuthExtManager.queryRoleAuthExt(filter);
		return list;
	}

	/**
	 * 查询角色详情(组织授权扩展)
	 */
	@RequestMapping(value="getRoleAuthExt",method=RequestMethod.GET, produces = {"application/json; charset=utf-8" })
	@ApiOperation(value = "查询角色详情(组织授权扩展)", httpMethod = "GET", notes = "查询角色详情(组织授权扩展)")
	//@DataPermission
	public CommonResult<RoleVo> getRoleAuthExt(@ApiParam(name="code",value="角色编码", required = true) @RequestParam String code) throws Exception{
		if(StringUtil.isEmpty(code)){
			return new CommonResult<RoleVo>(false, "角色编码必填！", null);
		}
		Role r = roleService.getByAlias(code);
		if(BeanUtils.isEmpty(r)){
			r = roleService.get(code);
		}
		if(BeanUtils.isEmpty(r)){
			return new CommonResult<RoleVo>(false, "根据输入的编码没有找到对应的角色", null);
		}

		RoleVo vo = new RoleVo();
		BeanUtils.copyNotNullProperties(vo, r);
		LambdaQueryWrapper<OrgAuthExt> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(OrgAuthExt::getRoleId, r.getId());
		queryWrapper.eq(OrgAuthExt::getAuthType, OrgAuthExt.AUTH_TYPE_ROLE);
		List<OrgAuthExt> extList = orgAuthExtManager.getBaseMapper().selectList(queryWrapper);
		if(extList==null && extList.size()<=0) {
			return new CommonResult<RoleVo>(false, "没有找到对应的组织角色信息", null);
		} else {
			OrgAuthExt ext = extList.get(0);
			vo.setExtId(ext.getId());
			vo.setExtOrgId(ext.getOrgId());
			return new CommonResult<RoleVo>(true, "获取角色明细成功", vo);
		}
	}

	//查询组织和PC应用关系信息(组织授权扩展)
	@RequestMapping(value="getSysAppAuthExtPage",method=RequestMethod.POST, produces = {"application/json; charset=utf-8" })
	@ApiOperation(value = "查询组织和PC应用关系信息(组织授权扩展)", httpMethod = "POST", notes = "查询组织和PC应用关系信息(组织授权扩展)")
	//@DataPermission
	public PageList<SysAppVo> getSysAppAuthExtPage(@ApiParam(name = "filter", value = "查询参数", required = true) @RequestBody QueryFilter filter) throws Exception{
		PageList<SysAppVo> list = orgAuthExtManager.getSysAppAuthExtPage(filter);
		return list;
	}

	/**
	 * 查询组织和PC应用关系信息 添加范围
	 */
	@RequestMapping(value="querySysAppExtList",method=RequestMethod.POST, produces = {"application/json; charset=utf-8" })
	@ApiOperation(value = "查询组织和PC应用关系信息 添加范围", httpMethod = "POST", notes = "查询组织和PC应用关系信息 添加范围")
	//@DataPermission
	public PageList<SysAppVo> querySysAppExtList(
			@ApiParam(name="orgId",value="组织id", required = true)@RequestParam(required=true) String orgId,
			@ApiParam(name = "filter", value = "查询参数", required = true) @RequestBody QueryFilter filter) throws Exception{
		IUser user = ContextUtil.getCurrentUser(); //获取当前用户
		Org org = orgService.getById(orgId);
		String parentId = org.getParentId();
		if("0".equals(parentId)) {
			//第一层组织
			if(user.isAdmin()) {
				PageList<SysAppVo> list = orgAuthExtManager.querySysAppExtListFirst(filter, orgId);
				return list;
			} else {
				PageList<SysAppVo> list = orgAuthExtManager.querySysAppExtListFirst(filter, orgId);
				return list;
			}
		} else {
			PageList<SysAppVo> list = orgAuthExtManager.querySysAppExtListOther(filter, parentId, orgId);
			return list;
		}
	}

	//查询组织和移动应用关系信息(组织授权扩展)
	@RequestMapping(value="getMobileAppAuthExtPage",method=RequestMethod.POST, produces = {"application/json; charset=utf-8" })
	@ApiOperation(value = "查询组织和移动应用关系信息(组织授权扩展)", httpMethod = "POST", notes = "查询组织和移动应用关系信息(组织授权扩展)")
	//@DataPermission
	public PageList<AppModelVo> getMobileAppAuthExtPage(@ApiParam(name = "filter", value = "查询参数", required = true) @RequestBody QueryFilter filter) throws Exception{
		PageList<AppModelVo> list = orgAuthExtManager.getMobileAppAuthExtPage(filter);
		return list;
	}

	/**
	 * 查询组织和移动应用关系信息 添加范围
	 */
	@RequestMapping(value="queryMobileAppExtList",method=RequestMethod.POST, produces = {"application/json; charset=utf-8" })
	@ApiOperation(value = "查询组织和PC应用关系信息 添加范围", httpMethod = "POST", notes = "查询组织和PC应用关系信息 添加范围")
	//@DataPermission
	public PageList<AppModelVo> queryMobileAppExtList(
			@ApiParam(name="orgId",value="组织id", required = true)@RequestParam(required=true) String orgId,
			@ApiParam(name = "filter", value = "查询参数", required = true) @RequestBody QueryFilter filter) throws Exception{
		IUser user = ContextUtil.getCurrentUser(); //获取当前用户
		Org org = orgService.getById(orgId);
		String parentId = org.getParentId();
		if("0".equals(parentId)) {
			//第一层组织
			if(user.isAdmin()) {
				PageList<AppModelVo> list = orgAuthExtManager.queryMobileAppExtListFirst(filter, orgId);
				return list;
			} else {
				PageList<AppModelVo> list = orgAuthExtManager.queryMobileAppExtListFirst(filter, orgId);
				return list;
			}
		} else {
			PageList<AppModelVo> list = orgAuthExtManager.queryMobileAppExtListOther(filter, parentId, orgId);
			return list;
		}
	}

	@RequestMapping(value="queryExtAuthAppIdByOrgIds",method=RequestMethod.POST, produces = {"application/json; charset=utf-8" })
	@ApiOperation(value = "通过组织id 查询授权应用id", httpMethod = "POST", notes = "通过组织id 查询授权应用id")
	public String queryExtAuthAppIdByOrgIds(
			@ApiParam(name="authType",value="授权类型", required = true)@RequestParam(required=true) String authType,
			@ApiParam(name="orgIds",value="组织ids(逗号分隔)", required = true)@RequestParam(required=true) String orgIds) throws Exception{
		List<String> orgIdList = Arrays.stream(orgIds.split(",")).collect(Collectors.toList());
		if(orgIdList==null || orgIdList.size()==0) {
			return "";
		}
		LambdaQueryWrapper<OrgAuthExt> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(OrgAuthExt::getAuthType, authType);
		queryWrapper.in(OrgAuthExt::getOrgId, orgIdList);
		List<OrgAuthExt> list = orgAuthExtManager.list(queryWrapper);

		List<String> appIdList = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			OrgAuthExt ext = list.get(i);
			if(OrgAuthExt.AUTH_TYPE_PC_APP.equals(authType)) {
				appIdList.add(ext.getPcAppId());
			} else if(OrgAuthExt.AUTH_TYPE_MOBILE_APP.equals(authType)) {
				appIdList.add(ext.getMobileAppId());
			}
		}
		return String.join(",", appIdList);
	}
}
