package com.bonus.canteen.core.basic.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.basic.mapper.BasicCanteenMapper;
import com.bonus.canteen.core.common.domain.TreeSelect;
import com.bonus.canteen.core.supermarket.mapper.SupermarketInfoMapper;
import com.bonus.canteen.core.supply.mapper.SupplyWarehouseInfoMapper;
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.basic.mapper.BasicAreaMapper;
import com.bonus.canteen.core.basic.domain.BasicArea;
import com.bonus.canteen.core.basic.service.IBasicAreaService;

/**
 * 区域Service业务层处理
 * 
 * @author xsheng
 * @date 2025-05-25
 */
@Service
public class BasicAreaServiceImpl implements IBasicAreaService {
    @Autowired
    private BasicAreaMapper basicAreaMapper;
    @Autowired
    private BasicCanteenMapper basicCanteenMapper;
    @Autowired
    private SupermarketInfoMapper supermarketInfoMapper;
    @Autowired
    SupplyWarehouseInfoMapper supplyWarehouseInfoMapper;

    /**
     * 查询区域
     * 
     * @param areaId 区域主键
     * @return 区域
     */
    @Override
    public BasicArea selectBasicAreaByAreaId(Long areaId) {
        return basicAreaMapper.selectBasicAreaByAreaId(areaId);
    }

    /**
     * 查询区域列表
     * 
     * @param basicArea 区域
     * @return 区域
     */
    @Override
    public List<BasicArea> selectBasicAreaList(BasicArea basicArea) {
        return basicAreaMapper.selectBasicAreaList(basicArea);
    }

    @Override
    public List<TreeSelect> selectAreaTreeList(BasicArea area) {
        List<BasicArea> areas = selectBasicAreaList(area);
        return buildAreaTreeSelect(areas);
    }

    /**
     * 新增区域
     * 
     * @param basicArea 区域
     * @return 结果
     */
    @Override
    public int insertBasicArea(BasicArea basicArea) {
        basicArea.setCreateTime(DateUtils.getNowDate());
        try {
            BasicArea checkResult = basicAreaMapper.selectBasicAreaByAreaName(basicArea.getAreaName());
            if (Objects.nonNull(checkResult)) {
                throw new ServiceException("区域名称已存在");
            }
            return basicAreaMapper.insertBasicArea(basicArea);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 修改区域
     * 
     * @param basicArea 区域
     * @return 结果
     */
    @Override
    public int updateBasicArea(BasicArea basicArea) {
        basicArea.setUpdateTime(DateUtils.getNowDate());
        try {
            List<BasicArea> allAreaList = basicAreaMapper.selectBasicAreaList(new BasicArea());
            List<String> otherAreaNameList = allAreaList.stream().filter(item -> !item.getAreaId().equals(basicArea.getAreaId()))
                    .map(BasicArea::getAreaName).collect(Collectors.toList());
            if (otherAreaNameList.contains(basicArea.getAreaName())) {
                throw new ServiceException("区域名称已存在");
            }
            return basicAreaMapper.updateBasicArea(basicArea);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 批量删除区域
     * 
     * @param areaIds 需要删除的区域主键
     * @return 结果
     */
    @Override
    public int deleteBasicAreaByAreaIds(Long[] areaIds) {
        int count1 = basicCanteenMapper.getBasicCanteenCountByAreaIds(areaIds);
        if (count1 > 0) {
            throw new ServiceException("该区域含有食堂信息，不能删除");
        }
        int coun2 = supermarketInfoMapper.getSupermarketCountByAreaIds(areaIds);
        if (coun2 > 0) {
            throw new ServiceException("该区域含有超市信息，不能删除");
        }
        int coun3 = supplyWarehouseInfoMapper.getSupplyWarehouseCountByAreaIds(areaIds);
        if (coun3 > 0) {
            throw new ServiceException("该区域含有仓库信息，不能删除");
        }
        return basicAreaMapper.deleteBasicAreaByAreaIds(areaIds);
    }

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

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

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

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

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

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