package cn.iocoder.yudao.module.system.controller.admin.dept;

import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptListReqVO;
import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptRespVO;
import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.dept.vo.dept.DeptSimpleRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;

@Tag(name = "管理后台 - 部门")
@RestController
@RequestMapping("/system/dept")
@Validated
public class DeptController {

    @Resource
    private DeptService deptService;
    @Resource
    private AdminUserService userService;

    @PostMapping("create")
    @Operation(summary = "创建部门")
    @PreAuthorize("@ss.hasPermission('system:dept:create')")
    public CommonResult<Long> createDept(@Valid @RequestBody DeptSaveReqVO createReqVO) {
        Long deptId = deptService.createDept(createReqVO);
        return success(deptId);
    }

    @PutMapping("update")
    @Operation(summary = "更新部门")
    @PreAuthorize("@ss.hasPermission('system:dept:update')")
    public CommonResult<Boolean> updateDept(@Valid @RequestBody DeptSaveReqVO updateReqVO) {
        deptService.updateDept(updateReqVO);
        return success(true);
    }

    @DeleteMapping("delete")
    @Operation(summary = "删除部门")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:dept:delete')")
    public CommonResult<Boolean> deleteDept(@RequestParam("id") Long id) {
        deptService.deleteDept(id);
        return success(true);
    }

    @GetMapping("/list")
    @Operation(summary = "获取部门列表")
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<List<DeptRespVO>> getDeptList(DeptListReqVO reqVO) {
        List<DeptDO> list = deptService.getDeptList(reqVO);

        if (reqVO.getVirtuallyStatus() == 1) {

            // 获得所有得虚机构部门信息
            List<DeptDO> virtuallyDeptId = list.stream()
                    .filter(dept -> dept.getVirtuallyStatus() == 1)
                    .collect(Collectors.toList());

            virtuallyDeptId.forEach(data -> {

                // 将虚机构的子部门，父部门设置为虚机构的父部门
                list.stream().filter(dept -> dept.getParentId().equals(data.getId()))
                        .map(dept -> dept.setParentId(data.getParentId()))
                        .collect(Collectors.toList());

            });

            // 移除虚机构，不展示
            list.removeIf(dept -> dept.getVirtuallyStatus() == 1);
        }

        return success(BeanUtils.toBean(list, DeptRespVO.class));
    }

    @GetMapping(value = {"/get-list"})
    @Operation(summary = "获取部门精简信息列表", description = "只包含被开启的部门，主要用于添加部门下拉选项")
    public CommonResult<List<DeptSimpleRespVO>> getDeptList() {
        List<DeptDO> list = deptService.getDeptList(
                new DeptListReqVO().setStatus(CommonStatusEnum.ENABLE.getStatus()));

        return success(BeanUtils.toBean(list, DeptSimpleRespVO.class));
    }

    @GetMapping(value = {"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取部门精简信息列表", description = "只包含被开启的部门，主要用于前端的下拉选项")
    public CommonResult<List<DeptSimpleRespVO>> getSimpleDeptList() {
        List<DeptDO> list = deptService.getDeptList(
                new DeptListReqVO().setStatus(CommonStatusEnum.ENABLE.getStatus()));

        // 获得所有得虚机构部门信息
        List<DeptDO> virtuallyDeptId = list.stream()
                .filter(dept -> dept.getVirtuallyStatus() == 1)
                .collect(Collectors.toList());

        virtuallyDeptId.forEach(data -> {

            // 将虚机构的子部门，父部门设置为虚机构的父部门
            list.stream().filter(dept -> dept.getParentId().equals(data.getId()))
                    .map(dept -> dept.setParentId(data.getParentId()))
                    .collect(Collectors.toList());

        });

        // 移除虚机构，不展示
        list.removeIf(dept -> dept.getVirtuallyStatus() == 1);

        return success(BeanUtils.toBean(list, DeptSimpleRespVO.class));
    }

    @GetMapping(value = { "/virtually-list"})
    @Operation(summary = "获取部门精简信息列表", description = "只包含被开启的部门，主要用于前端的下拉选项")
    public CommonResult<List<DeptSimpleRespVO>> getVirtuallyDeptList() {
        List<DeptDO> list = deptService.getDeptList(
                new DeptListReqVO().setStatus(CommonStatusEnum.ENABLE.getStatus()));

        return success(BeanUtils.toBean(list, DeptSimpleRespVO.class));
    }

    @GetMapping(value = {"/all-list"})
    @Operation(summary = "获取部门精简信息列表", description = "只包含被开启的部门，主要用于前端的下拉选项")
    @DataPermission(enable = false)
    public CommonResult<List<DeptSimpleRespVO>> getAllDeptList() {
        List<DeptDO> list = deptService.getDeptList(
                new DeptListReqVO().setStatus(CommonStatusEnum.ENABLE.getStatus()));

        // 获得所有得虚机构部门信息
        List<DeptDO> virtuallyDeptId = list.stream()
                .filter(dept -> dept.getVirtuallyStatus() == 1)
                .collect(Collectors.toList());

        virtuallyDeptId.forEach(data -> {

            // 将虚机构的子部门，父部门设置为虚机构的父部门
            list.stream().filter(dept -> dept.getParentId().equals(data.getId()))
                    .map(dept -> dept.setParentId(data.getParentId()))
                    .collect(Collectors.toList());

        });

        // 移除虚机构，不展示
        list.removeIf(dept -> dept.getVirtuallyStatus() == 1);

        return success(BeanUtils.toBean(list, DeptSimpleRespVO.class));
    }

    @GetMapping("/get")
    @Operation(summary = "获得部门信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:dept:query')")
    public CommonResult<DeptRespVO> getDept(@RequestParam("id") Long id) {
        DeptDO dept = deptService.getDept(id);
        return success(BeanUtils.toBean(dept, DeptRespVO.class));
    }

    @GetMapping("/getUserDept")
    @Operation(summary = "获取当前登录用户部门信息")
    public CommonResult<DeptRespVO> getUserDept() {
        LoginUser loginUser = getLoginUser();
        DeptDO dept = null;
        if (loginUser != null) {
            AdminUserDO user = userService.getUser(loginUser.getId());
            dept = deptService.getDept(user.getDeptId());
        }
        return success(BeanUtils.toBean(dept, DeptRespVO.class));
    }

    @GetMapping("/getCompanyDept")
    @Operation(summary = "获取部门类型为公司的部门信息")
    @DataPermission(enable = false)
    public CommonResult<List<DeptSimpleRespVO>> getCompanyDept() {
        List<DeptDO> list = deptService.getCompanyDept();

        return success(BeanUtils.toBean(list, DeptSimpleRespVO.class));
    }
}
