package com.hz.pm.api.user.manage;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hz.pm.api.common.util.StrUtils;
import com.hz.pm.api.user.helper.MhUnitCache;
import com.hz.pm.api.user.model.dto.MhUnitDTO;
import com.hz.pm.api.user.model.dto.MhUnitTreeDTO;
import com.hz.pm.api.user.model.dto.MhUnitUserTreeDTO;
import com.hz.pm.api.user.model.entity.MhUnit;
import com.hz.pm.api.user.model.entity.UserInfo;
import com.hz.pm.api.user.model.enumeration.UnitUserNodeType;
import com.hz.pm.api.user.model.po.MhUnitListReq;
import com.hz.pm.api.user.model.po.UserTreeReq;
import com.hz.pm.api.user.model.vo.MhUnitListVO;
import com.hz.pm.api.user.service.IMhUnitService;
import com.hz.pm.api.user.service.IUserInfoService;
import com.ningdatech.basic.model.PageVo;
import com.ningdatech.basic.util.CollUtils;
import com.ningdatech.basic.util.TreeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

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

/**
 * <p>
 * MhUnitManage
 * </p>
 *
 * @author WendyYang
 * @since 15:33 2024/1/10
 */
@Component
@RequiredArgsConstructor
public class MhUnitManage {

    private final IMhUnitService mhUnitService;
    private final MhUnitCache mhUnitCache;
    private final IUserInfoService userInfoService;

    public List<MhUnitTreeDTO> getMhUnitTree() {
        List<MhUnitDTO> allUnits = mhUnitCache.all();
        List<MhUnitTreeDTO> nodes = BeanUtil.copyToList(allUnits, MhUnitTreeDTO.class);
        return TreeUtil.convertToTree(nodes, 0L);
    }

    public PageVo<MhUnitListVO> page(MhUnitListReq req) {
        LambdaQueryWrapper<MhUnit> query = Wrappers.lambdaQuery(MhUnit.class)
                .like(StrUtils.isNotBlank(req.getName()), MhUnit::getName, req.getName());
        Page<MhUnit> page = mhUnitService.page(req.page(), query);
        if (page.getTotal() == 0) {
            return PageVo.empty();
        }
        List<MhUnitListVO> records = BeanUtil.copyToList(page.getRecords(), MhUnitListVO.class);
        return PageVo.of(records, page.getTotal());
    }

    public List<MhUnitUserTreeDTO> getUserTree(UserTreeReq req) {
        List<Long> selectedUnitIds = new ArrayList<>();
        List<MhUnitUserTreeDTO> selectedUsers = new ArrayList<>();
        List<MhUnitUserTreeDTO> selectedUnits = new ArrayList<>();
        if (req.getId() != null) {
            // 查询单位
            LambdaQueryWrapper<MhUnit> unitQuery = Wrappers.lambdaQuery(MhUnit.class)
                    .select(MhUnit::getId)
                    .like(StrUtils.isNotBlank(req.getName()), MhUnit::getName, req.getName())
                    .eq(MhUnit::getParentId, req.getId());
            List<MhUnit> units = mhUnitService.list(unitQuery);
            selectedUnitIds.addAll(CollUtils.fieldList(units, MhUnit::getId));
            // 查询用户
            LambdaQueryWrapper<UserInfo> userQuery = Wrappers.lambdaQuery(UserInfo.class)
                    .select(UserInfo::getMhUnitId, UserInfo::getId, UserInfo::getRealName)
                    .like(StrUtils.isNotBlank(req.getName()), UserInfo::getRealName, req.getName())
                    .eq(UserInfo::getMhUnitId, req.getId())
                    .last("limit 100");
            List<UserInfo> userInfos = userInfoService.list(userQuery);
            selectedUnitIds.addAll(CollUtils.fieldList(userInfos, UserInfo::getMhUnitId));
            userInfos.forEach(w -> selectedUsers.add(getMhUnitUserTree(w)));
            if (selectedUnitIds.isEmpty()) {
                return Collections.emptyList();
            }
            String rootId = UnitUserNodeType.UNIT + "#" + req.getId();
            selectedUnitIds.forEach(w -> {
                MhUnitDTO unit = mhUnitCache.getById(w);
                if (unit != null) {
                    selectedUnits.add(getMhUnitUserTree(unit));
                }
            });
            selectedUnits.addAll(selectedUsers);
            return TreeUtil.convertToTree(selectedUnits, rootId);
        } else {
            // 如果没有查询指定组织，那么直接查询第一级组织
            List<MhUnitDTO> childrenUnits = mhUnitCache.getChildren(0L);
            if (childrenUnits.isEmpty()) {
                return Collections.emptyList();
            }
            for (MhUnitDTO unit : childrenUnits) {
                selectedUnits.add(getMhUnitUserTree(unit));
            }
            selectedUnits.sort(selectedUnits.get(0).comparator());
            return selectedUnits;
        }
    }

    private MhUnitUserTreeDTO getMhUnitUserTree(MhUnitDTO unit) {
        MhUnitUserTreeDTO node = new MhUnitUserTreeDTO();
        node.setSort(unit.getSort());
        node.setName(unit.getName());
        node.setBizId(unit.getId());
        node.setParentId(UnitUserNodeType.UNIT.name() + "#" + unit.getParentId());
        node.setId(UnitUserNodeType.UNIT.name() + "#" + unit.getId());
        node.setType(UnitUserNodeType.UNIT);
        return node;
    }

    private MhUnitUserTreeDTO getMhUnitUserTree(UserInfo w) {
        MhUnitUserTreeDTO node = new MhUnitUserTreeDTO();
        node.setSort((short) 1);
        node.setName(w.getRealName());
        node.setBizId(w.getId());
        node.setParentId(UnitUserNodeType.UNIT.name() + "#" + w.getMhUnitId());
        node.setId(UnitUserNodeType.USER.name() + "#" + w.getId());
        node.setType(UnitUserNodeType.USER);
        return node;
    }

}
