package com.younike.system.service.impl;

import java.util.*;
import java.time.LocalDateTime;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.younike.common.core.domain.AjaxResult;
import com.younike.common.core.domain.model.LoginUser;
import com.younike.common.exception.GlobalException;
import com.younike.common.utils.SecurityUtils;
import com.younike.system.domain.*;
import com.younike.system.domain.vo.CategoryPublishVo;
import com.younike.system.domain.vo.CategoryVo;
import com.younike.system.domain.vo.GoodsVo;
import com.younike.system.domain.vo.MerchantGoodsVo;
import com.younike.system.mapper.CateDimensionMapper;
import com.younike.system.mapper.CategoryMapper;
import com.younike.system.mapper.DimensionMapper;
import com.younike.system.param.GoodsParam;
import com.younike.system.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 分类Service业务层处理
 *
 * @author elev
 * @date 2022-01-04
 */
@Service
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DimensionMapper dimensionMapper;

    @Autowired
    private CateDimensionMapper cateDimensionMapper;

    @Autowired
    private IServerUserFollowService followService;

    @Autowired
    private IServerUserService serverUserService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IMerchantCategoryService merchantCategoryService;

    @Override
    @Transactional
    public AjaxResult submit(CategoryVo categoryVo) {
        if (categoryVo == null
                || StringUtils.isEmpty(categoryVo.getCategoryName())
                || categoryVo.getDimensionList() == null
                || categoryVo.getDimensionList().size() == 0) {
            return AjaxResult.error("参数错误");
        }
        if (categoryVo.getCategoryId() == null) {
            categoryVo.setType(0);
            if (categoryVo.getSorting() == null) {
                // 查询 系统中最大的分类排序
                List<Category> categoryList = categoryMapper.getByParentId(null);
                if (CollectionUtils.isNotEmpty(categoryList)) {
                    Optional<Category> maxSorting = categoryList.stream().max(Comparator.comparing(Category::getSorting));
                    maxSorting.ifPresent(vo -> categoryVo.setSorting(vo.getSorting()+1));
                } else {
                    categoryVo.setSorting(1);
                }
            }
            try {
                LoginUser loginUser = SecurityUtils.getLoginUser();
                categoryVo.setCreateBy(loginUser.getUsername());
                categoryVo.setCreateTime(LocalDateTime.now());
            } catch (Exception e) {
                e.printStackTrace();
            }
            int insertCategory = categoryMapper.insertCategory(categoryVo);
            if (insertCategory < 1) {
                throw new GlobalException("添加失败");
            }
        } else {
            try {
                LoginUser loginUser = SecurityUtils.getLoginUser();
                categoryVo.setUpdateBy(loginUser.getUsername());
                categoryVo.setUpdateTime(LocalDateTime.now());
            } catch (Exception e) {
                e.printStackTrace();
            }
            int updateCategory = categoryMapper.updateCategory(categoryVo);
            if (updateCategory < 1) {
                throw new GlobalException("修改失败");
            }
        }
        List<Dimension> updateList = new ArrayList<>();
        List<Dimension> insertList = new ArrayList<>();
        List<CateDimension> cateDimensionList = new ArrayList<>();
        categoryVo.getDimensionList().forEach(dimension -> {
            if (dimension.getDimensionId() != null) {
                try {
                    LoginUser loginUser = SecurityUtils.getLoginUser();
                    dimension.setUpdateBy(loginUser.getUsername());
                    dimension.setUpdateTime(LocalDateTime.now());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                updateList.add(dimension);
            }
            if (dimension.getDimensionId() == null && (dimension.getDelFlag() == null || dimension.getDelFlag() == 0)) {
                try {
                    LoginUser loginUser = SecurityUtils.getLoginUser();
                    dimension.setCreateBy(loginUser.getUsername());
                    dimension.setCreateTime(LocalDateTime.now());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                insertList.add(dimension);
            }
        });
        if (updateList.size() > 0) {
            int updateBatch = dimensionMapper.updateBatch(updateList);
            if (updateBatch < 1) {
                throw new GlobalException("添加失败");
            }
        }
        if (insertList.size() > 0) {
            int insertBatch = dimensionMapper.insertBatch(insertList);
            if (insertBatch < 1) {
                throw new GlobalException("添加失败");
            }
            insertList.forEach(dimension -> {
                CateDimension cateDimension = new CateDimension();
                cateDimension.setCategoryId(categoryVo.getCategoryId());
                cateDimension.setDimensionId(dimension.getDimensionId());
                cateDimensionList.add(cateDimension);
            });
        }
        if (cateDimensionList.size() > 0) {
            int insertBatch = cateDimensionMapper.insertBatch(cateDimensionList);
            if (insertBatch < 1) {
                throw new GlobalException("添加失败");
            }
        }
        return AjaxResult.success("添加成功");
    }

    @Override
    public AjaxResult submitChild(Category category) {
        if (category == null || StringUtils.isEmpty(category.getParentId()) || StringUtils.isEmpty(category.getCategoryName())) {
            return AjaxResult.error("参数错误");
        }
        if (category.getCategoryId() == null) {
            category.setType(1);
            if (category.getSorting() == null) {
                // 查询 系统中最大的分类排序
                List<Category> categoryList = categoryMapper.getByParentId(category.getParentId());
                if (CollectionUtils.isNotEmpty(categoryList)) {
                    Optional<Category> maxSorting = categoryList.stream().max(Comparator.comparing(Category::getSorting));
                    maxSorting.ifPresent(vo -> category.setSorting(vo.getSorting()+1));
                } else {
                    category.setSorting(1);
                }
            }
            try {
                LoginUser loginUser = SecurityUtils.getLoginUser();
                category.setCreateBy(loginUser.getUsername());
                category.setCreateTime(LocalDateTime.now());
            } catch (Exception e) {
                e.printStackTrace();
            }
            int insertCategory = categoryMapper.insertCategory(category);
            if (insertCategory < 1) {
                throw new GlobalException("添加失败");
            }
        } else {
            try {
                LoginUser loginUser = SecurityUtils.getLoginUser();
                category.setUpdateBy(loginUser.getUsername());
                category.setUpdateTime(LocalDateTime.now());
            } catch (Exception e) {
                e.printStackTrace();
            }
            int updateCategory = categoryMapper.updateCategory(category);
            if (updateCategory < 1) {
                throw new GlobalException("修改失败");
            }
        }
        return AjaxResult.success("添加成功");
    }

    @Override
    public List<CategoryVo> categoryList(Integer bizType) {
        List<CategoryVo> categoryList = categoryMapper.getCategoryList(bizType);
        if (categoryList == null || categoryList.size() == 0) {
            return categoryList;
        }
        List<CategoryVo> categoryVoList = categoryList.stream().filter(category -> category.getParentId() == null && category.getType().equals(0)).collect(Collectors.toList());
        Map<String, List<CategoryVo>> categoryMap = categoryList.stream().filter(category -> category.getParentId() != null && category.getType().equals(1)).collect(Collectors.groupingBy(category -> category.getParentId()));
        if (categoryVoList.size() > 0) {
            categoryVoList.forEach(categoryVo -> {
                categoryVo.setChildrenCategory(categoryMap.get(categoryVo.getCategoryId().toString()));
            });
        }
        return categoryVoList;
    }

    @Override
    public List<CategoryVo> enabledCategoryList(Integer bizType) {
        List<CategoryVo> categoryList = categoryMapper.getCategoryList(bizType);
        if (categoryList == null || categoryList.size() == 0) {
            return categoryList;
        }
        List<CategoryVo> categoryVoList = categoryList.stream()
                .filter(category -> category.getIsEnable() == 1)
                .filter(category -> category.getParentId() == null && category.getType().equals(0))
                .collect(Collectors.toList());
        Map<String, List<CategoryVo>> categoryMap = categoryList.stream().filter(category -> category.getParentId() != null && category.getType().equals(1)).collect(Collectors.groupingBy(category -> category.getParentId()));
        if (categoryVoList.size() > 0) {
            categoryVoList.forEach(categoryVo -> {
                categoryVo.setChildrenCategory(categoryMap.get(categoryVo.getCategoryId().toString()));
            });
        }
        return categoryVoList;
    }

    @Override
    public List<CategoryVo> categoryTree() {
        List<CategoryVo> categoryList = categoryMapper.selectCategoriesList(null);
        if (categoryList == null || categoryList.size() == 0) {
            return categoryList;
        }
        List<CategoryVo> categoryVoList = categoryList.stream().filter(category -> category.getParentId() == null && category.getType().equals(0)).collect(Collectors.toList());
        Map<String, List<CategoryVo>> categoryMap = categoryList.stream().filter(category -> category.getParentId() != null && category.getType().equals(1)).collect(Collectors.groupingBy(category -> category.getParentId()));
        if (categoryVoList.size() > 0) {
            categoryVoList.forEach(categoryVo -> {
                categoryVo.setChildrenCategory(categoryMap.get(categoryVo.getCategoryId().toString()));
            });
        }
        return categoryVoList;
    }

    @Override
    public int updateSortingBatch(List<Category> categoryList) {
        return categoryMapper.updateSortingBatch(categoryList);
    }

    /**
     * 查询分类
     *
     * @param categoryId 分类主键
     * @return 分类
     */
    @Override
    public Category selectCategoryByCategoryId(Long categoryId) {
        return categoryMapper.selectCategoryByCategoryId(categoryId);
    }

    /**
     * 查询分类列表
     *
     * @param category 分类
     * @return 分类
     */
    @Override
    public List<Category> selectCategoryList(Category category)
    {
        return categoryMapper.selectCategoryList(category);
    }

    /**
     * 新增分类
     *
     * @param category 分类
     * @return 结果
     */
    @Override
    public int insertCategory(Category category) {
        category.setCreateTime(LocalDateTime.now());
        return categoryMapper.insertCategory(category);
    }

    /**
     * 修改分类
     *
     * @param category 分类
     * @return 结果
     */
    @Override
    public int updateCategory(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        return categoryMapper.updateCategory(category);
    }

    /**
     * 批量删除分类
     *
     * @param categoryIds 需要删除的分类主键
     * @return 结果
     */
    @Override
    public int deleteCategoryByCategoryIds(Long[] categoryIds) {
        return categoryMapper.deleteCategoryByCategoryIds(categoryIds);
    }

    /**
     * 删除分类信息
     *
     * @param categoryId 分类主键
     * @return 结果
     */
    @Override
    public int deleteCategoryByCategoryId(Long categoryId) {
        return categoryMapper.deleteCategoryByCategoryId(categoryId);
    }

    /**
     * 获取全部服务数据
     * @return
     */
    @Override
    public AjaxResult selectCategoriesList(Integer bizType) {
        //获取全部服务分类数据
        List<CategoryVo> categoryList = categoryMapper.selectCategoriesList(bizType);
        if (categoryList == null || categoryList.size() == 0) {
            return AjaxResult.success(null);
        }
        List<CategoryVo> categoryVoList = categoryList.stream().filter(category -> category.getParentId() == null && category.getType().equals(0)).collect(Collectors.toList());
        Map<String, List<CategoryVo>> categoryMap = categoryList.stream().filter(category -> category.getParentId() != null && category.getType().equals(1)).collect(Collectors.groupingBy(category -> category.getParentId()));
        if (categoryVoList.size() > 0) {
            categoryVoList.forEach(categoryVo -> {
                categoryVo.setChildrenCategory(categoryMap.get(categoryVo.getCategoryId().toString()));
            });
        }
        return AjaxResult.success(categoryVoList);
    }

    /**
     * 首页服务数据
     * @return
     */
    @Override
    public  List<CategoryVo> getHomeCategoriesList(Integer bizType) {
//        List<Category> categoryList = categoryMapper.getHomeCategoriesList(bizType);
        // 查询所有家政服务分类
        List<CategoryVo> categoryList = categoryMapper.selectCategoriesList(bizType);
        if (CollectionUtils.isEmpty(categoryList)) {
            return null;
        }
        // entity -> vo
        List<CategoryVo> categoryVoList = categoryList.stream().filter(Objects::nonNull).map(category -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(category, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());
        // 筛选出首页展示的一级分类
        List<CategoryVo> indexCategoryVoList = categoryVoList.stream()
                .filter(categoryVo -> Objects.equals(categoryVo.getIndexShow(), 1) && Objects.equals(categoryVo.getType(), 0)).collect(Collectors.toList());
        // 筛选出二级分类
        List<CategoryVo> secondaryCategoryVoList = categoryVoList.stream()
                .filter(category -> category.getParentId() != null && category.getType().equals(1)).collect(Collectors.toList());
        // 筛选出一级分类的子分类
        if (CollectionUtils.isNotEmpty(indexCategoryVoList) && CollectionUtils.isNotEmpty(secondaryCategoryVoList)) {
            Map<String, List<CategoryVo>> subCategoryMap = secondaryCategoryVoList.stream().filter(categoryVo -> !Objects.isNull(categoryVo.getParentId()) && Objects.equals(categoryVo.getType(), 1)).collect(Collectors.groupingBy(CategoryVo::getParentId));
            indexCategoryVoList.forEach(categoryVo -> {
                categoryVo.setChildrenCategory(subCategoryMap.get(String.valueOf(categoryVo.getCategoryId())));
            });
        }

        return indexCategoryVoList;
    }

    @Override
    public AjaxResult selectCategoriesListServer(Integer bizType) {
        //获取全部服务分类数据
        List<CategoryVo> categoryList = new ArrayList<>();
        CategoryVo allInfo = new CategoryVo();
        allInfo.setParentId(null);
        allInfo.setType(0);
        allInfo.setCategoryId(0l);
        allInfo.setCategoryName("全部服务");
        categoryList.add(allInfo);
        categoryList.addAll(categoryMapper.selectCategoriesList(bizType));
        if (categoryList == null || categoryList.size() == 0) {
            return AjaxResult.success(null);
        }
        List<CategoryVo> categoryVoList = categoryList.stream().filter(category -> category.getParentId() == null && category.getType().equals(0)).collect(Collectors.toList());
        Map<String, List<CategoryVo>> categoryMap = categoryList.stream().filter(category -> category.getParentId() != null && category.getType().equals(1)).collect(Collectors.groupingBy(category -> category.getParentId()));
        if (categoryVoList.size() > 0) {
            categoryVoList.forEach(categoryVo -> {
                List<CategoryVo> childList = new ArrayList<>();
                CategoryVo info = new CategoryVo();
                BeanUtils.copyProperties(categoryVo, info);  ;
                info.setChildrenCategory(null);
                childList.add(info);
                if(!ObjectUtils.isEmpty(categoryMap.get(categoryVo.getCategoryId().toString()))){
                    childList.addAll(categoryMap.get(categoryVo.getCategoryId().toString()));
                }
                categoryVo.setChildrenCategory(childList);
            });
        }
        return AjaxResult.success(categoryVoList);
    }

    @Override
    public Category selectCategoryByGoodsId(Long goodsId){
        return categoryMapper.selectCategoryByGoodsId(goodsId);
    }

    /**
     * （服务端）查询全部一级分类
     * @return
     */
    @Override
    public AjaxResult categoriesPublishList( Long serverId) {
        ServerUser serverUser = serverUserService.selectServerUserByServerId(serverId);
        if (serverUser == null) {
            return AjaxResult.error("获取用户信息失败");
        }

        //要返回的数据
        ArrayList<CategoryPublishVo> categoryPublishVos = new ArrayList<>();

        List<Category> categoryVoList = categoryMapper.selectCategoriesPublishList();
        if(ObjectUtils.isEmpty(categoryVoList) || categoryVoList.size()<1){
            return AjaxResult.success(categoryPublishVos);
        }
        for (Category categoryVo: categoryVoList) {
            CategoryPublishVo categoryPublishVo = new CategoryPublishVo();
            com.younike.common.utils.bean.BeanUtils.copyProperties(categoryVo, categoryPublishVo);
            categoryPublishVo.setAttention(serverUser.getFollowAll() == 1);
            categoryPublishVos.add(categoryPublishVo);
        }
        if (serverUser.getFollowAll() == 1) {
            return AjaxResult.success(categoryPublishVos);
        }

        //查询服务人员关注的分类
        //查询关注类型列表
        ServerUserFollow serverUserFollow = new ServerUserFollow();
        serverUserFollow.setServerUserId(serverId);
        List<ServerUserFollow> serverUserFollows = followService.selectServerUserFollowList(serverUserFollow);
        if(ObjectUtils.isEmpty(serverUserFollows) || serverUserFollows.size()<0){
            return AjaxResult.success(categoryPublishVos);
        }

        //关注的数据转成map
        Map<Long, ServerUserFollow> collect = serverUserFollows.stream().collect(Collectors.toMap(ServerUserFollow::getCategoryId, Function.identity()));
        for (CategoryPublishVo categoryVo : categoryPublishVos) {
            ServerUserFollow follow = collect.get(categoryVo.getCategoryId());
            if(ObjectUtils.anyNotNull(follow)){
                categoryVo.setAttention(true);
            }
        }

        return AjaxResult.success(categoryPublishVos);
    }

    /**
     * 查询所有一级分类
     * @return
     */
    @Override
    public List<Category> categoriesPublishIdList() {
       return categoryMapper.selectCategoriesPublishList();
    }

    /**
     * 首页服务分类（包含分类下数据）数据
     * @param bizType 家政维修
     * @param goodsType 商家 0，预定 1，团购 2
     * @return
     */
    @Override
    public AjaxResult getHomeCategoriesCountList(Integer bizType, Integer goodsType) {

//        查询首页以及分类
        List<CategoryVo> homeCategoriesList = this.getHomeCategoriesList(bizType);
        for (CategoryVo vo: homeCategoriesList) {
            GoodsParam goodsParam = new GoodsParam();
            goodsParam.setBizType(bizType);
            goodsParam.setParentId(vo.getCategoryId().intValue());
            if(goodsType==1){
                goodsParam.setIsGroupGoods("0");
                //查询预订服务数量
                List<GoodsVo> goodsVos = goodsService.seekCrewList(goodsParam);
                vo.setGoodsCount(goodsVos.size());

            }else if(goodsType==2){
                //查询团购服务数量
                goodsParam.setIsGroupGoods("1");
                //查询团购服务数量
                List<GoodsVo> goodsVos = goodsService.seekCrewList(goodsParam);
                vo.setGoodsCount(goodsVos.size());
            }else{
                //查询商家数量
                List<MerchantGoodsVo> merchantGoodsVos = goodsService.seekMerchantGoodsList(goodsParam);
                vo.setGoodsCount(merchantGoodsVos.size());
            }
        }
        //总数量
        int sum = homeCategoriesList.stream().mapToInt(CategoryVo::getGoodsCount).sum();
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("count",sum);
        stringObjectMap.put("list",homeCategoriesList);
        return AjaxResult.success(stringObjectMap);
    }

    /**
     * 根据服务人员id获取所在商家的分类列表
     * @param serverId
     * @return
     */
    @Override
    public AjaxResult serverCategoryList(Long serverId) {
        ServerUser serverUser = serverUserService.selectServerUserByServerId(serverId);
        if (serverUser == null) {
            return AjaxResult.error("获取用户信息失败");
        }
        if(ObjectUtils.isEmpty(serverUser.getMerchantId())){
            return AjaxResult.error("当前用户无所属商家");
        }

      
        //根据商家id查询分类数据
        MerchantCategory merchantCategory = new MerchantCategory();

        List<Category> categories = categoryMapper.serverCategoryList(serverUser.getMerchantId());
              

        return AjaxResult.success(categories);
    }
}
