/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package cn.ysk.cashier.service.impl.productimpl;

import cn.ysk.cashier.dto.product.TbProductSortCriteria;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.pojo.product.TbProductGroup;
import cn.ysk.cashier.pojo.product.TbShopCategory;
import cn.ysk.cashier.utils.ValidationUtil;
import cn.ysk.cashier.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.repository.product.TbShopCategoryRepository;
import cn.ysk.cashier.service.product.TbShopCategoryService;
import cn.ysk.cashier.dto.product.TbShopCategoryDto;
import cn.ysk.cashier.dto.product.TbShopCategoryQueryCriteria;
import cn.ysk.cashier.mapper.product.TbShopCategoryMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import cn.ysk.cashier.utils.PageUtil;
import cn.ysk.cashier.utils.QueryHelp;

import java.time.Instant;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author lyf
* @date 2024-01-08
**/
@Service
@RequiredArgsConstructor
public class TbShopCategoryServiceImpl implements TbShopCategoryService {

    private final TbShopCategoryRepository tbShopCategoryRepository;
    private final TbShopCategoryMapper tbShopCategoryMapper;

    @Override
    public Map<String,Object> queryAll(TbShopCategoryQueryCriteria criteria){
        PageRequest sort = PageRequest.of(criteria.getPage(), criteria.getSize(), Sort.by("sort"));
        Page<TbShopCategory> page = tbShopCategoryRepository.findAllBy(criteria.getShopId(), sort);

        List<Integer> treeId = new ArrayList<>();
        for (TbShopCategory category : page.getContent()) {
            Integer ids = category.getId();
            treeId.add(ids);
        }
        //找到子分类
        List<TbShopCategory> children = tbShopCategoryRepository.findChildren(treeId);
        if (children.isEmpty()){
            return PageUtil.toPage(page.map(tbShopCategoryMapper::toDto));
        }

        List<TbShopCategoryDto> dto = new ArrayList<>();
        for (TbShopCategory category : page.getContent()) {
            List<TbShopCategory> tbShopCategoryChildren = new ArrayList<>();
            for (TbShopCategory tbShopCategory :children) {
                if (tbShopCategory.getTree().equals(category.getId())){
                    tbShopCategoryChildren.add(tbShopCategory);
                }
            }

            TbShopCategoryDto tbShopCategoryDto = new TbShopCategoryDto();
            tbShopCategoryDto.setChildrenList(tbShopCategoryChildren);
            BeanUtils.copyProperties(category, tbShopCategoryDto);
            dto.add(tbShopCategoryDto);
        }
        List<TbShopCategoryDto> result = dto.stream()
                .filter(d -> d.getTree()==null || d.getId().equals(d.getTree()))
                .collect(Collectors.toList());

        return PageUtil.toPage(result, page.getTotalElements()-children.size());
    }

//    @Override
//    public List<TbShopCategoryDto> queryAll(TbShopCategoryQueryCriteria criteria){
//        return tbShopCategoryMapper.toDto(tbShopCategoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
//    }

    @Override
    @Transactional
    public TbShopCategoryDto findById(Integer id) {
        TbShopCategory tbShopCategory = tbShopCategoryRepository.findById(id).orElseGet(TbShopCategory::new);
        ValidationUtil.isNull(tbShopCategory.getId(),"TbShopCategory","id",id);
        return tbShopCategoryMapper.toDto(tbShopCategory);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TbShopCategory create(TbShopCategory resources) {
        resources.setCreatedAt(Instant.now().toEpochMilli());
        resources.setUpdatedAt(Instant.now().toEpochMilli());
        TbShopCategory byName = tbShopCategoryRepository.findByName(resources.getName(), resources.getShopId());
        if (byName != null){
            throw new BadRequestException("分类名称重复");
        }
        if (StringUtils.isNotBlank(resources.getPid())){
            resources.setTree(Integer.valueOf(resources.getPid().trim()));
        }
        TbShopCategory save = tbShopCategoryRepository.save(resources);
        save.setSort(save.getId());
        return tbShopCategoryRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TbShopCategory resources) {
        TbShopCategory tbShopCategory = tbShopCategoryRepository.findById(resources.getId()).orElseGet(TbShopCategory::new);
        if (resources.getName() == null || resources.getShopId() == null){
            throw new BadRequestException("必要参数为空");
        }
        resources.setUpdatedAt(Instant.now().toEpochMilli());
        ValidationUtil.isNull( tbShopCategory.getId(),"TbShopCategory","id",resources.getId());
        tbShopCategory.copy(resources);
        tbShopCategoryRepository.save(tbShopCategory);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            tbShopCategoryRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<TbShopCategoryDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TbShopCategoryDto tbShopCategory : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("分类名称", tbShopCategory.getName());
            map.put("简称", tbShopCategory.getShortName());
            map.put("分类层级", tbShopCategory.getTree());
            map.put("上级分类id-为0则表示是顶级", tbShopCategory.getPid());
            map.put("图标", tbShopCategory.getPic());
            map.put("商户Id", tbShopCategory.getMerchantId());
            map.put("店铺Id", tbShopCategory.getShopId());
            map.put("颜色格式标识", tbShopCategory.getStyle());
            map.put("是否显示：1显示 0不显示", tbShopCategory.getIsShow());
            map.put("分类描述", tbShopCategory.getDetail());
            map.put("排序", tbShopCategory.getSort());
            map.put("关键词", tbShopCategory.getKeyWord());
            map.put(" createdAt",  tbShopCategory.getCreatedAt());
            map.put(" updatedAt",  tbShopCategory.getUpdatedAt());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}