/*
 * 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.controller;

import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysDept;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.DeptTreeSelectVO;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.SysDeptMoveVo;
import com.yifu.cloud.plus.v1.yifu.admin.api.vo.SysDeptVo;
import com.yifu.cloud.plus.v1.yifu.admin.service.SysDeptService;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.UserPermissionVo;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.log.annotation.SysLog;
import com.yifu.cloud.plus.v1.yifu.common.security.annotation.Inner;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 部门管理 前端控制器
 * </p>
 *
 * @author lengleng
 * @since 2019/2/1
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/dept")
@Tag(name = "部门管理模块")
public class DeptController {

	private final SysDeptService sysDeptService;

	/**
	 * 通过ID查询
	 * @param id ID
	 * @return SysDept
	 */
	@GetMapping("/{id:\\d+}")
	public R<SysDept> getById(@PathVariable Long id) {
		return R.ok(sysDeptService.getById(id));
	}

	/**
	 * 返回树形菜单集合
	 * @return 树形菜单
	 */
	@GetMapping(value = "/tree")
	public R<List<Tree<Long>>> listDeptTrees() {
		return R.ok(sysDeptService.listDeptTrees());
	}

	/**
	 * 返回当前用户树形菜单集合
	 * @return 树形菜单
	 */
	@SysLog("返回当前用户树形菜单")
	@GetMapping(value = "/user-tree")
	public R<List<Tree<Long>>> listCurrentUserDeptTrees() {
		return R.ok(sysDeptService.listCurrentUserDeptTrees());
	}

	/**
	 * 添加
	 * @param sysDept 实体
	 * @return success/false
	 */
	@SysLog("添加部门")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys_dept_add')")
	public R<Boolean> save(@Valid @RequestBody SysDept sysDept) {
		return R.ok(sysDeptService.saveDept(sysDept));
	}

	/**
	 * 删除
	 * @param id ID
	 * @return success/false
	 */
	@SysLog("删除部门")
	@DeleteMapping("/{id:\\d+}")
	@PreAuthorize("@pms.hasPermission('sys_dept_del')")
	public R<Boolean> removeById(@PathVariable Long id) {
		return R.ok(sysDeptService.removeDeptById(id));
	}

	/**
	 * 编辑
	 * @param sysDept 实体
	 * @return success/false
	 */
	@SysLog("编辑部门")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys_dept_edit')")
	public R<Boolean> update(@Valid @RequestBody SysDept sysDept) {
		return R.ok(sysDeptService.updateDeptById(sysDept));
	}

	/**
	 * 根据部门名查询部门信息
	 * @param deptname 部门名
	 * @return
	 */
	@SysLog("根据部门名查询部门信息")
	@GetMapping("/details/{deptname}")
	public R<SysDept> user(@PathVariable String deptname) {
		SysDept condition = new SysDept();
		condition.setName(deptname);
		return R.ok(sysDeptService.getOne(new QueryWrapper<>(condition)));
	}

	/**
	 * 查收子级id列表
	 * @return 返回子级id列表
	 */
	@Inner
	@GetMapping(value = "/child-id/{deptId:\\d+}")
	public R<List<Long>> listChildDeptId(@PathVariable Long deptId) {
		return R.ok(sysDeptService.listChildDeptId(deptId));
	}

	/**
	 * 从ldap中获取部门
	 * @return R
	 */
	@SysLog("从ldap中获取部门")
	@PostMapping("/updateDept")
	public R updateDeptByLdap() {
		return R.ok(sysDeptService.updateDeptByLdap());
	}

	/**
	 * 从ldap中获取部门
	 * @return R
	 */
	@SysLog("从ldap中获取部门")
	@PostMapping("/inner/updateDept")
	@Inner
	public R innerUpdateDeptByLdap() {
		return R.ok(sysDeptService.updateDeptByLdap());
	}

	/**
	 * 客户服务平台——获取部门树（用于下拉选择）
	 * @return 树形菜单
	 * @author chenyuxi
	 * @since 1.9.7
	 */
	@GetMapping(value = "/csp/list")
	public R<List<DeptTreeSelectVO>> cspList(SysDeptVo dept) {
		if(Common.isEmpty(dept.getProjectNo())){
			return R.failed("项目编码不能为空");
		}
		return R.ok(sysDeptService.cspDeptTreeSelect(dept));
	}

	/**
	 * 客户服务平台——获取部门树（带部门下人数）
	 * @return 树形菜单
	 * @author chenyuxi
	 * @since 1.9.7
	 */
	@GetMapping(value = "/csp/tree")
	public R<List<DeptTreeSelectVO>> cspTree(SysDeptVo dept) {
		if(Common.isEmpty(dept.getProjectNo())){
			return R.failed("项目编码不能为空");
		}
		return R.ok(sysDeptService.cspDeptTree(dept));
	}

	/**
	 * 客户服务平台——获取花名册的部门树（带部门下人数）
	 * @return 树形菜单
	 * @author chenyuxi
	 * @since 1.9.7
	 */
	@PostMapping(value = "/csp/rosterTree")
	public R<List<DeptTreeSelectVO>> cspRosterTree(@RequestBody SysDeptVo dept) {
		if(Common.isEmpty(dept.getProjectNo())){
			return R.failed("项目编码不能为空");
		}
		YifuUser user = SecurityUtils.getUser();
		if (user == null || Common.isEmpty(user.getId())) {
			return R.failed(CommonConstants.PLEASE_LOG_IN);
		}
		List<UserPermissionVo> cspPermList = user.getCspPermMap();
		if(Common.isEmpty(cspPermList)){
			return R.failed("获取用户权限失败！");
		}
		// 获取用户在当前项目下的权限
		UserPermissionVo authority = null;
		for (UserPermissionVo userPermissionVo : cspPermList) {
			if(dept.getProjectNo().equals(userPermissionVo.getProjectNo())){
				authority = userPermissionVo;
			}
		}
		if(Common.isEmpty(authority)){
			return R.failed("获取用户在当前项目下的权限失败！");
		}
		return R.ok(sysDeptService.cspRosterTree(dept, authority));
	}

	/**
	 * 客户服务平台——添加部门
	 * @param sysDept 实体
	 * @return success/false
	 * @author chenyuxi
	 * @since 1.9.7
	 */
	@SysLog("客户服务平台——添加部门")
	@PostMapping("/csp")
	public R<String> saveCspDept(@RequestBody SysDept sysDept) {
		if(Common.isEmpty(sysDept.getProjectNo())){
			return R.failed("项目编码不能为空");
		}
		if(Common.isEmpty(sysDept.getName())){
			return R.failed("部门名称不能为空");
		}
		if(sysDept.getName().length()>50){
			return R.failed("部门名称不能超过50个字");
		}
		// 父级不传，默认增顶级部门
		if (Common.isEmpty(sysDept.getParentId())){
			sysDept.setParentId(0L);
		}
		return sysDeptService.saveCspDept(sysDept);
	}

	/**
	 * 客户服务平台——编辑部门
	 * @param sysDept 实体
	 * @return success/false
	 * @author chenyuxi
	 * @since 1.9.7
	 */
	@SysLog("客户服务平台——编辑部门")
	@PutMapping("/csp")
	public R<String> updateCspDept(@RequestBody SysDept sysDept) {
		if(Common.isEmpty(sysDept.getDeptId())){
			return R.failed("ID不能为空");
		}
		if(Common.isEmpty(sysDept.getName())){
			return R.failed("部门名称不能为空");
		}
		if(sysDept.getName().length()>50){
			return R.failed("部门名称不能超过50个字");
		}
		return sysDeptService.updateCspDept(sysDept);
	}

	/**
	 * 删除
	 * @param id ID
	 * @return success/false
	 * @author chenyuxi
	 * @since 1.9.7
	 */
	@SysLog("客户服务平台——删除部门")
	@DeleteMapping("/csp/{id:\\d+}")
	public R<String> removeCspDeptById(@PathVariable Long id) {
		if(Common.isEmpty(id)){
			return R.failed("项目Id不能为空");
		}
		return sysDeptService.removeCspDeptById(id);
	}

	/**
	 * 客户服务平台——获取项目下部门总数
	 * @return R<Integer> 部门总数
	 * @author chenyuxi
	 * @since 1.9.7
	 */
	@GetMapping(value = "/csp/getDeptCount")
	public R<Integer> cspDeptCount(SysDeptVo dept) {
		if(Common.isEmpty(dept.getProjectNo())){
			return R.failed("项目编码不能为空");
		}
		return R.ok(sysDeptService.cspDeptCount(dept.getProjectNo()));
	}

	/**
	 * @Author fxj
	 * @Description 获取
	 * @Date 17:27 2025/2/26
	**/
	@PostMapping(value = "/cspUpdateDept")
	public R<Boolean> cspUpdateDept(@RequestBody SysDeptMoveVo dept) {
		return sysDeptService.cspUpdateDept(dept);
	}

	/**
	 * 客户服务平台——获取项目下已删除的部门
	 * @return R<String> 删除部门的ID集合
	 * @author chenyuxi
	 * @since 1.9.7
	 */
	@GetMapping(value = "/csp/getDelDeptIds")
	public R<String> cspDelDeptIds(SysDeptVo dept) {
		if(Common.isEmpty(dept.getProjectNo())){
			return R.failed("项目编码不能为空");
		}
		return R.ok(sysDeptService.cspDelDeptIds(dept.getProjectNo()));
	}

}
