package com.bonus.canteen.core.alloc.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.bonus.canteen.core.alloc.mapper.AllocCanteenMapper;
import com.bonus.canteen.core.common.domain.TreeSelect;
import com.bonus.canteen.core.alloc.mapper.AllocAreaMapper;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bonus.canteen.core.alloc.domain.AllocArea;
import com.bonus.canteen.core.alloc.service.IAllocAreaService;

/**
 * 区域Service业务层处理
 * 
 * @author xsheng
 * @date 2025-04-03
 */
@Service
public class AllocAreaServiceImpl implements IAllocAreaService {
    @Autowired
    private AllocAreaMapper allocAreaMapper;
    @Autowired
    private AllocCanteenMapper allocCanteenMapper;

    @Override
    public List<TreeSelect> selectAreaTreeList(AllocArea area) {
        List<AllocArea> areas = selectAllocAreaList(area); //SpringUtils.getAopProxy(this).selectAllocAreaList(area);
        return buildAreaTreeSelect(areas);
    }

    /**
     * 查询区域
     * 
     * @param areaId 区域主键
     * @return 区域
     */
    @Override
    public AllocArea selectAllocAreaByAreaId(Long areaId) {
        return allocAreaMapper.selectAllocAreaByAreaId(areaId);
    }

    /**
     * 查询区域列表
     * 
     * @param allocArea 区域
     * @return 区域
     */
    @Override
    public List<AllocArea> selectAllocAreaList(AllocArea allocArea) {
        return allocAreaMapper.selectAllocAreaList(allocArea);
    }

    /**
     * 新增区域
     * 
     * @param allocArea 区域
     * @return 结果
     */
    @Override
    public int insertAllocArea(AllocArea allocArea) {
        allocArea.setCreateTime(DateUtils.getNowDate());
        try {
            AllocArea checkResult = allocAreaMapper.selectAllocAreaByAreaName(allocArea.getAreaName());
            if (Objects.nonNull(checkResult)) {
                throw new ServiceException("区域名称已存在");
            }
            return allocAreaMapper.insertAllocArea(allocArea);
        } catch (Exception e) {
            throw new ServiceException("新增区域异常，" + e.getMessage());
        }
    }

    /**
     * 修改区域
     * 
     * @param allocArea 区域
     * @return 结果
     */
    @Override
    public int updateAllocArea(AllocArea allocArea) {
        allocArea.setUpdateTime(DateUtils.getNowDate());
        try {
            List<AllocArea> allAreaList = allocAreaMapper.selectAllocAreaList(new AllocArea());
            List<String> otherAreaNameList = allAreaList.stream().filter(item -> !item.getAreaId().equals(allocArea.getAreaId()))
                                                .map(AllocArea::getAreaName).collect(Collectors.toList());
            if (otherAreaNameList.contains(allocArea.getAreaName())) {
                throw new ServiceException("区域名称已存在");
            }
            return allocAreaMapper.updateAllocArea(allocArea);
        } catch (Exception e) {
            throw new ServiceException("更新区域失败，" + e.getMessage());
        }
    }

    /**
     * 批量删除区域
     * 
     * @param areaIds 需要删除的区域主键
     * @return 结果
     */
    @Override
    public int deleteAllocAreaByAreaIds(Long[] areaIds) {
        int count = allocCanteenMapper.selectAllocCanteenCountByAreaIds(areaIds);
        if (count > 0) {
            throw new ServiceException("区域含有食堂信息，不能删除");
        }
        return allocAreaMapper.deleteAllocAreaByAreaIds(areaIds);
    }

    /**
     * 删除区域信息
     * 
     * @param areaId 区域主键
     * @return 结果
     */
    @Override
    public int deleteAllocAreaByAreaId(Long areaId) {
        return allocAreaMapper.deleteAllocAreaByAreaId(areaId);
    }

    @Override
    public List<TreeSelect> buildAreaTreeSelect(List<AllocArea> areas)
    {
        List<AllocArea> areaTrees = buildAreaTree(areas);
        return areaTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<AllocArea> buildAreaTree(List<AllocArea> areas) {
        List<AllocArea> returnList = new ArrayList<AllocArea>();
        List<Long> tempList = areas.stream().map(AllocArea::getAreaId).collect(Collectors.toList());
        for (AllocArea area : areas)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(area.getParentId()))
            {
                recursionFn(areas, area);
                returnList.add(area);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = areas;
        }
        return returnList;
    }

    private void recursionFn(List<AllocArea> list, AllocArea t)
    {
        // 得到子节点列表
        List<AllocArea> childList = getChildList(list, t);
        t.setChildren(childList);
        for (AllocArea tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    private List<AllocArea> getChildList(List<AllocArea> list, AllocArea t)
    {
        List<AllocArea> tlist = new ArrayList<AllocArea>();
        Iterator<AllocArea> it = list.iterator();
        while (it.hasNext())
        {
            AllocArea n = (AllocArea) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getAreaId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<AllocArea> list, AllocArea t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

}
