package com.usky.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.system.domain.HceArticle;
import com.usky.system.domain.HceCategory;
import com.usky.system.domain.SysUser;
import com.usky.system.mapper.HceArticleMapper;
import com.usky.system.mapper.HceCategoryMapper;
import com.usky.system.service.HceCategoryService;
import com.usky.system.service.ISysUserService;
import com.usky.system.service.vo.HceCategoryListVO;
import com.usky.system.service.vo.HceCategoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 帮助中心_栏目管理 服务实现类
 * </p>
 *
 * @author han
 * @since 2023-08-29
 */
@Service
public class HceCategoryServiceImpl extends AbstractCrudService<HceCategoryMapper, HceCategory> implements HceCategoryService {
    @Resource
    private HceArticleMapper hceArticleMapper;
    @Autowired
    private ISysUserService userService;

    @Override
    public List<HceCategoryListVO> page(HceCategoryVO hceCategoryVO){
        long userId = SecurityUtils.getUserId();
        SysUser sysUser = userService.selectUserByIdOne(userId);
        List<HceCategoryListVO> list = new ArrayList<>();
        List<Integer> categoryIdList = new ArrayList<>();
        if(StringUtils.isNotBlank(hceCategoryVO.getCategoryName())){
            LambdaQueryWrapper<HceCategory> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.like(HceCategory::getCategoryName, hceCategoryVO.getCategoryName());
            List<HceCategory> list1 = this.list(queryWrapper);
            if(list1.size() > 0){
                for (int i = 0; i < list1.size(); i++) {
                    categoryIdList.add(list1.get(i).getId());
                }
                if(("00").equals(sysUser.getUserType())){
                    if (1L == userId)
                    {
                        list = baseMapper.selectMenuTreeAll(categoryIdList,hceCategoryVO.getStartTime(),hceCategoryVO.getEndTime());
                    }
                    else
                    {
                        list = baseMapper.selectMenuTreeByUserId(categoryIdList,hceCategoryVO.getStartTime(),hceCategoryVO.getEndTime(),userId);
                    }
                }else{
                    if (1L == userId)
                    {
                        list = baseMapper.selectMenuTreeAll(categoryIdList,hceCategoryVO.getStartTime(),hceCategoryVO.getEndTime());
                    }
                    else
                    {
                        list = baseMapper.selectMenuTreeByUserIdOne(categoryIdList,hceCategoryVO.getStartTime(),hceCategoryVO.getEndTime(),SecurityUtils.getTenantId());
                    }

                }
            }
        }else{
            if(("00").equals(sysUser.getUserType())){
                if (1L == userId)
                {
                    list = baseMapper.selectMenuTreeAll(categoryIdList,hceCategoryVO.getStartTime(),hceCategoryVO.getEndTime());
                }
                else
                {
                    list = baseMapper.selectMenuTreeByUserId(categoryIdList,hceCategoryVO.getStartTime(),hceCategoryVO.getEndTime(),userId);
                }
            }else{
                if (1L == userId)
                {
                    list = baseMapper.selectMenuTreeAll(categoryIdList,hceCategoryVO.getStartTime(),hceCategoryVO.getEndTime());
                }
                else
                {
                    list = baseMapper.selectMenuTreeByUserIdOne(categoryIdList,hceCategoryVO.getStartTime(),hceCategoryVO.getEndTime(),SecurityUtils.getTenantId());
                }
            }
        }

        List<HceCategoryListVO> finalList = list;
        List<HceCategoryListVO> list1 = list.stream().filter(s ->s.getParentId() == 0).map(
                menu->{menu.setChildren(getChildrenData(menu, finalList));
                    return menu;
                }
        ).collect(Collectors.toList());

        return list1;
    }

    @Override
    public List<HceCategoryListVO> pageWhite(HceCategoryVO hceCategoryVO){
        List<HceCategoryListVO> list = new ArrayList<>();
        List<Integer> categoryIdList = new ArrayList<>();
        if(StringUtils.isNotBlank(hceCategoryVO.getCategoryName())){
            LambdaQueryWrapper<HceCategory> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.like(HceCategory::getCategoryName, hceCategoryVO.getCategoryName());
            List<HceCategory> list2 = this.list(queryWrapper);
            if(list2.size() > 0){
                for (int i = 0; i < list2.size(); i++) {
                    categoryIdList.add(list2.get(i).getId());
                }
                list = baseMapper.selectMenuTreeAll(categoryIdList,hceCategoryVO.getStartTime(),hceCategoryVO.getEndTime());
            }
        }else{
            list = baseMapper.selectMenuTreeAll(categoryIdList,hceCategoryVO.getStartTime(),hceCategoryVO.getEndTime());
        }

        List<HceCategoryListVO> finalList = list;
        List<HceCategoryListVO> list1 = list.stream().filter(s ->s.getParentId() == 0).map(
                menu->{menu.setChildren(getChildrenData(menu, finalList));
                    return menu;
                }
        ).collect(Collectors.toList());

        return list1;
    }

    private List<HceCategoryListVO> getChildrenData(HceCategoryListVO parent, List<HceCategoryListVO> all){
        List<HceCategoryListVO> children = all.stream().filter(k ->k.getParentId().equals(parent.getMenuId())).map(
                menu->{
                    menu.setChildren(getChildrenData(menu,all));
                    return menu;
                }
        ).collect(Collectors.toList());
        return children;
    }

    public void add(HceCategory hceCategory){
//        LambdaQueryWrapper<HceCategory> queryWrapper = Wrappers.lambdaQuery();
//        queryWrapper.eq(HceCategory::getCategoryName,hceCategory.getCategoryName());
//        List<HceCategory> list = this.list(queryWrapper);
//        if(list.size() > 0){
//            throw new BusinessException("栏目名称重复，请重新填写栏目名称");
//        }
        LambdaQueryWrapper<HceCategory> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.eq(HceCategory::getMenuId,hceCategory.getMenuId());
        List<HceCategory> list1 = this.list(queryWrapper1);
        if(list1.size() > 0){
            throw new BusinessException("关联菜单名称重复");
        }

        //新增栏目时校验对应上级栏目是否存在，不存在要先新增上级栏目后再新增本栏目
//        Integer pid = baseMapper.selectPidByMenuid(hceCategory.getMenuId());
//        if(pid != null && pid != 0){
//            LambdaQueryWrapper<HceCategory> queryWrapper2 = Wrappers.lambdaQuery();
//            queryWrapper2.eq(HceCategory::getMenuId,pid);
//            List<HceCategory> list2 = this.list(queryWrapper2);
//            if(list2.size() <= 0){
//                throw new BusinessException("上级栏目不存在，请先添加上级栏目");
//            }
//        }

        hceCategory.setCreatedate(LocalDateTime.now());
        this.save(hceCategory);
    }

    public void update(HceCategory hceCategory){
//        LambdaQueryWrapper<HceCategory> queryWrapper = Wrappers.lambdaQuery();
//        queryWrapper.eq(HceCategory::getCategoryName,hceCategory.getCategoryName())
//                .ne(HceCategory::getId,hceCategory.getId());
//        List<HceCategory> list = this.list(queryWrapper);
//        if(list.size() > 0){
//            throw new BusinessException("栏目名称重复，请重新填写栏目名称");
//        }
        LambdaQueryWrapper<HceCategory> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.eq(HceCategory::getMenuId,hceCategory.getMenuId())
                .ne(HceCategory::getId,hceCategory.getId());
        List<HceCategory> list1 = this.list(queryWrapper1);
        if(list1.size() > 0){
            throw new BusinessException("关联菜单名称重复");
        }
        hceCategory.setModifydate(LocalDateTime.now());
        this.updateById(hceCategory);
    }

    public void remove(Integer id){
        if(id == null || id == 0){
            throw new BusinessException("栏目id不能为空或者等于0");
        }
        LambdaQueryWrapper<HceArticle> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(HceArticle::getCategoryid,id);
        List<HceArticle> list = hceArticleMapper.selectList(queryWrapper);
        if(list.size() > 0){
            throw new BusinessException("该栏目存在栏目内容不可删除");
        }
//        LambdaQueryWrapper<HceCategory> queryWrapper1 = Wrappers.lambdaQuery();
//        queryWrapper1.eq(HceCategory::getPid,id)
//                .eq(HceCategory::getStatus,1);
//        List<HceCategory> list1 = this.list(queryWrapper1);
//        if(list1.size()>0){
//            throw new BusinessException("该栏目存在子栏目不可删除");
//        }
        this.removeById(id);

    }

}
