/*
 *  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 com.youchain.basicdata.domain.Box;
import com.youchain.utils.FileUtil;
import com.youchain.utils.PageUtil;
import com.youchain.utils.QueryHelp;
import com.youchain.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import com.youchain.basicdata.repository.BoxRepository;
import com.youchain.basicdata.service.BoxService;
import com.youchain.basicdata.service.dto.BoxDto;
import com.youchain.basicdata.service.dto.BoxQueryCriteria;
import com.youchain.basicdata.service.mapstruct.BoxMapper;
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.List;
import java.util.Map;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * @author huojin
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-08-17
 **/
@Service
@RequiredArgsConstructor
public class BoxServiceImpl implements BoxService {

    private final BoxRepository boxRepository;
    private final BoxMapper boxMapper;
    private final EntityManager entityManager;
    @Override
    public Map<String, Object> queryAll(BoxQueryCriteria criteria, Pageable pageable) {
        Page<Box> page = boxRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(boxMapper::toDto));
    }

    @Override
    public List<BoxDto> queryAll(BoxQueryCriteria criteria) {
        return boxMapper.toDto(boxRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public BoxDto findById(Long id) {
        Box box = boxRepository.findById(id).orElseGet(Box::new);
        ValidationUtil.isNull(box.getId(), "Box", "id", id);
        return boxMapper.toDto(box);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BoxDto create(Box resources) {
        return boxMapper.toDto(boxRepository.save(resources));
    }

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

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

    @Override
    public void download(List<BoxDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (BoxDto box : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("物料ID", box.getItem());
            map.put("点位ID", box.getPoint());
            map.put("创建人", box.getCreateBy());
            map.put("修改人", box.getUpdateBy());
            map.put("创建时间", box.getCreateTime());
            map.put("修改时间", box.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Box getBoxByItem(long itemId) {
        return boxRepository.getBoxByItem(itemId);
    }

    @Override
    public Box getBoxByCode(String code) {
        return boxRepository.getBoxByCode(code);
    }

    @Override
    public Box toEntity(BoxDto boxDto) {
        return boxMapper.toEntity(boxDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refreshPointStatus() {
        String sql="update Point point set point.status='USED'  where point.id in (select box.point.id from Box box) and point.type='SHIP' ";
        Query query=entityManager.createQuery(sql);
        long num= query.executeUpdate();

        String sql2="update Point point set point.status='FREE'  where point.id not in (select box.point.id from Box box) and point.type='SHIP' ";
        Query query2=entityManager.createQuery(sql2);
        long num2= query2.executeUpdate();

    }
}
