package com.cico.nest.lcdp.boot.core.system.api.dept;

import com.cico.nest.lcdp.boot.core.system.controller.admin.dept.vo.dept.DeptListReqVO;
import com.cico.nest.lcdp.boot.core.system.dal.dataobject.dept.DeptDO;
import com.cico.nest.lcdp.boot.core.system.dal.dataobject.user.AdminUserDO;
import com.cico.nest.lcdp.boot.core.system.service.dept.DeptService;
import com.cico.nest.lcdp.boot.core.system.service.user.AdminUserService;
import com.cico.nest.lcdp.framework.api.dept.LcdpDeptApi;
import com.cico.nest.lcdp.framework.api.dept.dto.LcdpDeptDTO;
import com.cico.nest.lcdp.framework.common.enums.CommonStatusEnum;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class LcdpDeptApiImpl implements LcdpDeptApi {


    private final AdminUserService adminUserService;

    @Resource
    private DeptService deptService;

    @Override
    public List<LcdpDeptDTO> listDeptByNames(Collection<String> deptNames) {
        List<DeptDO> deptDOList = deptService.listDeptByNames(deptNames);
        return this.dtoConversion(deptDOList);
    }

    @Override
    public List<LcdpDeptDTO> listDeptByIds(Collection<String> deptIds) {
        List<String> deptIdList = deptIds.stream().map(String::valueOf).collect(Collectors.toList());
        List<DeptDO> deptDOList = deptService.getDeptList(deptIdList);
        return this.dtoConversion(deptDOList);
    }

    @Override
    public List<LcdpDeptDTO> listDept() {
        DeptListReqVO reqVO = new DeptListReqVO();
        reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
        List<DeptDO> deptDOList = deptService.getDeptList(reqVO);
        return this.dtoConversion(deptDOList);
    }

    @Override
    public List<String> getDepartIdsByUsername(String username) {
        AdminUserDO adminUser = adminUserService.getUserByUsername(username);
        List<String> deptIdList= new ArrayList<>();
        deptIdList.add(adminUser.getDeptId().toString());
        return deptIdList;
    }

    private List<LcdpDeptDTO> dtoConversion(List<DeptDO> deptDOList) {
        List<LcdpDeptDTO> deptDTOS = new ArrayList<>();
        deptDOList.forEach(deptDO -> {
            LcdpDeptDTO deptDTO = dtoConversion(deptDO);
            if (deptDTO != null) {
                deptDTOS.add(deptDTO);
            }
        });
        return deptDTOS;
    }

    private LcdpDeptDTO dtoConversion(DeptDO deptDO) {
        if (deptDO != null) {
            LcdpDeptDTO deptDTO = new LcdpDeptDTO();
            deptDTO.setId(String.valueOf(deptDO.getId()));
            deptDTO.setName(deptDO.getName());
            return deptDTO;
        }
        return null;
    }

}
