package org.nl.quartz.task;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.nl.acs.agv.server.ZheDaAgvService;
import org.nl.acs.device.domain.Device;
import org.nl.acs.device_driver.basedriver.standard_inspect_site.StandardInspectSiteDeviceDriver;
import org.nl.acs.device_driver.tianneng.site.SiteDeviceDriver;
import org.nl.acs.instruction.domain.Instruction;
import org.nl.acs.instruction.service.InstructionService;
import org.nl.acs.opc.DeviceAppService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 查询AGV任务状态
 */
@Slf4j
@Component
public class QueryZDAgvTaskStatus {

    @Autowired
    InstructionService instructionService;

    @Autowired
    ZheDaAgvService agvService;

    @Autowired
    DeviceAppService deviceAppService;


    public void run() throws Exception {
        try {
            log.info("自动线程开始查询浙大AGV任务状态");
            HttpResponse response2 = agvService.queryAgvInstStatus("1");
            //查询AGV指令列表
            JSONArray inst_rows2 = JSONArray.parseArray(response2.body());
            //            JSONArray inst_rows2 = JSONArray.parseArray("");
            for (int i = 0; i < inst_rows2.size(); i++) {
                JSONObject inst_jo = inst_rows2.getJSONObject(i);
                String inst_code = inst_jo.getString("task_code");
                Instruction inst = instructionService.findByCodeFromCache(inst_code);
                if (ObjectUtil.isEmpty(inst)){
                    continue;
                }
                //反馈结果状态
                log.info("instcode：" + inst_code + "," + inst_jo.toString());

                String status = inst_jo.getString("status");
                String vehicle = "";
                //正在执行指令agv车号
                if (!StrUtil.isEmpty(inst_jo.getString("vehicle"))) {
                    vehicle = inst_jo.getString("vehicle");
                    inst.setCarno(vehicle);
                }
                //							RAW：初始状态
                //							ACTIVE：业务订单已激活
                //							DISPATCHABLE：业务订单已通过系统验证，等待被调度执行
                //							BEING_PROCESSED：业务订单正在被执行
                //							WITHDRAWN：业务订单已被撤销
                //							FINISHED：业务订单已完成
                //							FAILED：业务订单已失败
                //							UNROUTABLE：无法规划该业务订单的执行路线
                //执行中
                if ("BEING_PdROCESSED".equals(status) || "ACTIVE".equals(status)) {
                    if (inst != null) {
                        inst.setInstruction_status("1");
                        instructionService.update(inst);
                    }
                } else if ("FINISHED".equals(status)) {
                    if (inst != null&&!"3".equals(inst.getInstruction_status())){
                        String startPoint=inst.getStart_point_code();
                        Device start_device = deviceAppService.findDeviceByCode(startPoint);
                        if (start_device.getDeviceDriver() instanceof SiteDeviceDriver) {
                            SiteDeviceDriver siteDeviceDriver=(SiteDeviceDriver)start_device.getDeviceDriver();
                            if(siteDeviceDriver.getMode()!=10) {
                                try {
                                    siteDeviceDriver.writing(10);
                                    siteDeviceDriver.writing(10);
                                    siteDeviceDriver.writing(10);
                                    siteDeviceDriver.writing(10);
                                    siteDeviceDriver.writing(10);
                                }catch(Exception e){
                                    log.error("写入信号失败：{}{}",e,e.getMessage());
                                }
                            }
                        }
                        inst.setInstruction_status("2");
                        instructionService.finish(inst);
                    }
                } else if ("WITHDRAWN".equals(status) || "FAILED".equals(status)) {
                    if (inst != null) {
                        inst.setInstruction_status("3");
                        instructionService.update(inst);
                        instructionService.removeByCodeFromCache(inst_jo.getString("task_code"));
                    }
                }
                JSONArray ja = inst_jo.getJSONArray("destinations");
                for (int j = 0; j < ja.size(); j++) {
                    JSONObject jo = ja.getJSONObject(j);
                    JSONArray pro_rows = jo.getJSONArray("properties");
                    //Load 取货动作 Unload放货动作 Wait等待
                    String operation = jo.getString("operation");
                    String device = jo.getString("locationName");
                    for (int k = 0; k < pro_rows.size(); k++) {
                        JSONObject item = pro_rows.getJSONObject(k);
                        if ("true".equals(item.get("value"))) {
                            String param = item.get("key").toString();
                            //EntryRequired是否进入前等待  PauseOnStation是否离开等待 Wait在该点进行等待
                            agvService.process(inst_code, param, device, operation, vehicle);
                        }
                    }
                }
            }
        } catch (Exception e){

        }

    }
}
