/*
*  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.Area;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.service.dto.StockSmallDto;
import com.youchain.utils.*;
import jdk.internal.dynalink.beans.StaticClass;
import lombok.RequiredArgsConstructor;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.dto.PointDto;
import com.youchain.basicdata.service.dto.PointSmallDto;
import com.youchain.basicdata.service.dto.PointQueryCriteria;
import com.youchain.basicdata.service.mapstruct.PointMapper;
import org.hibernate.Criteria;
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.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author liuxue
* @date 2023-07-26
**/
@Service
@RequiredArgsConstructor
public class PointServiceImpl implements PointService {

    private final PointRepository pointRepository;
    private final PointMapper pointMapper;
    private final EntityManager entityMapper;

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

    @Override
    public List<PointDto> queryAll(PointQueryCriteria criteria){
        return pointMapper.toDto(pointRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }
    @Override
    public List<PointSmallDto> queryKyPointList(){
        List<Map<String,String>>  maps=pointRepository.getKyPointList();
        String irsStr = JSON.toJSONString(maps);
        List<PointSmallDto> evaUserResps = JSON.parseArray(irsStr,PointSmallDto.class);
        return  evaUserResps;
    }

    @Override
    public List<Point> getPoint(String type){
        String hql="select p from Point p where p.enabled=true and p.status='FREE' and (?1 is null or p.type=?1) ";
        Query query=entityMapper.createQuery(hql);
        query.setParameter(1,type);
        List<Point> ps=query.getResultList();
        return  ps;
    }


    @Override
    @Transactional
    public PointDto findById(Long id) {
        Point point = pointRepository.findById(id).orElseGet(Point::new);
        ValidationUtil.isNull(point.getId(),"Point","id",id);
        return pointMapper.toDto(point);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PointDto create(Point resources) {
        return pointMapper.toDto(pointRepository.save(resources));
    }

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

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

    @Override
    public void download(List<PointDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PointDto point : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("RCS代码", point.getCode());
            map.put("名称", point.getName());
            map.put("状态", point.getStatus());
            map.put("描述", point.getDescription());
            map.put("区域编码", point.getBeatCode());
            map.put("库区名称", point.getArea().getName());
            map.put("是否启用", point.getEnabled());
            map.put("仓库名称", point.getDept().getName());
            map.put("坐标X", point.getPosX());
            map.put("坐标Y", point.getPosY());
            map.put("坐标Z", point.getPosZ());
            map.put("类型", point.getType());
            map.put("热度", point.getHeat());
            map.put("创建人", point.getCreateBy());
            map.put("修改人", point.getUpdateBy());
            map.put("创建时间", point.getCreateTime());
            map.put("修改时间", point.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void queryPoint(String pointCode) {
        /*  String resultJson= HttpPostUtil.sendPostReq(UrlApi.agv_url, jsonObject.toString());//返回ResponseJson*/
        String resultJson = "{\n" +
                "\"status\":200,\n" +
                "\"message\":\"\",\n" +
                "\"data\":[{\n" +
                "\"pointCode\":\"xxxxxx\",\n" +
                "\"pointStatus\":0\n" +
                "}]\n" +
                "}";
        JSONObject resulObject = JSON.parseObject(resultJson);
        String code = resulObject.getString("status") == null ? "" : resulObject.getString("status");
        if (code.equals("200")) {


        }
    }

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