/*
 *  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.businessdata.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.youchain.basicdata.domain.Box;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.basicdata.repository.StockRepository;
import com.youchain.basicdata.service.PointService;
import com.youchain.basicdata.service.impl.BoxServiceImpl;
import com.youchain.businessdata.domain.*;
import com.youchain.businessdata.inputJson.ReturnIssueInfo;
import com.youchain.businessdata.inputJson.ReturnIssueInfoParams;
import com.youchain.businessdata.inputJson.ReturnMoInfo;
import com.youchain.businessdata.inputJson.ReturnMoParams;
import com.youchain.businessdata.repository.AsnDetailRepository;
import com.youchain.businessdata.repository.TaskRepository;
import com.youchain.businessdata.service.*;
import com.youchain.businessdata.service.dto.OrderDto;
import com.youchain.modules.quartz.utils.TimeNumberUtils;
import com.youchain.modules.system.service.DictService;
import com.youchain.service.LogService;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.businessdata.repository.AgvTaskRepository;
import com.youchain.businessdata.service.dto.AgvTaskDto;
import com.youchain.businessdata.service.dto.AgvTaskQueryCriteria;
import com.youchain.businessdata.service.mapstruct.AgvTaskMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestBody;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;


/**
 * @author baobinglin
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-08-18
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class AgvTaskServiceImpl implements AgvTaskService {

    private final AgvTaskRepository agvTaskRepository;
    private final AgvTaskMapper agvTaskMapper;
    private final TaskRepository taskRepository;
    private final InventoryService inventoryService;
    private final InventoryLogService inventoryLogService;
    private final TaskService taskService;
    private final PointService pointService;
    private final PointRepository pointRepository;
    private final StockRepository stockRepository;
    private final AsnDetailRepository asnDetailRepository;
    private final EntityManager entityMapper;

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

    @Override
    public List<AgvTaskDto> queryAll(AgvTaskQueryCriteria criteria) {
        return agvTaskMapper.toDto(agvTaskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public AgvTaskDto findById(Integer id) {
        AgvTask agvTask = agvTaskRepository.findById(id).orElseGet(AgvTask::new);
        ValidationUtil.isNull(agvTask.getId(), "AgvTask", "id", id);
        return agvTaskMapper.toDto(agvTask);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AgvTaskDto create(AgvTask resources) {
        return agvTaskMapper.toDto(agvTaskRepository.save(resources));
    }

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

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

    @Override
    public void download(List<AgvTaskDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AgvTaskDto agvTask : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("容器码", agvTask.getStockCode());
            map.put("容器类型", agvTask.getStockTypeCode());
            map.put("起点位置", agvTask.getStartSlotCode());
            map.put("终点位置", agvTask.getEndSlotCode());
            map.put("容器当前位置", agvTask.getSlotCode());
            map.put("任务状态", agvTask.getStatus());
            map.put("任务类型", agvTask.getType());
            map.put("下游任务号", agvTask.getJobId());
            map.put("工作类型", agvTask.getJobType());
            map.put("优先级", agvTask.getJobPriority());
            map.put("强制优先级", agvTask.getJobPriorityType());
            map.put("任务组", agvTask.getJobForce());
            map.put("任务组执行顺序", agvTask.getJobForceAsc());
            map.put("返回报文", agvTask.getJobMessage());
            map.put("变动时间", agvTask.getJobMessageTime());
            map.put("创建时间", agvTask.getCreateTime());
            map.put("开始时间", agvTask.getStartTime());
            map.put("完成时间", agvTask.getEndTime());
            map.put("创建人", agvTask.getCreateBy());
            map.put("修改人", agvTask.getUpdateBy());
            map.put("修改时间", agvTask.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * @param agvTasks
     * @return
     */
    @Override
    public synchronized String sendAgvTaskImpl(AgvTask agvTasks) {

        JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());

        Map<String, Object> objMap = new LinkedHashMap<>();
        objMap.put("orgId", agvTasks.getId());//库存组织 ID
        objMap.put("requestId", agvTasks.getId());//请求 id
        objMap.put("missionCode", agvTasks.getId());//任务编号

        objMap.put("missionType", agvTasks.getJobType());//货 架 ( 托 盘 ) 移动 RACK_MOVE
        String viewBoardType = "";
        Point point = pointService.findByCode(agvTasks.getStartSlotCode(), null, null, null, null);
        //到达上视自动识别
        if (point.getArea().getName().equals("1F满车入库线边区") || point.getArea().getName().equals("2F满车入库线边区") || point.getArea().getName().equals("1F空车线边区") || point.getArea().getName().equals("1F空车线边区")) {
            viewBoardType = "IDENTIFY_REQUIRE";
        }
        objMap.put("viewBoardType", viewBoardType);//上视识别类型；需要 IDENTIFY_REQUIRE 不需要NORMAL
        objMap.put("robotType", "LIFT");//机器人功能类型
        JSONArray robotModels = new JSONArray();
        objMap.put("robotModels", robotModels);//机器人具体型号
        JSONArray robotIds = new JSONArray();
        objMap.put("robotIds", robotIds);//机器人编号
        objMap.put("priority", "1");//数值越小，优先级越高，默认是 1
        objMap.put("containerModelCode", "");//容器模型编码
        objMap.put("containerCode", agvTasks.getStockCode() == null ? "" : agvTasks.getStockCode());//容器编号
        objMap.put("templateCode", "");//作业流程模板编号
        objMap.put("lockRobotAfterFinish", false);//是否需要流程结束后机器人保持任务锁定状态
        objMap.put("unlockRobotId", "");//解锁当前小车的在上个任务的锁定状态
        objMap.put("unlockMissionCode", "");//当前小车的上一个任务
        objMap.put("idleNode", "");//作业流程完成后，指定机器人停放区域/点
        JSONArray missionDataArray = new JSONArray();
        JSONObject missionDataObj = new JSONObject(new LinkedHashMap<>());
        Map<String, Object> missionDataMap = new LinkedHashMap<>();
        missionDataMap.put("sequence", 1);//序号
        missionDataMap.put("position", agvTasks.getStartSlotCode());//起始点
        missionDataMap.put("type", "NODE_POINT");//作业位置类型：点位：NODE_POINT
        missionDataMap.put("putDown", false);//作业点位是否需要放下货架
        missionDataMap.put("passStrategy", "AUTO");//当前任务点结束后放行策略
        missionDataMap.put("waitingMillis", "0");//自动触发离开当前任务节点的时间，默认单位:毫秒
        missionDataObj.putAll(missionDataMap);
        missionDataArray.add(missionDataObj);

        JSONObject missionDataObj2 = new JSONObject(new LinkedHashMap<>());
        Map<String, Object> missionDataMap2 = new LinkedHashMap<>();
        missionDataMap2.put("sequence", 2);//序号
        missionDataMap2.put("position", agvTasks.getEndSlotCode());//目标点
        missionDataMap2.put("type", "NODE_POINT");//作业位置类型：点位：NODE_POINT
        missionDataMap2.put("putDown", true);//作业点位是否需要放下货架
        missionDataMap2.put("passStrategy", "AUTO");//当前任务点结束后放行策略
        missionDataMap2.put("waitingMillis", "0");//自动触发离开当前任务节点的时间，默认单位:毫秒
        missionDataObj2.putAll(missionDataMap2);
        missionDataArray.add(missionDataObj2);


        objMap.put("missionData", missionDataArray);
        jsonObject.putAll(objMap);
        System.out.println(jsonObject.toString());
        String resultJson = HttpPostUtil.sendPostReq(UrlApi.submitMission, jsonObject.toString());//返回ResponseJson*/
        JSONObject resulObject = JSON.parseObject(resultJson);
        String code = "0";
        code = resulObject.getString("code") == null ? "" : resulObject.getString("code");
        if (code.equals("0")) {
            agvTasks.setJobForce(agvTasks.getId().toString());//任务组
            agvTasks.setJobForceAsc((1));
            agvTasks.setStatus(BizStatus.ATCALL);
            agvTasks.setJobMessage(resultJson);
            agvTasks.setReqMessage(jsonObject.toString());
            agvTasks.setStartTime(new Timestamp(new Date().getTime()));
            update(agvTasks);
        } else {
            agvTasks.setJobMessage(resultJson);
            agvTasks.setReqMessage(jsonObject.toString());
            update(agvTasks);
        }
        return resultJson;
    }

    @Override
    public synchronized String sendAgvTaskLXImpl(List<AgvTask> agvTasks) {
        JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());
        String agvCode = TimeNumberUtils.getKmResCode() + agvTasks.get(0).getId()+"_"+agvTasks.get(0).getBeScan();
//        String agvCode = TimeNumberUtils.getLXTaskCode();

        Map<String, Object> objMap = new LinkedHashMap<>();
        objMap.put("orgId", agvCode);//库存组织 ID(或工厂代码，供应商代码)
        objMap.put("requestId", agvCode);//请求 id
        objMap.put("missionCode", agvCode);//任务编号
        objMap.put("missionType", "PICKER_MOVE");//任务类型 ：料箱
        objMap.put("viewBoardType", "");//上视识别类型:
        objMap.put("robotType", "PICKER");//机器人功能类型
        JSONArray robotModels = new JSONArray();
        objMap.put("robotModels", robotModels);//机器人具体型号
        JSONArray robotIds = new JSONArray();
        objMap.put("robotIds", robotIds);//机器人编号
        objMap.put("priority", "1");//数值越小，优先级越高，默认是 1
        objMap.put("templateCode", "");//作业流程模板编号
        objMap.put("lockRobotAfterFinish", false);//是否需要流程结束后机器人保持任务锁定状态
        objMap.put("unlockRobotId", "");//解锁当前小车的在上个任务的锁定状态
        objMap.put("unlockMissionCode", "");//当前小车的上一个任务
        objMap.put("idleNode", "");//作业流程完成后，指定机器人停放区域/点

        JSONArray missionDataArray = new JSONArray();
        for (int i = 0; i < agvTasks.size(); i++) {
            AgvTask agvTask = agvTasks.get(i);
            JSONObject missionDataObj = new JSONObject(new LinkedHashMap<>());
            Map<String, Object> missionDataMap = new LinkedHashMap<>();
            missionDataMap.put("sequence", (i + 1));//序号
            missionDataMap.put("binCode", agvTask.getStockCode());//料箱号

            Point startPoint=pointRepository.findByCode(agvTask.getStartSlotCode());
            missionDataMap.put("startPosition", startPoint.getBeatCode());//料箱所在的起始点位
            missionDataMap.put("startSlotCode", agvTask.getStartSlotCode());//料箱所在的起始槽位
            //取料箱时之前是否需确认 点位
            if (startPoint.getCode().equals("SSX-01-001")){
                missionDataMap.put("takeActionConfirm", true);
            }else {
                missionDataMap.put("takeActionConfirm", false);
            }
            Point endPoint=pointRepository.findByCode(agvTask.getEndSlotCode());
            missionDataMap.put("endPosition", endPoint.getBeatCode());//料箱所在的目标点位
            missionDataMap.put("endSlotCode", agvTask.getEndSlotCode());//料箱所在的目标槽位
            missionDataMap.put("putActionConfirm", false);//放料箱时之前是否需要确认
            missionDataObj.putAll(missionDataMap);
            missionDataArray.add(missionDataObj);
        }

        objMap.put("missionData", missionDataArray);
        jsonObject.putAll(objMap);
        String resultJson = HttpPostUtil.sendPostReq(UrlApi.submitMission, jsonObject.toString());
        if (resultJson== null|| resultJson.isEmpty()) {
            return null;
        }
        JSONObject resulObject = JSON.parseObject(resultJson);
        String code = resulObject.getString("code") == null ? "" : resulObject.getString("code");

        if (code.equals("0")) {
            for (int i = 0; i < agvTasks.size(); i++) {
                AgvTask agvTask = agvTasks.get(i);
                agvTask.setJobForce(agvCode);//任务组
                agvTask.setJobForceAsc((i + 1));
                agvTask.setStatus(BizStatus.ATCALL);
                agvTask.setJobMessage(resultJson);
                agvTask.setReqMessage(jsonObject.toString());
                agvTask.setStartTime(new Timestamp(new Date().getTime()));
                update(agvTask);
            }
        } else {
            for (int i = 0; i < agvTasks.size(); i++) {
                AgvTask agvTask = agvTasks.get(i);
                agvTask.setJobMessage(resultJson);
                agvTask.setReqMessage(jsonObject.toString());
                update(agvTask);
            }
        }
        return resultJson;
    }

    @Override
    public synchronized String containerIn(String containerCode, String position) {
        JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());
        jsonObject.put("requestId", String.valueOf(new Date().getTime()));//请求 id
        jsonObject.put("containerType", "");//容器类型
        jsonObject.put("containerCode", containerCode);//容器编号
        jsonObject.put("position", position);//容器当前位置
        jsonObject.put("enterOrientation", "");//角度
        return jsonObject.toString();
    }

    @Override
    public synchronized String containerOut(String containerCode) {
        JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());
        jsonObject.put("requestId", String.valueOf(new Date().getTime()));//请求 id
        jsonObject.put("containerType", "");//容器类型
        jsonObject.put("containerCode", containerCode);//容器编号
        jsonObject.put("position", "");//容器当前位置
        return jsonObject.toJSONString();
    }

    @Override
    public void getConveyorState(String conveyorId) {
        /*  String resultJson= HttpPostUtil.sendPostReq(UrlApi.agv_url, jsonObject.toString());//返回ResponseJson*/
        String resultJson = "{\n" + "\"success\":true,\n" + "\"code\":200,\n" + "\"message\":\"\",\n" + "\"conveyorId\":\"1\",\n" + "\"state\":\"1\"\n" + "}";
        JSONObject resulObject = JSON.parseObject(resultJson);
        String code = resulObject.getString("code") == null ? "" : resulObject.getString("code");
        if (code.equals("200")) {
            /**
             * state
             * 1：允许取货
             * 2：允许放货
             * 3、不允许取货
             * 4、不允许放货
             */
            String state = resulObject.getString("state") == null ? "" : resulObject.getString("state");
            if (state.equals("1")) {

            } else if (state.equals("2")) {

            } else if (state.equals("3")) {

            } else if (state.equals("4")) {

            }
        }

    }

    public AgvTask toEntity(AgvTaskDto agvTaskDto) {
        return agvTaskMapper.toEntity(agvTaskDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void agvTaskCallback(AgvTask agvTask, Task task, String status) {

        if (status.equals(BizStatus.PICKER_SEND)) {
            //入库
            if (agvTask.getType().equals(BizStatus.ASN)&&task!=null) {
                //增加库存
                AsnDetail ad = task.getAsnDetail();
                ad.setReceivedQty(ad.getOrderQty());
                ad.setStatus(BizStatus.RECEIVED);
                asnDetailRepository.save(ad);
                task.setTaskStatus(BizStatus.FINISH);
                task.setMoveQty(task.getPlanQty());
                taskService.update(task);
                Stock stock = task.getSrcStock();
                List<Inventory> inventoryList = inventoryService.queryInventory(stock);
                for (Inventory inventory : inventoryList) {
                    Long[] ids = new Long[1];
                    ids[0] = inventory.getId();
                    inventoryService.deleteAll(ids);
                }

                //生成库存
                Inventory inventory = inventoryService.getInventory(task.getItemKey(), task.getDstPoint(), task.getSrcStock(), task.getDept(), BizStatus.RECEIVING_UP);
                inventory.setQuantity(task.getPlanQty());
                inventoryService.update(inventory);
                inventoryLogService.storeInventoryLog(BizStatus.RECEIVING_UP, BizStatus.ADD, null, task.getItemKey(), task.getSrcPoint(), task.getDstPoint(), task.getSrcStock(), task.getSrcStock(), task.getPlanQty(), task.getPlanQty(), BizStatus.ASN, ad.getId(), inventory.getId(), ad.getRemark());

            }
            //任务完成
            agvTask.setStatus(BizStatus.FINISH);
            agvTask.setEndTime(new Timestamp(new Date().getTime()));
            this.update(agvTask);

        } else if (status.equals(BizStatus.CANCEL)) {
            if (agvTask.getType().equals(BizStatus.ASN)&&task!=null) {
                //取消入库
                /* 关闭入库单*/
                AsnDetail ad = task.getAsnDetail();
                ad.setStatus(BizStatus.CLOSE);
                asnDetailRepository.save(ad);
                /* 解绑容器库位*/
                Stock stock=task.getSrcStock();
                Point point=stock.getPoint();
                if (point!=null){
                    point.setStatus(BaseStatus.FREE);
                    pointRepository.save(point);
                }
                stock.setStatus(BaseStatus.FREE);
                stock.setPoint(null);
                stock.setName(stock.getCode());
                stockRepository.save(stock);
                /*关闭Task*/
                task.setTaskStatus(BizStatus.CLOSE);
                taskRepository.save(task);
            }
            // 任务取消
            agvTask.setStatus(BizStatus.CANCEL);
            agvTask.setEndTime(new Timestamp(new Date().getTime()));
            this.update(agvTask);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void agvTaskCallback(AgvTask agvTask, String status, String containerCode) {

        if (status.equals(BizStatus.PICKER_SEND)) {
            //小件：AGV把料箱放到料箱车上扣减库存

            List<Task> taskList = taskRepository.getAgvTaskList(agvTask.getId());
            //扣除库存
            for (Task task : taskList) {
                taskService.pickConfirm(task.getId(), task.getPlanQty());
                /*try {
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage());
                }*/
            }

            agvTask.setStatus(BizStatus.FINISH);
            agvTask.setEndTime(new Timestamp(new Date().getTime()));
            this.update(agvTask);


        }
    }

    @Override
    public double queryBillCodeSum(String billCode) {
        String hql = "select sum(task.moveQty) from Task task where  task.billCode= :billCode";
        Query query = entityMapper.createQuery(hql);
        query.setParameter("billCode", billCode);
        List<Double> orderNumberSumList = query.getResultList();
        if (orderNumberSumList.size() > 0) {
            return orderNumberSumList.get(0);
        }
        return 0d;

    }

    @Override
    public AgvTask findByjobCode(String jobForce, String containerCode) {
        String hql = " from AgvTask agv where  agv.jobForce= :jobForce and agv.stockCode= :containerCode";
        Query query = entityMapper.createQuery(hql);
        query.setParameter("jobForce", jobForce);
        query.setParameter("containerCode", containerCode);
        List<AgvTask> agvTaskList = query.getResultList();
        if (agvTaskList.size() > 0) {
            return agvTaskList.get(0);
        }
        return null;
    }

    @Override
    public List<AgvTask> findByjobCode(String jobForce) {
        String hql = " from AgvTask agv where  agv.jobForce= :jobForce";
        Query query = entityMapper.createQuery(hql);
        query.setParameter("jobForce", jobForce);
        List<AgvTask> agvTaskList = query.getResultList();
        return agvTaskList;
    }

    @Override
    public List<AgvTask> queryByAgvTask(String status, String type) {
        String hql = " from AgvTask agv where  agv.status= :status and agv.type= :type";
        Query query = entityMapper.createQuery(hql);
        query.setParameter("status", status);
        query.setParameter("type", type);
        List<AgvTask> agvTaskList = query.getResultList();
        return agvTaskList;
    }

    @Override
    public void closeAgvTask(Long id) {
        AgvTask agvTask=agvTaskRepository.getById(Math.toIntExact(id));
        agvTask.setStatus(BizStatus.CLOSE);
        agvTaskRepository.save(agvTask);
    }

}
