/*
 *  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.alibaba.fastjson.JSONObject;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.basicdata.service.dto.ItemDto;
import com.youchain.businessdata.domain.AsnDetail;
import com.youchain.modules.mnt.websocket.MsgType;
import com.youchain.modules.mnt.websocket.SocketMsg;
import com.youchain.modules.mnt.websocket.WebSocketServer;
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 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);
        log.info(irsStr);
        List<StockSmallDto> evaUserResps = JSON.parseArray(irsStr, StockSmallDto.class);
        return evaUserResps;
    }

    @Override
    public List<StockSmallDto> queryStockList2(String code) {
        List<Object[]> objs = stockRepository.getStockList2(code);
        List<StockSmallDto> list = EntityUtils.castEntity(objs, StockSmallDto.class, new StockSmallDto());
        log.info("fangfa2 " + list.toString());
        return list;
    }

    @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());
        stock.copy(resources);
        stockRepository.save(stock);
    }

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

    @Override
    public void download(List<StockDto> all, HttpServletResponse response) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();
        for (StockDto stock : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("容器代码", stock.getCode());
            map.put("上级容器ID", stock.getPid());
            map.put("仓库ID", stock.getDept().getName());
            map.put("子容器数量", stock.getSubCount());
            map.put("容器名称", stock.getName());
            map.put("类型名称", stock.getStockType().getName());
            map.put("容器使用重量", stock.getUseWeight());
            map.put("容器使用体积", stock.getUseSize());
            map.put("容器重量占用率", stock.getUsageWeight());
            map.put("容器体积占用率", stock.getUsageSize());
            map.put("状态", stock.getEnabled());
            map.put("创建人", stock.getCreateBy());
            map.put("修改人", stock.getUpdateBy());
            map.put("创建时间", stock.getCreateTime());
            map.put("修改时间", stock.getUpdateTime());
            map.put("顶级容器ID", stock.getTopId());
            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 findByPointCode(String code) {
        String hql = " from Stock t where t.point.code='" + code + "'";
        Query query = entityMapper.createQuery(hql);
        List<Stock> stockList = query.getResultList();
        if (stockList.size() > 0) {
            return stockList.get(0);
        }
        return null;
    }

    @Override
    public Stock findByKStock(String areaName) {
        String hql = " from Stock t where  t.point.id>0 and t.point.status='USED' and t.status='FREE' and t.point.type='STORAGE' ";
        if (areaName.equals(AreaNameDic.QTYK) || areaName.equals(AreaNameDic.HTYK)) {
            hql += " and t.point.area.name in ('前后桶空车区','前后桶部装空车缓存区')";
        } else {
            hql += " and t.point.area.name ='" + areaName + "'";
        }
        Query query = entityMapper.createQuery(hql);
        List<Stock> stockList = query.getResultList();
        if (stockList.size() > 0) {
            return stockList.get(0);
        }
        return null;
    }


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

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

    @Override
    public String stockMsg(String msg) {
        try {
            String message = JSONObject.toJSONString(new SocketMsg(msg, MsgType.INFO));
            WebSocketServer.sendInfo(new SocketMsg(msg, MsgType.INFO), "stock");
            return message;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";

    }

    @Override
    public void stockShangJia() {

    }
}
