package org.sky.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.sky.core.boot.ctrl.KdController;
import org.sky.core.cache.utils.CacheUtil;
import org.sky.core.mp.support.Condition;
import org.sky.core.secure.KdUser;
import org.sky.core.secure.annotation.PreAuth;
import org.sky.core.secure.constant.AuthConstant;
import org.sky.core.tenant.annotation.NonDS;
import org.sky.core.tool.api.R;
import org.sky.core.tool.constant.KdConstant;
import org.sky.core.tool.support.Kv;
import org.sky.core.tool.utils.Func;
import org.sky.system.cache.DictCache;
import org.sky.system.cache.UserCache;
import org.sky.system.pojo.entity.Dept;
import org.sky.system.pojo.entity.User;
import org.sky.system.pojo.enums.DictEnum;
import org.sky.system.pojo.vo.DeptVO;
import org.sky.system.service.IDeptService;
import org.sky.system.wrapper.DeptWrapper;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

import static org.sky.core.cache.constant.CacheConstant.SYS_CACHE;

/**
 * 控制器
 *
 */
@NonDS
@RestController
@AllArgsConstructor
@RequestMapping("/dept")
@Tag(name = "部门", description = "部门")
public class DeptController extends KdController {

	private final IDeptService deptService;

	/**
	 * 详情
	 */
	@PreAuth(menu = "dept")
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入dept")
	public R<DeptVO> detail(Dept dept) {
		Dept detail = deptService.getOne(Condition.getQueryWrapper(dept));
		return R.data(DeptWrapper.build().entityVO(detail));
	}

	/**
	 * 列表
	 */
	@PreAuth(menu = "dept")
	@GetMapping("/list")
	@Parameters({
		@Parameter(name = "deptName", description = "部门名称", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
		@Parameter(name = "fullName", description = "部门全称", in = ParameterIn.QUERY, schema = @Schema(type = "string"))
	})
	@ApiOperationSupport(order = 2)
	@Operation(summary = "列表", description = "传入dept")
	public R<List<DeptVO>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> dept, KdUser kdUser) {
		QueryWrapper<Dept> queryWrapper = Condition.getQueryWrapper(dept, Dept.class);
		List<Dept> list = deptService.list((!kdUser.getTenantId().equals(KdConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Dept::getTenantId, kdUser.getTenantId()) : queryWrapper);
		return R.data(DeptWrapper.build().listNodeVO(list));
	}

	/**
	 * 懒加载列表
	 */
	@PreAuth(menu = "dept")
	@GetMapping("/lazy-list")
	@Parameters({
		@Parameter(name = "deptName", description = "部门名称", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
		@Parameter(name = "fullName", description = "部门全称", in = ParameterIn.QUERY, schema = @Schema(type = "string"))
	})
	@ApiOperationSupport(order = 3)
	@Operation(summary = "懒加载列表", description = "传入dept")
	public R<List<DeptVO>> lazyList(@Parameter(hidden = true) @RequestParam Map<String, Object> dept, Long parentId, KdUser kdUser) {
		List<DeptVO> list = deptService.lazyList(kdUser.getTenantId(), parentId, dept);
		return R.data(DeptWrapper.build().listNodeLazyVO(list));
	}

	/**
	 * 获取部门树形结构
	 */
	@PreAuth(menu = "dept")
	@GetMapping("/tree")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "树形结构", description = "树形结构")
	public R<List<DeptVO>> tree(String tenantId, KdUser kdUser) {
		List<DeptVO> tree = deptService.tree(Func.toStrWithEmpty(tenantId, kdUser.getTenantId()));
		return R.data(tree);
	}

	/**
	 * 懒加载获取部门树形结构
	 */
	@PreAuth(menu = "dept")
	@GetMapping("/lazy-tree")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "懒加载树形结构", description = "树形结构")
	public R<List<DeptVO>> lazyTree(String tenantId, Long parentId, KdUser kdUser) {
		List<DeptVO> tree = deptService.lazyTree(Func.toStrWithEmpty(tenantId, kdUser.getTenantId()), parentId);
		return R.data(tree);
	}

	/**
	 * 新增或修改
	 */
//	@IsAdmin
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "新增或修改", description = "传入dept")
	public R submit(@Valid @RequestBody Dept dept) {
		if (deptService.submit(dept)) {
			CacheUtil.clear(SYS_CACHE);
			CacheUtil.clear(SYS_CACHE, Boolean.FALSE);
			// 返回懒加载树更新节点所需字段
			Kv kv = Kv.create().set("id", String.valueOf(dept.getId())).set("tenantId", dept.getTenantId())
				.set("deptCategoryName", DictCache.getValue(DictEnum.ORG_CATEGORY, dept.getDeptCategory()));
			return R.data(kv);
		}
		return R.fail("操作失败");
	}

	/**
	 * 删除
	 */
//	@IsAdmin
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "删除", description = "传入ids")
	public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		CacheUtil.clear(SYS_CACHE);
		CacheUtil.clear(SYS_CACHE, Boolean.FALSE);
		return R.status(deptService.removeDept(ids));
	}

	/**
	 * 下拉数据源
	 */
	@PreAuth(AuthConstant.PERMIT_ALL)
	@GetMapping("/select")
	@ApiOperationSupport(order = 8)
	@Operation(summary = "下拉数据源", description = "传入id集合")
	public R<List<Dept>> select(Long userId, String deptId) {
		if (Func.isNotEmpty(userId)) {
			User user = UserCache.getUser(userId);
			deptId = user.getDeptId();
		}
		List<Dept> list = deptService.list(Wrappers.<Dept>lambdaQuery().in(Dept::getId, Func.toLongList(deptId)));
		return R.data(list);
	}


}
