package com.zt.plat.module.qms.resource.record.controller.admin.recordapply;

import com.zt.plat.framework.common.biz.system.permission.PermissionCommonApi;
import com.zt.plat.framework.common.biz.system.permission.dto.DeptDataPermissionRespDTO;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.datapermission.core.annotation.DeptDataPermissionIgnore;
import com.zt.plat.framework.security.core.LoginUser;
import com.zt.plat.framework.security.core.util.SecurityFrameworkUtils;
import com.zt.plat.module.system.api.dept.DeptApi;
import com.zt.plat.module.system.api.dept.dto.DeptRespDTO;
import com.zt.plat.module.system.api.user.AdminUserApi;
import com.zt.plat.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

import static com.zt.plat.module.qms.enums.ErrorCodeConstants.CURRENT_USER_COMPANY_NOT_EXISTS;


@Slf4j
@Tag(name = "通用接口-获取当前用户所在公司下所有部门及用户")
@RestController
@RequestMapping("/qms/resource/current-user")
@Validated
@DeptDataPermissionIgnore(enable = "true")
public class CommonRecordController {

    @Resource
    private DeptApi deptApi;

    @Resource
    private AdminUserApi adminUserApi;


    @Resource
    private PermissionCommonApi permissionCommonApi;


    @GetMapping("/dept-list")
    @Operation(summary = "获取当前用户所在公司的所有部门")
    public CommonResult<List<DeptRespDTO>> getDeptList() {
//        if (!ObjectUtils.isEmpty(deptDataList)) return CommonResult.success(deptDataList);
        // 获取当前部门的所有子部门
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        Long visitCompanyId = loginUser.getVisitCompanyId();
        // 获取当前所属公司下面的所有的部门
        if (ObjectUtils.isEmpty(loginUser) || loginUser.getVisitCompanyId() == null)
            return CommonResult.error(CURRENT_USER_COMPANY_NOT_EXISTS);
        CommonResult<List<DeptRespDTO>> childDeptList = deptApi.getChildDeptList(visitCompanyId);
        List<DeptRespDTO> data = childDeptList.getData();
        List<DeptRespDTO> deptDataList = getChildDeptList(data);
        return CommonResult.success(deptDataList);
    }

    // 使用递归查询子部门，并且指定查询四层部门,把所有查询结果放到一个list 集合中返回
    public List<DeptRespDTO> getChildDeptList(List<DeptRespDTO> list) {
        List<DeptRespDTO> allDeptList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(list)) {
            allDeptList.addAll(list);
        }
        getChildDeptListRecursive(list, allDeptList, 0);
        return allDeptList;
    }

    /**
     * 递归查询子部门，最多查询4层
     *
     * @param list        当前层级的部门列表
     * @param allDeptList 存储所有查询结果的集合
     * @param depth       当前递归深度
     */
    private void getChildDeptListRecursive(List<DeptRespDTO> list, List<DeptRespDTO> allDeptList, int depth) {
        // 递归深度限制为4层
        if (ObjectUtils.isEmpty(list) || depth >= 4) {
            return;
        }

//        List<Long> deptIds = new ArrayList<>();
        for (DeptRespDTO deptRespDTO : list) {
            CommonResult<List<DeptRespDTO>> result = deptApi.getChildDeptList(deptRespDTO.getId());
            if (result != null && result.isSuccess()) {
                List<DeptRespDTO> childDeptList = result.getData();
                if (!ObjectUtils.isEmpty(childDeptList)) {
                    // 将子部门添加到结果集合中
                    allDeptList.addAll(childDeptList);
                    // 递归查询下一层部门
                    getChildDeptListRecursive(childDeptList, allDeptList, depth + 1);
                }
            }
        }
    }

    @GetMapping("/user-list")
    @Operation(summary = "获得当前公司下面的所有用户")
    //@PreAuthorize("@ss.hasPermission('qms:record-relation:query')")
    public CommonResult<List<AdminUserRespDTO>> getUserList() {
        CommonResult<List<AdminUserRespDTO>> userDataList;
        CommonResult<List<DeptRespDTO>> deptList = this.getDeptList();
        List<DeptRespDTO> data = deptList.getData();
        // 获取部门的所有id
        List<Long> deptIds = new ArrayList<>();
        data.forEach(deptRespDTO -> {
            deptIds.add(deptRespDTO.getId());
        });
        userDataList = adminUserApi.getUserListByDeptIds(deptIds);
        return userDataList;
    }


    @GetMapping("/test")
    @Operation(summary = "获得当前公司下面的所有用户")
    //@PreAuthorize("@ss.hasPermission('qms:record-relation:query')")
    public CommonResult<DeptDataPermissionRespDTO> test() {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        Long userId = loginUser.getId();
        CommonResult<Boolean> booleanCommonResult = permissionCommonApi.hasAnyPermissions(userId,"read");
        log.info("booleanCommonResult:{}", booleanCommonResult.getData());
        CommonResult<DeptDataPermissionRespDTO> ytjyAdmin = permissionCommonApi.getDeptDataPermissionWithRoleCodes(userId, "11");

        return ytjyAdmin;
    }
}
