package com.youchain.modules.quartz.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.s7connector.api.S7Connector;
import com.youchain.basicdata.domain.Item;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.basicdata.repository.ItemRepository;
import com.youchain.basicdata.repository.PointRepository;
import com.youchain.basicdata.repository.StockRepository;
import com.youchain.businessdata.domain.Task;
import com.youchain.businessdata.inputJson.OrderInfo;
import com.youchain.businessdata.rest.MoController;
import com.youchain.businessdata.rest.PlcController;
import com.youchain.businessdata.service.AgvTaskService;
import com.youchain.businessdata.service.MlsService;
import com.youchain.businessdata.service.MoService;
import com.youchain.businessdata.service.TaskService;
import com.youchain.exception.handler.ApiResult;
import com.youchain.modules.quartz.domain.QuartzLog;
import com.youchain.modules.quartz.repository.QuartzLogRepository;
import com.youchain.service.LogService;
import com.youchain.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static org.springframework.http.HttpStatus.BAD_REQUEST;


@Slf4j
@Service
public class plcTask {
    @Autowired
    public PlcController plcController;
    @Autowired
    public ItemRepository itemRepository;
    @Autowired
    public PointRepository pointRepository;
    @Autowired
    public MoService moService;
    @Autowired
    public MlsService mlsService;
    @Autowired
    public TaskService taskService;
    @Autowired
    public StockRepository stockRepository;
    @Autowired
    public QuartzLogRepository quartzLogRepository;
    @Autowired
    public LogService logService;
    public JSONObject getMoJson(String labelNo) {
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("ifaceCode", "MLS-WQ-003");
        jsonObject.put("sourceSystem", "WQ");
        JSONObject params=new JSONObject();
        params.put("labelNo",labelNo);
        params.put("orgId",808);
        params.put("pageNo",0);
        params.put("pageSize",10);
        jsonObject.put("params", params);
        return jsonObject;
    }
    public JSONObject getOrderJson(String deliveryHeaderId) {
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("ifaceCode", "MLS-WQ-002");
        jsonObject.put("sourceSystem", "WQ");
        JSONObject params=new JSONObject();
        params.put("deliveryHeaderId",deliveryHeaderId);
        params.put("orgId",808);
        params.put("pageNo",0);
        params.put("pageSize",10);
        jsonObject.put("params", params);
        return jsonObject;
    }
    public synchronized void plcTask() {
//        String mo="LB]A0006897]240625]12125300000145]200]240625104089]]";
//        String lx="05010010";
        S7ConnectorUtils.connect();
        String mo = S7ConnectorUtils.readMo(S7ConnectorUtils.s7Connector,12);
        String lx = S7ConnectorUtils.readMo(S7ConnectorUtils.s7Connector,0);
        //获取入库接驳口
        List<Point> srcPointList = pointRepository.findByAreaCode("入库接驳口");
        if (srcPointList.isEmpty()){
            System.out.println("入库接驳口不存在");
            throw new RuntimeException("入库接驳口不存在");
        }
        Point srcPoint = srcPointList.get(0);
        // 去重
        String keyMo=mo+":"+lx;
        if (keyMo.equals(srcPoint.getItemCode())){
            // 重复扫码
            srcPoint.setDescription("标签重复，清空标签");
            pointRepository.save(srcPoint);
            return;
        }else {
            srcPoint.setItemCode(mo+":"+lx);
            pointRepository.save(srcPoint);
        }

//        String mo="LB]A0006897]240625]12125300000145]200]240625104089]]";
//        String lx="05010010";
//        LB]A0006907]240522]12125300001741]50.00]240522554318]]
//        LB]A0006897]240625]12125300000145]200]240625104089]]
        if(mo.length()>10){
            if (!mo.substring(0, 2).equals("LB")){
                /*MO票不全，补全MO票，获取料箱吗*/
                mo=lx+mo;
                Stock stock = stockRepository.findFirstByStatus(BaseStatus.FREE);
                if (stock!=null){
                    lx=stock.getCode();
                }
            }
        }
        String[] mos = mo.split("]");
        if (!mo.isEmpty() && !lx.isEmpty() &&mos.length>5){
            String it = mos[3];// 料号
            String labelNo = mos[5];// 标签
            try {
                // 同步MO信息
                JSONObject moJson=getMoJson(labelNo);

                String moString = HttpPostUtil.sendPostReq(UrlApi.publicApi, moJson.toString(), mlsService.getToKen());
                String deliveryHeaderId = mlsService.getMoInfo(moString);
                // 获取单头
                JSONObject moBody=JSONObject.parseObject(moString);
                String moBodyData=moBody.getJSONObject("data").getJSONArray("list").getJSONObject(0).getString("deliveryHeaderId");;
                System.out.println("moBodyData:"+moBodyData);
                // 同步订单信息
                JSONObject orderJson=getOrderJson(moBodyData);
                String orderString = HttpPostUtil.sendPostReq(UrlApi.publicApi, orderJson.toString(), mlsService.getToKen());
                mlsService.getOrderInfo(orderString);

                // 验证物料是否存在
                // 验证标签是否已入库
                List<Task> taskList = taskService.findByLabelNo(labelNo);
                if (!taskList.isEmpty()) {
                    System.out.println("验证标签是否已入库"+labelNo);
                    srcPoint.setDescription("已有入库任务");
                    pointRepository.save(srcPoint);
                    return;
                }
                // 验证送货单状态 和 是否检验
                JSONObject orderBody=JSONObject.parseObject(orderString);
                JSONObject orderData = orderBody.getJSONObject("data");
                JSONArray orderList = orderData.getJSONArray("list");
                if (!orderList.isEmpty()){
                    JSONObject itemAsn = orderList.getJSONObject(0);
                    String iqcResult = itemAsn.getString("iqcResult");
                    String isIqcInspected = itemAsn.getString("isIqcInspected");
                    if (iqcResult.equals("ACCEPT")&&isIqcInspected.equals("Y")){

                    }else {
                        srcPoint.setDescription(labelNo + "检验结果错误" + deliveryHeaderId+" iqcResult:"+iqcResult+" isIqcInspected:"+isIqcInspected);
                        pointRepository.save(srcPoint);
                        return;
                    }
                }

                // 获取物料
                Item item = itemRepository.findByCode(it);
                // 获取容器
                Stock stock = stockRepository.findByCode(lx);
                // 验证容器状态
                if (stock.getStatus().equals(BaseStatus.USED)) {
                    srcPoint.setDescription("容器已入库");
                    pointRepository.save(srcPoint);
                    return;
                }
                try {
                    moService.scanMo(item, stock, srcPoint,labelNo);
                    S7ConnectorUtils.write(S7ConnectorUtils.s7Connector, 2);
                    srcPoint.setDescription("入库成功");
                    pointRepository.save(srcPoint);
                } catch(Exception e){
                    String ex="入库失败,MO票" + mo+",料箱码"+lx+",错误信息:"+e.getMessage();
                    /*List<QuartzLog> quartzLogList=quartzLogRepository.findByJobName("访问PLC");
                    if (quartzLogList.size()>0){
                        *//* 重复异常*//*
                        QuartzLog quartzLog=quartzLogList.get(0);
                        if (quartzLog.getJobName().equals("访问PLC")
                                &&quartzLog.getIsSuccess().equals(false)
                                &&quartzLog.getExceptionDetail().equals(ex)){
                            *//* 重复异常*//*
                        }else {
                            S7ConnectorUtils.write(S7ConnectorUtils.s7Connector, 1);
                        }
                    }*/
                    srcPoint.setDescription(ex);
                    pointRepository.save(srcPoint);
                    throw new RuntimeException(ex);
                }
            } catch (Exception e) {
                S7ConnectorUtils.write(S7ConnectorUtils.s7Connector, 1);
                srcPoint.setDescription("标签解析失败，异常出口");
                pointRepository.save(srcPoint);
                throw new RuntimeException(e.getMessage());
            }
        }else {
            throw new RuntimeException("扫码错误,MO票" + mo+",料箱码"+lx+"");
        }
    }
}
