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

import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
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.qms.resource.record.constant.RecordConstants;
import com.zt.plat.module.qms.resource.record.controller.admin.recordapply.vo.DeptUserUniteRespVo;
import com.zt.plat.module.qms.resource.record.controller.admin.recordassign.vo.RecordAssignRespVO;
import com.zt.plat.module.qms.resource.record.service.recordassign.RecordAssignService;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
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 RecordAssignService recordAssignService;

//    private static final String DEPT_TYPE = "dept";
//    private static final String USER_TYPE = "user";

    @GetMapping("/dept-assign-list")
    @Operation(summary = "获取当前用户所在公司的所有部门,以及分发号")
    public CommonResult<List<RecordAssignRespVO>> getDeptAssignList() {
        CommonResult<List<DeptRespDTO>> deptList = this.getDeptList();
        if (ObjectUtils.isEmpty(deptList)) return CommonResult.success(new ArrayList<>());
        List<DeptRespDTO> data = deptList.getData();
        List<Long> deptIds = data.stream().map(DeptRespDTO::getId).toList();
        List<RecordAssignRespVO> recordAssignDOList = recordAssignService.selectListByTargetIds(deptIds);
        return CommonResult.success(recordAssignDOList);
    }

    @GetMapping("/user-assign-list")
    @Operation(summary = "获取当前用户所在公司的所有部门,以及分发号")
    public CommonResult<List<RecordAssignRespVO>> getUserAssignList() {
        CommonResult<List<AdminUserRespDTO>> deptList = this.getUserList(null);
        if (ObjectUtils.isEmpty(deptList)) return CommonResult.success(new ArrayList<>());
        List<AdminUserRespDTO> data = deptList.getData();
        List<Long> deptIds = data.stream().map(AdminUserRespDTO::getId).toList();
        List<RecordAssignRespVO> recordAssignDOList = recordAssignService.selectListByTargetIds(deptIds);
        return CommonResult.success(recordAssignDOList);
    }

    @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);
        return deptApi.getChildDeptList(visitCompanyId);
    }

    // 使用递归查询子部门，并且指定查询四层部门,把所有查询结果放到一个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;
//    }

//    private void getChildDeptListRecursive(List<DeptRespDTO> list, List<DeptRespDTO> allDeptList, int depth) {
//        // 递归深度限制为4层
//        if (ObjectUtils.isEmpty(list) || depth >= 3) {
//            return;
//        }
//
//        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(@RequestParam(name = "deptIds", required = false) String deptIdsList) {
        log.info("deptIdsList:{}", deptIdsList); // "1,2,3,4,5"
        // 字符串转换成  list<Long> 列表
        List<Long> deptIds = new ArrayList<>();
        if (!ObjectUtils.isEmpty(deptIdsList)) {
            deptIds = Arrays.stream(deptIdsList.split(",")).map(Long::parseLong).toList();
        }
        CommonResult<List<AdminUserRespDTO>> userDataList;
        CommonResult<List<DeptRespDTO>> deptList = this.getDeptList();
        List<DeptRespDTO> data = deptList.getData();
        // 获取部门的所有id

        if (ObjectUtils.isEmpty(deptIds)) {
            for (DeptRespDTO item : data) {
                deptIds.add(item.getId());
            }
        }
        userDataList = adminUserApi.getUserListByDeptIds(deptIds);
        return userDataList;
    }

    // 获取当前用户所在公司下所有部门及用户

    /**
     * @param deptId 部门 Id
     * @return
     */
    @GetMapping("/dept-user-list")
    @Operation(summary = "获得当前公司下面的部门，及用户")
    //@PreAuthorize("@ss.hasPermission('qms:record-relation:query')")
    public CommonResult<List<DeptUserUniteRespVo>> getDeptUserList(@RequestParam(name = "deptId", required = false) Long deptId) {
//        log.info("deptId:{}", deptId); // "1"
        Long loginUserCompanyId = SecurityFrameworkUtils.getLoginUserCompanyId();
        if (ObjectUtils.isEmpty(deptId)) deptId = loginUserCompanyId;
        CommonResult<List<DeptRespDTO>> childDeptList = deptApi.getChildDeptList(deptId);
        List<DeptRespDTO> data = childDeptList.getData();
        // 获取第一层部门的部门和用户
        List<DeptUserUniteRespVo> userDataList = new ArrayList<>();
        for (DeptRespDTO item : data) {
            if (item.getParentId().equals(deptId)) {
                DeptUserUniteRespVo respVo = new DeptUserUniteRespVo();
                respVo.setTargetType(RecordConstants.TargetType.DEPT);
                respVo.setHasLeaf(false);
                respVo.setTargetId(item.getId());
                respVo.setTargetName(item.getName());
                userDataList.add(respVo);
            }
        }
        // 判断 deptId 下是否有用户
        CommonResult<List<AdminUserRespDTO>> userListByDeptIds = adminUserApi.getUserListByDeptIds(Collections.singletonList(deptId));
        if (ObjectUtils.isEmpty(userListByDeptIds.getData())) return CommonResult.success(userDataList);
        for (AdminUserRespDTO item : userListByDeptIds.getData()) {
            DeptUserUniteRespVo respVo = new DeptUserUniteRespVo();
            respVo.setTargetType(RecordConstants.TargetType.USER);
            respVo.setHasLeaf(true);
            respVo.setTargetId(item.getId());
            respVo.setTargetName(item.getNickname());
            userDataList.add(respVo);
        }
        return CommonResult.success(userDataList);
    }
}
