package com.fzm.mall.server.admin.distribution.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.admin.distribution.entity.dto.DictCnProvinceDTO;
import com.fzm.mall.server.admin.distribution.mapper.DictCnProvinceMapper;
import com.fzm.mall.server.admin.distribution.model.DictCnProvince;
import com.fzm.mall.server.admin.distribution.service.IDictCnProvinceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wulixian
 * @since 2021-04-06
 */
@Service
@Transactional
public class DictCnProvinceServiceImpl extends ServiceImpl<DictCnProvinceMapper, DictCnProvince> implements IDictCnProvinceService {

    @Override
    public List<DictCnProvinceDTO> listAll() {
        QueryWrapper<DictCnProvince> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("region").orderByDesc("area_name");
        List<DictCnProvince> list = list(queryWrapper);

        Map<String, List<DictCnProvince>> map = list.stream().collect(Collectors.groupingBy(DictCnProvince::getRegion));
        List<DictCnProvinceDTO> result = new ArrayList<>(map.size());
        Iterator<Map.Entry<String, List<DictCnProvince>>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, List<DictCnProvince>> next = iterator.next();
            DictCnProvinceDTO dto = new DictCnProvinceDTO();
            dto.setRegion(next.getKey());
            dto.setProvinceList(next.getValue());
            result.add(dto);
        }
        return result;
    }
}
