package com.xiaoniu.system.platformsettings.storetype.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoniu.common.core.constant.Constants;
import com.xiaoniu.common.core.exception.ServiceException;
import com.xiaoniu.common.core.utils.StringUtils;
import com.xiaoniu.common.core.vo.LabelAndValueVO;
import com.xiaoniu.common.security.utils.SecurityUtils;
import com.xiaoniu.system.platformsettings.storetype.domain.TbStoreType;
import com.xiaoniu.system.platformsettings.storetype.dto.AddStoreTypeDTO;
import com.xiaoniu.system.platformsettings.storetype.dto.EditStoreTypeDTO;
import com.xiaoniu.system.platformsettings.storetype.dto.StoreTypeListQueryDTO;
import com.xiaoniu.system.platformsettings.storetype.mapper.TbStoreTypeMapper;
import com.xiaoniu.system.platformsettings.storetype.service.ITbStoreTypeService;
import com.xiaoniu.system.platformsettings.storetype.vo.StoreTypeDetailsVO;
import com.xiaoniu.system.platformsettings.storetype.vo.StoreTypeListVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 门店类型信息表 服务实现类
 * </p>
 *
 * @author haoxuyang
 * @since 2024-10-11 02:13:07
 */
@Service
public class TbStoreTypeServiceImpl extends ServiceImpl<TbStoreTypeMapper, TbStoreType> implements ITbStoreTypeService {

    @Override
    public List<StoreTypeListVO> storeTypeList(StoreTypeListQueryDTO dto) {
        LambdaQueryWrapper<TbStoreType> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getName())) {
            wrapper.like(TbStoreType::getName, dto.getName());
        }
        if (StringUtils.isNotNull(dto.getStatus())) {
            wrapper.eq(TbStoreType::getStatus, dto.getStatus());
        }
        if (StringUtils.isNotEmpty(dto.getBeginTime())) {
            wrapper.gt(TbStoreType::getCreateTime, dto.getBeginTime() + " 00:00:01");
        }
        if (StringUtils.isNotEmpty(dto.getEndTime())) {
            wrapper.lt(TbStoreType::getCreateTime, dto.getEndTime() + " 23:59:59");
        }
        wrapper.eq(TbStoreType::getDelFlag, Constants.ZERO);
        wrapper.orderByAsc(TbStoreType::getSort);
        wrapper.eq(TbStoreType::getType,Constants.ONE);
        wrapper.orderByDesc(TbStoreType::getCreateTime);
        List<StoreTypeListVO> list = baseMapper.selectVoList(wrapper, StoreTypeListVO.class);
        if (!CollectionUtils.isEmpty(list)) {
            list = buildTree(list);
        }
        return list;
    }

    @Override
    public void addStoreType(AddStoreTypeDTO dto) {
        TbStoreType tbStoreType = new TbStoreType();
        BeanUtils.copyProperties(dto, tbStoreType);
        if (StringUtils.isNull(dto.getParentId())) {
            tbStoreType.setParentId(0L);
        }
        try {
            tbStoreType.setCreateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            log.error("获取当前登陆用户失败{}" + e.getMessage());
        }
        tbStoreType.setType(Constants.ONE);
        tbStoreType.setCreateTime(new Date());
        baseMapper.insert(tbStoreType);
    }

    @Override
    public void editStoreType(EditStoreTypeDTO dto) {
        TbStoreType tbStoreType = baseMapper.selectById(dto.getId());
        if (StringUtils.isNull(tbStoreType)) {
            throw new ServiceException("当前信息不存在");
        }
        BeanUtils.copyProperties(dto, tbStoreType);
        if (StringUtils.isNull(dto.getParentId())) {
            tbStoreType.setParentId(0L);
        }
        try {
            tbStoreType.setUpdateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            log.error("获取当前登陆用户失败{}" + e.getMessage());
        }
        tbStoreType.setUpdateTime(new Date());
        baseMapper.updateById(tbStoreType);
    }

    @Override
    public StoreTypeDetailsVO details(Long id) {
        TbStoreType tbStoreType = baseMapper.selectById(id);
        if (StringUtils.isNull(tbStoreType)) {
            throw new ServiceException("当前信息不存在");
        }
        if (Constants.TWO.equals(tbStoreType.getDelFlag())) {
            throw new ServiceException("当前信息已删除");
        }
        StoreTypeDetailsVO detailsVO = new StoreTypeDetailsVO();
        BeanUtils.copyProperties(tbStoreType, detailsVO);
        detailsVO.setParentId(String.valueOf(tbStoreType.getParentId()));
        return detailsVO;
    }

    @Override
    public void delStoreType(Long id) {
        TbStoreType tbStoreType = baseMapper.selectById(id);
        if (StringUtils.isNull(tbStoreType)) {
            throw new ServiceException("当前信息不存在");
        }
        tbStoreType.setDelFlag(Constants.TWO);
        try {
            tbStoreType.setUpdateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            log.error("获取当前登陆用户失败{}" + e.getMessage());
        }
        tbStoreType.setUpdateTime(new Date());
        baseMapper.updateById(tbStoreType);
    }

    @Override
    public List<LabelAndValueVO> getStoreTyp(Long id) {
        if (StringUtils.isNull(id)) {
            return new ArrayList<>();
        }
        List<TbStoreType> tbStoreTypes = baseMapper.selectList(new LambdaQueryWrapper<TbStoreType>().eq(TbStoreType::getParentId, id).eq(TbStoreType::getDelFlag, Constants.ZERO).eq(TbStoreType::getStatus, Constants.ONE).orderByAsc(TbStoreType::getSort));
        if (StringUtils.isNotNull(tbStoreTypes)) {
            return tbStoreTypes.stream().map(item -> {
                LabelAndValueVO labelAndValueVO = new LabelAndValueVO();
                labelAndValueVO.setLabel(item.getName());
                labelAndValueVO.setValue(String.valueOf(item.getId()));
                return labelAndValueVO;
            }).toList();
        }
        return new ArrayList<>();
    }

    @Override
    public List<LabelAndValueVO> getStoreType2(Long id) {
        List<TbStoreType> tbStoreTypes = baseMapper.selectList(new LambdaQueryWrapper<TbStoreType>().ne(TbStoreType::getParentId, 0L).eq(TbStoreType::getDelFlag, Constants.ZERO).eq(TbStoreType::getStatus, Constants.ONE).orderByAsc(TbStoreType::getSort));
        if (StringUtils.isNotNull(tbStoreTypes)) {
            return tbStoreTypes.stream().map(item -> {
                LabelAndValueVO labelAndValueVO = new LabelAndValueVO();
                labelAndValueVO.setLabel(item.getName());
                labelAndValueVO.setValue(String.valueOf(item.getId()));
                return labelAndValueVO;
            }).toList();
        }
        return new ArrayList<>();
    }

    public static List<StoreTypeListVO> buildTree(List<StoreTypeListVO> nodes) {
        List<StoreTypeListVO> roots = new ArrayList<>();
        // 将所有节点放入 Map
        Map<Long, List<StoreTypeListVO>> nodeMap = nodes.stream().collect(Collectors.groupingBy(StoreTypeListVO::getId));

        //首先获取当前列表的顶级集合
        for (StoreTypeListVO node : nodes) {
            if (StringUtils.isNotNull(node.getParentId())) {
                List<StoreTypeListVO> list = nodes.stream().filter(o -> o.getId().equals(node.getParentId())).toList();
                if (CollectionUtils.isEmpty(list)) {
                    roots.add(node);
                }
            }
        }
        //获取顶级列表的子元素
        for (StoreTypeListVO root : roots) {
            recursionFn(nodes, root);
        }
        return roots;
    }

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

    /**
     * 得到子节点列表
     */
    private static List<StoreTypeListVO> getChildList(List<StoreTypeListVO> list, StoreTypeListVO t) {
        List<StoreTypeListVO> tlist = new ArrayList<StoreTypeListVO>();
        Iterator<StoreTypeListVO> it = list.iterator();
        while (it.hasNext()) {
            StoreTypeListVO n = (StoreTypeListVO) it.next();
            if (n.getParentId().equals(t.getId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private static boolean hasChild(List<StoreTypeListVO> list, StoreTypeListVO t) {
        return !CollectionUtils.isEmpty(getChildList(list, t));
    }
}
