/*
 *  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.alibaba.fastjson.JSON;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.basicdata.service.dto.ItemDto;
import com.youchain.businessdata.domain.AsnDetail;
import com.youchain.businessdata.domain.Inventory;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.basicdata.repository.StockRepository;
import com.youchain.basicdata.service.StockService;
import com.youchain.basicdata.service.dto.StockDto;
import com.youchain.basicdata.service.dto.StockSmallDto;
import com.youchain.basicdata.service.dto.StockQueryCriteria;
import com.youchain.basicdata.service.mapstruct.StockMapper;
import lombok.extern.slf4j.Slf4j;
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 liuxue
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-07-28
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class StockServiceImpl implements StockService {

    private final StockRepository stockRepository;
    private final PointRepository pointRepository;
    private final StockMapper stockMapper;
    private final EntityManager entityMapper;

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

    @Override
    public List<StockDto> queryAll(StockQueryCriteria criteria) {
        return stockMapper.toDto(stockRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public List<StockSmallDto> queryKyStockList(String code) {
        List<Map<String, String>> maps = stockRepository.getKyStockList(code);
        String irsStr = JSON.toJSONString(maps);
        List<StockSmallDto> evaUserResps = JSON.parseArray(irsStr, StockSmallDto.class);
        return evaUserResps;
    }

    @Override
    @Transactional
    public StockDto findById(Long id) {
        Stock stock = stockRepository.findById(id).orElseGet(Stock::new);
        ValidationUtil.isNull(stock.getId(), "Stock", "id", id);
        return stockMapper.toDto(stock);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StockDto create(Stock resources) {
        return stockMapper.toDto(stockRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Stock resources) {
        Stock stock = stockRepository.findById(resources.getId()).orElseGet(Stock::new);
//        ValidationUtil.isNull(stock.getId(), "Stock", "id", resources.getId());
        if (!(stock.getPoint()+"").equals(resources.getPoint()+"")){
            // 库位变化
            Point startPoint=stock.getPoint();
            if (startPoint!=null){
                /* 清空原库位*/
                startPoint.setStatus(BaseStatus.FREE);
                pointRepository.save(startPoint);
            }
            Point endPoint=resources.getPoint();
            if (endPoint!=null){
                /* 占用目标库位*/
                endPoint.setStatus(BaseStatus.USED);
                pointRepository.save(endPoint);
            }
        }
        stockRepository.save(resources);
    }

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

    @Override
    public void download(List<StockDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (StockDto stock : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("代码", stock.getCode());
            map.put("类型", stock.getStockType().getCode());
            if (stock.getPoint()!=null){
                map.put("点位", stock.getPoint().getCode());
            }else {
                map.put("点位", "");
            }
            map.put("是否启用", stock.getEnabled());
            list.add(map);
        }

        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Stock toEntity(StockDto stockDto) {
        return stockMapper.toEntity(stockDto);
    }

    @Override
    public Stock findByCode(String code, String status) {
        String hql = "select t from Stock t where t.code='" + code + "'";
        if (status != null && status.length() > 0) {
            hql += " and t.status='" + status + "'";
        }
        Query query = entityMapper.createQuery(hql);
        List<Stock> ts = query.getResultList();
        if (ts.size() > 0) {
            return ts.get(0);
        }
        return null;
    }

    @Override
    public Stock findByKStock(String areaName) {
        String hql = " from Stock t where  t.point.area.name ='" + areaName + "' and t.point.id>0 and t.point.status='USED' and t.status='FREE' and t.point.type='STORAGE' ";
        Query query = entityMapper.createQuery(hql);
        List<Stock> stockList = query.getResultList();
        if (stockList.size() > 0) {
            return stockList.get(0);
        }
        return null;
    }

    @Override
    public String getItemCode(String stockCode) {
        String itemCode="";
        String hql = " from Inventory inv where inv.stock.code='" + stockCode + "' and inv.quantity-inv.queuedQty>0 ";
        Query query = entityMapper.createQuery(hql);
        List<Inventory> inventoryList = query.getResultList();
        if (inventoryList.size() > 0) {
            itemCode=inventoryList.get(0).getItemKey().getItem().getCode();
        }
        return itemCode;
    }

}
