/*
 *
 *      Copyright (c) 2018-2025, avenue 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: avenue
 *
 */

package com.emergency.avenue.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.emergency.avenue.admin.api.dto.SysDeptDTO;
import com.emergency.avenue.admin.api.entity.SysDept;
import com.emergency.avenue.admin.api.entity.SysDeptRelation;
import com.emergency.avenue.admin.service.SysDeptRelationService;
import com.emergency.avenue.admin.service.SysDeptService;
import com.emergency.avenue.common.core.constant.FieldParam;
import com.emergency.avenue.common.core.constant.TranslationDict;
import com.emergency.avenue.common.core.util.R;
import com.emergency.avenue.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * <p>
 * 部门管理 前端控制器
 * </p>
 *
 * @author avenue
 * @since 2018-01-20
 */
@RestController
@AllArgsConstructor
@RequestMapping("/dept")
@Tag(description = "dept", name = "部门管理模块")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class SysDeptController {

	private final SysDeptRelationService relationService;

	private final SysDeptService sysDeptService;

	/**
	 * 通过ID查询
	 * @param id ID
	 * @return SysDept
	 */
	@GetMapping("/{id}")
	public R getById(@PathVariable String id) {
		return R.ok(sysDeptService.getById(id));
	}

	/**
	 * 查询全部部门
	 */
	@GetMapping("/list")
	public R list() {
		return R.ok(sysDeptService.list());
	}

	/**
	 * 返回树形菜单集合
	 * @param deptName 部门名称
	 * @return 树形菜单
	 */
	@GetMapping(value = "/tree")
	@TranslationDict({
			@FieldParam(dictType = "dept_type", targetField = "deptType")
	})
	public R getTree(String deptName) {
		return R.ok(sysDeptService.selectTree(deptName));
	}

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

	/**
	 * 删除
	 * @param id ID
	 * @return success/false
	 */
	@SysLog("删除部门")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('sys_dept_del')")
	public R removeById(@PathVariable String id) {
		return R.ok(sysDeptService.removeDeptById(id));
	}

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

	/**
	 * 查收子级列表
	 * @return 返回子级
	 */
	@GetMapping(value = "/getDescendantList/{deptId}")
	public R getDescendantList(@PathVariable String deptId) {
		return R.ok(
				relationService.list(Wrappers.<SysDeptRelation>lambdaQuery().eq(SysDeptRelation::getAncestor, deptId)));
	}

	/**
	 * 根据部门类型查询部门数据
	 * @return 部门数据
	 */
	@GetMapping(value = "/getDeptTypeList/{deptType}")
	public R getDeptTypeList(@PathVariable Long deptType) {
		return R.ok(
				sysDeptService.list(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getDeptType, deptType)));
	}

	/**
	 * 查根据parentId查询下级组织
	 * @return 部门数据
	 */
	@PostMapping(value = "/getDeptParentIdList")
	public R getDeptParentIdList(@RequestBody SysDeptDTO sysDeptDTO) {
		LambdaQueryWrapper<SysDept> queryWrapper = Wrappers.<SysDept>lambdaQuery();
		if (CharSequenceUtil.isNotBlank(sysDeptDTO.getDeptType())) {
			queryWrapper.eq(SysDept::getDeptType, sysDeptDTO.getDeptType());
		}
		if (CollUtil.isNotEmpty(sysDeptDTO.getParentIdList())) {
			queryWrapper.in(SysDept::getParentId, sysDeptDTO.getParentIdList());
		}
		if (CharSequenceUtil.isNotBlank(sysDeptDTO.getWarehouseType())) {
			queryWrapper.like(SysDept::getWarehouseType, sysDeptDTO.getWarehouseType());
		}
		List<SysDept> deptList = sysDeptService.list(queryWrapper);
		return R.ok(deptList);
	}
}
