/*
 *  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 com.youchain.basicdata.service.impl;

import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.youchain.basicdata.domain.Area;

import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.basicdata.repository.AreaRepository;
import com.youchain.basicdata.service.AreaService;
import com.youchain.basicdata.service.dto.AreaDto;
import com.youchain.basicdata.service.dto.AreaQueryCriteria;
import com.youchain.basicdata.service.mapstruct.AreaMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;

/**
 * @author HJL
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-08-14
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class AreaServiceImpl implements AreaService {

    private final AreaRepository areaRepository;
    private final AreaMapper areaMapper;
    private final EntityManager entityMapper;

    @Override
    public Map<String, Object> queryAll(AreaQueryCriteria criteria, Pageable pageable) {
        Page<Area> page = areaRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(areaMapper::toDto));
    }

    @Override
    public List<AreaDto> queryAll(AreaQueryCriteria criteria) {
        return areaMapper.toDto(areaRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public AreaDto findById(Long id) {
        Area area = areaRepository.findById(id).orElseGet(Area::new);
        ValidationUtil.isNull(area.getId(), "Area", "id", id);
        return areaMapper.toDto(area);
    }

    @Override
    @Transactional
    public Area findEntityById(Long id) {
        Area area = areaRepository.findById(id).orElseGet(Area::new);
        ValidationUtil.isNull(area.getId(), "Area", "id", id);
        return area;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AreaDto create(Area resources) {
        return areaMapper.toDto(areaRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Area resources) {
        Area area = areaRepository.findById(resources.getId()).orElseGet(Area::new);
        ValidationUtil.isNull(area.getId(), "Area", "id", resources.getId());
        area.copy(resources);
        areaRepository.save(area);
    }

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

    @Override
    public void download(List<AreaDto> all, HttpServletResponse response) throws Exception {
        List<Map<String, Object>>  list= ExcelDownUtils.CreateMap(all,"Area");
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<AreaDto> getAreas(String type) {
        List<Area> areas = areaRepository.getAreas();
        return areaMapper.toDto(areas);
    }

    @Override
    public Area findByCode(String code) {
        String hql = "select t from Area t where t.code='" + code + "' or t.name='" + code + "' ";
        Query query = entityMapper.createQuery(hql);
        List<Area> ts = query.getResultList();
        if (ts.size() > 0) {
            return ts.get(0);
        }
        return null;
    }


    @Override
    public List<Area> queryByAreaCodes(List<String> codes) {
        if (CollectionUtils.isEmpty(codes)) {
            return Collections.emptyList();
        }
        //去重
        codes = codes.stream().filter(Objects::nonNull).distinct().collect(Collectors.toList());
        return areaRepository.queryByAreaCodes(codes);
    }

    @Override
    public Map<String, Area> queryByAreaCodesToMap(List<String> codes) {
        List<Area> items = queryByAreaCodes(codes);
        //封装成map
        Map<String, Area> itemMap = Maps.newHashMap();
        for (Area item : items) {
            itemMap.put(item.getName(), item);
            itemMap.put(item.getCode(), item);
        }
        return itemMap;
    }
}