package org.nl.acs.ext.wms.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nl.acs.AcsConfig;
import org.nl.acs.address.service.AddressService;
import org.nl.acs.address.service.dto.AddressDto;
import org.nl.acs.device.service.DeviceService;
import org.nl.acs.ext.wms.LmsUtil;
import org.nl.acs.ext.wms.data.*;
import org.nl.acs.ext.wms.service.AcsToWmsService;
import org.nl.acs.log.service.DeviceExecuteLogService;
import org.nl.acs.task.service.TaskService;
import org.nl.acs.task.service.dto.TaskDto;
import org.nl.system.service.param.ISysParamService;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
@Lazy
public class AcsToWmsServiceImpl implements AcsToWmsService {
    @Autowired
    ISysParamService paramService;

    @Autowired
    DeviceService deviceService;

    @Autowired
    AddressService addressService;

    @Autowired
    TaskService taskService;

    @Autowired
    DeviceExecuteLogService logServer;

    /*@Value("${acsTowms.token}")*/
    public String token;


    private String log_file_type = "log_file_type";
    private String log_type = "ACS请求LMS";

    @Override
    public String applyTaskToWms(JSONObject jo) {
        try {
            MDC.put(log_file_type, log_type);
            log.info("applyTaskToWms-----输入参数{}", jo);
            String wmsurl = paramService.findByCode(AcsConfig.WMSURL).getValue();
            AddressDto addressDto = addressService.findByCode("applyTaskToWms");
            String url = wmsurl + addressDto.getMethods_url();
            HttpResponse result2 = null;
            try {
                result2 = HttpRequest.post(url)
                        .header("Authorization", token)
                        .body(String.valueOf(jo))
                        .execute();
//                ////System.out.println(result2);
            } catch (Exception e) {
                String msg = e.getMessage();
                log.info("applyTaskToWms-----输出参数{}", msg);
                //网络不通
//                //System.out.println(msg);
            }
            if (ObjectUtil.isEmpty(result2)) {
                log.info("applyTaskToWms-----输出参数{}", "返回结果为空");
                return null;
            }
            String type = "";
            if (result2.getStatus() == 200) {
                type = "info";
            } else {
                type = "error";
            }
            log.info("applyTaskToWms-----输出参数{}", result2.body());
            return result2.body();

        } finally {
            MDC.remove(log_file_type);
        }

    }

    @Override
    public HttpResponse feedbackTaskStatusToWms(JSONArray data) {

        try {
            MDC.put(log_file_type, log_type);
            String wmsurl = paramService.findByCode(AcsConfig.WMSURL).getValue();

            String task_code = "";
            for (int i = 0; i < data.size(); i++) {
                JSONObject json = (JSONObject) data.get(i);
                task_code = json.getString("task_code");
            }
            TaskDto taskDto = taskService.findByCode(task_code);
            String vehicle_code = taskDto.getVehicle_code();

            HttpResponse result2 = null;
            log.info("feedbackTaskStatusToWms-----请求参数{}", data.toString());

            AddressDto addressDto = addressService.findByCode("feedbackTaskStatusToWms");
            String methods_url = addressDto.getMethods_url();
            try {
                result2 = HttpRequest.post(wmsurl + methods_url)
                        .header("Authorization", token).body(String.valueOf(data))
                        .execute();
//                //System.out.println(result2);
            } catch (Exception e) {
                String msg = e.getMessage();
                //网络不通
//                //System.out.println(msg);
                log.info("feedbackTaskStatusToWms-----输出参数{}", msg);

            }


            String type = "";
            if (result2.getStatus() == 200) {
                type = "info";
            } else {
                type = "error";
            }

            JSONObject jo = JSONObject.parseObject(result2.body());
            log.info("feedbackTaskStatusToWms-----输出参数{}", jo.toString());
            return result2;
        } finally {
            MDC.remove(log_file_type);
        }

    }


    @Override
    public String requestTaskAgain(String address, String task_id, String vehicle_code) {
        String wmsurl = paramService.findByCode(AcsConfig.WMSURL).getValue();
        JSONObject jo = new JSONObject();
        jo.put("task_id", task_id);
        String result2 = null;

        AddressDto addressDto = addressService.findByCode("requestTaskAgain");
        String methods_url = addressDto.getMethods_url();
        String url = wmsurl + methods_url;
        log.info("requestTaskAgain----请求参数{}", jo);

        try {
            result2 = HttpRequest.post(url)
                    .body(String.valueOf(jo))
                    .execute().body();
            //System.out.println(result2);
            log.info("requestTaskAgain----返回参数{}", result2);
        } catch (Exception e) {
            String msg = e.getMessage();
            //网络不通
            //System.out.println(msg);

        }
        return result2;
    }

    @Override
    public HttpResponse feedbackAgvStatus(String device_code, String error, String error_message) {
        String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();

        JSONObject json = new JSONObject();
        json.put("device_code", device_code);
        json.put("error", error);
        json.put("error_message", error_message);

        AddressDto addressDto = addressService.findByCode("feedbackAgvStatus");
        String methods_url = addressDto.getMethods_url();
        String url = wmsUrl + methods_url;
        HttpResponse result = null;
        log.info("feedbackAgvStatus----请求参数{}", json);

        try {
            result = HttpRequest.post(url)
                    .body(String.valueOf(json))
                    .execute();
            System.out.println(result);
            log.info("feedbackAgvStatus----返回参数{}", result);
        } catch (Exception e) {
            String msg = e.getMessage();
            //网络不通
            //System.out.println(msg);
        }
        return result;
    }

    @Override
    public HttpResponse feedbackDeviceStatus(String device_code, String state) {
        String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();

        JSONObject json = new JSONObject();
        json.put("device_code", device_code);
        json.put("back_time", DateUtil.format(DateUtil.date(), "yyyyMMddHHmmssSSS"));
        json.put("is_have", state);
        AddressDto addressDto = addressService.findByCode("feedbackDeviceStatus");
        String methods_url = addressDto.getMethods_url();
        String url = wmsUrl + methods_url;
        HttpResponse result = null;
        log.info("feedbackDeviceStatus----请求参数{}", json);

        try {
            result = HttpRequest.post(url)
                    .body(String.valueOf(json))
                    .execute();
            System.out.println(result);
            log.info("feedbackDeviceStatus----返回参数{}", result);
        } catch (Exception e) {
            String msg = e.getMessage();
            //网络不通
            //System.out.println(msg);
        }
        return result;
    }

    @Override
    public HttpResponse feedbackAgv(JSONArray from) {
        String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();

        AddressDto addressDto = addressService.findByCode("feedbackAgv");
        String methods_url = addressDto.getMethods_url();
        String url = wmsUrl + methods_url;
        HttpResponse result = null;
        log.info("feedbackAgv----请求参数{}", from);

        try {
            result = HttpRequest.post(url)
                    .body(String.valueOf(from))
                    .execute();
            System.out.println(result);
            log.info("feedbackAgv----返回参数{}", result);
        } catch (Exception e) {
            String msg = e.getMessage();
            //网络不通
            //System.out.println(msg);
        }
        return result;
    }

    @Override
    public HttpResponse applyOpenOrCloseDoor(String device_code, String status) {
        String wmsurl = paramService.findByCode(AcsConfig.WMSURL).getValue();
        JSONObject jo = new JSONObject();
        jo.put("device_code", device_code);
        jo.put("status", status);
        HttpResponse result = null;
        log.info("applyOpenOrCloseDoor-----请求参数{}", jo.toString());

        AddressDto addressDto = addressService.findByCode("applyOpenOrCloseDoor");
        String methods_url = addressDto.getMethods_url();
        try {
            result = HttpRequest.post(wmsurl + methods_url)
                    .body(String.valueOf(jo))
                    .execute();
            System.out.println(result);
            log.info("applyOpenOrCloseDoor-----返回参数{}", result);
        } catch (Exception e) {
            String msg = e.getMessage();
            //网络不通
            //System.out.println(msg);
        }
        return result;
    }

    @Override
    public HttpResponse queryDoorsStatus() {
        String wmsurl = paramService.findByCode(AcsConfig.WMSURL).getValue();

        HttpResponse result = null;
        log.info("queryDoorStatus-----请求");
        AddressDto addressDto = addressService.findByCode("queryDoorsStatus");
        String methods_url = addressDto.getMethods_url();
        try {
            result = HttpRequest.get(wmsurl + methods_url)
                    .body("")
                    .execute();
            log.info("queryDoorStatus-----输出参数{}", result.body().toString());
        } catch (Exception e) {
            String msg = e.getMessage();
            //网络不通
            //System.out.println(msg);

        }
        return result;
    }

    @Override
    public HttpResponse feedbackOrderStatus(JSONObject param) {
        if (StrUtil.equals(paramService.findByCode(AcsConfig.HASWMS).getValue(), "1")) {
            String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();
            String ext_order_id = param.getString("ext_order_id");
            String status = param.getString("status");
            String type1 = param.getString("type");
            JSONObject json = new JSONObject();
            json.put("ext_order_id", ext_order_id);
            json.put("status", status);
            json.put("type", type1);
            AddressDto addressDto = addressService.findByCode("feedbackOrderStatus");
            String methods_url = addressDto.getMethods_url();
            String url = wmsUrl + methods_url;
            HttpResponse result = null;
            log.info("feedbackOrderStatus----请求参数{}", json);
            try {
                result = HttpRequest.post(url)
                        .body(String.valueOf(json))
                        .execute();
                String type = "";
                if (result.getStatus() == 200) {
                    type = "info";
                } else {
                    type = "error";
                }

                log.info("feedbackOrderStatus----返回参数{}", result);
            } catch (Exception e) {
                String msg = e.getMessage();
                //网络不通
                //System.out.println(msg);
            }
            return result;

        }
        return null;
    }

    @Override
    public HttpResponse applyInCacheLineTask(JSONObject param) {
        if (StrUtil.equals(paramService.findByCode(AcsConfig.HASWMS).getValue(), "1")) {
            String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();
            // TODO 还没向地址表中添加 applyInCacheLineTask地址
            AddressDto addressDto = addressService.findByCode("applyInCacheLineTask");
            String methods_url = addressDto.getMethods_url();
            String url = wmsUrl + methods_url;
            HttpResponse result = null;
            log.info("feedbackOrderStatus----请求参数{}", param);
            try {
                result = HttpRequest.post(url)
                        .body(String.valueOf(param))
                        .execute();
                String type = "";
                if (result.getStatus() == 200) {
                    type = "info";
                } else {
                    type = "error";
                }

                log.info("applyInCacheLineTask----返回参数{}", result);
            } catch (Exception e) {
                String msg = e.getMessage();
                //网络不通
                //System.out.println(msg);
            }
            return result;
        }
        return null;
    }

    @Override
    public HttpResponse applyOutCacheLineTask(JSONObject param) {
        if (StrUtil.equals(paramService.findByCode(AcsConfig.HASWMS).getValue(), "1")) {
            String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();
            // TODO 还没向地址表中添加 applyOutCacheLineTask
            AddressDto addressDto = addressService.findByCode("applyOutCacheLineTask");
            String methods_url = addressDto.getMethods_url();
            String url = wmsUrl + methods_url;
            HttpResponse result = null;
            log.info("feedbackOrderStatus----请求参数{}", param);
            try {
                result = HttpRequest.post(url)
                        .body(String.valueOf(param))
                        .execute();
                String type = "";
                if (result.getStatus() == 200) {
                    type = "info";
                } else {
                    type = "error";
                }

                log.info("applyOutCacheLineTask----返回参数{}", result);
            } catch (Exception e) {
                String msg = e.getMessage();
                //网络不通
                //System.out.println(msg);
            }
            return result;
        }
        return null;
    }

    @Override
    public ApplyLabelingAndBindingResponse applyLabelingAndBindingRequest(ApplyLabelingAndBindingRequest param) {
        try {
            MDC.put(log_file_type, log_type);
            ApplyLabelingAndBindingResponse applyLabelingAndBindingResponse = new ApplyLabelingAndBindingResponse();
            if (StrUtil.equals(paramService.findByCode(AcsConfig.HASWMS).getValue(), "1")) {
                String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();
                AddressDto addressDto = addressService.findByCode("applyLabelingAndBinding");
                String methods_url = addressDto.getMethods_url();
                String url = wmsUrl + methods_url;
                log.info("ApplyLabelingAndBindingRequest----请求参数{}", param);
                try {
                    //                    String result = "";
                    String result = HttpRequest.post(url)
                            .body(JSON.toJSONString(param))
                            .execute().body();
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    log.info("ApplyLabelingAndBindingResponse----返回参数{}", result);
                    applyLabelingAndBindingResponse = JSONObject.toJavaObject(jsonObject, ApplyLabelingAndBindingResponse.class);
                } catch (Exception e) {
                    JSONObject map = new JSONObject();
                    map.put("status", 400);
                    map.put("message", e.getMessage());
                    return JSONObject.toJavaObject(map, ApplyLabelingAndBindingResponse.class);
                }
            }
            return applyLabelingAndBindingResponse;
        } finally {
            MDC.remove(log_file_type);
        }


    }

    @Override
    public LiKuApplyTakResponse liKuApplyTaskRequest(LiKuApplyTaskRequest param) {
        try {
            MDC.put(log_file_type, log_type);
            LiKuApplyTakResponse liKuApplyTakResponse = new LiKuApplyTakResponse();
            if (StrUtil.equals(paramService.findByCode(AcsConfig.HASWMS).getValue(), "1")) {
                String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();
                AddressDto addressDto = addressService.findByCode("liKuApplyTask");
                String methods_url = addressDto.getMethods_url();
                String url = wmsUrl + methods_url;
                log.info("LiKuApplyTaskRequest----请求参数{}", param);
                try {
                    String result = HttpRequest.post(url)
                            .body(JSON.toJSONString(param))
                            .execute().body();
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    log.info("LiKuApplyTakResponse----返回参数{}", result);
                    liKuApplyTakResponse = JSONObject.toJavaObject(jsonObject, LiKuApplyTakResponse.class);
                } catch (Exception e) {
                    JSONObject map = new JSONObject();
                    map.put("status", 400);
                    map.put("message", e.getMessage());
                    return JSONObject.toJavaObject(map, LiKuApplyTakResponse.class);
                }
            }
            return liKuApplyTakResponse;
        } finally {
            MDC.remove(log_file_type);
        }

    }


    @Override
    public UpdateLKTaskResponse updateLKTaskRequest(UpdateLKTaskRequest param) {
        try {
            MDC.put(log_file_type, log_type);
            log.info("updateLKTaskRequest-----输入参数{}", param);
            UpdateLKTaskResponse updateLKTaskResponse = new UpdateLKTaskResponse();
            if (StrUtil.equals(paramService.findByCode(AcsConfig.HASWMS).getValue(), "1")) {
                String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();
                AddressDto addressDto = addressService.findByCode("liKuApplyTask");
                String methods_url = addressDto.getMethods_url();
                String url = wmsUrl + methods_url;
                try {
                    String result = HttpRequest.post(url)
                            .body(JSON.toJSONString(param))
                            .execute().body();
                    log.info("UpdateLKTaskResponse----返回参数{}", result);

                    JSONObject jsonObject = JSONObject.parseObject(result);
                    updateLKTaskResponse = JSONObject.toJavaObject(jsonObject, UpdateLKTaskResponse.class);
                } catch (Exception e) {
                    JSONObject map = new JSONObject();
                    map.put("status", 400);
                    map.put("message", e.getMessage());
                    return JSONObject.toJavaObject(map, UpdateLKTaskResponse.class);
                }
            }

            return updateLKTaskResponse;
        } finally {
            MDC.remove(log_file_type);
        }

    }

    @Override
    public HttpResponse shipDeviceUpdate(JSONObject param) {
        try {
            MDC.put(log_file_type, log_type);
            //            log.info("shipDeviceUpdate-----输入参数{}", param);
            if (StrUtil.equals(paramService.findByCode(AcsConfig.HASWMS).getValue(), "1")) {
                String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();
                AddressDto addressDto = addressService.findByCode("shipDeviceUpdate");
                String methods_url = addressDto.getMethods_url();
                String url = wmsUrl + methods_url;
                return HttpRequest
                        .post(url)
                        .body(param.toString())
                        .execute();
            }
        } catch (Throwable ignored) {

        } finally {
            MDC.remove(log_file_type);
        }
        return null;
    }


    @Override
    public HttpResponse shipAgvUpdate(JSONArray param) {
        try {
            MDC.put(log_file_type, log_type);
            //            log.info("shipDeviceUpdate-----输入参数{}", param);
            if (StrUtil.equals(paramService.findByCode(AcsConfig.HASWMS).getValue(), "1")) {
                String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();
                AddressDto addressDto = addressService.findByCode("shipDeviceUpdate");
                String methods_url = addressDto.getMethods_url();
                String url = wmsUrl + methods_url;
                return HttpRequest
                        .post(url)
                        .body(param.toString())
                        .execute();
            }
        } catch (Throwable ignored) {

        } finally {
            MDC.remove(log_file_type);
        }
        return null;
    }


    @Override
    public HttpResponse feedAgvTaskStatus(JSONArray from) {
        String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();

        AddressDto addressDto = addressService.findByCode("feedAgvTaskStatus");
        String methods_url = addressDto.getMethods_url();
        String url = wmsUrl + methods_url;
        HttpResponse result = null;
        log.info("feedAgvTaskStatus----请求参数{}", from);

        try {
            result = HttpRequest.post(url)
                    .body(String.valueOf(from))
                    .execute();
            System.out.println(result);
            log.info("feedAgvTaskStatus----返回参数{}", result);
        } catch (Exception e) {
            String msg = e.getMessage();
            //网络不通
            //System.out.println(msg);
        }
        return result;
    }

    @Override
    public JSONObject feedAgvTaskAction(JSONArray from) {
        String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();
        AddressDto addressDto = addressService.findByCode("feedAgvTaskStatus");
        String methods_url = addressDto.getMethods_url();
        String url = wmsUrl + methods_url;
        JSONObject result = new JSONObject();
        log.info("feedAgvTaskAction----请求参数{}", from);
        try {
            String msg = HttpRequest.post(url)
                    .body(String.valueOf(from))
                    .execute().body();
            result.put("code", "200");
            result.put("msg", msg);
            log.info("feedAgvTaskAction----调用成功，返回参数{}", result);
        } catch (Exception e) {
            result.put("msg", e.getMessage());
            result.put("code", "500");
            log.info("feedAgvTaskAction----调用失败，返回参数{}", e.getMessage());
        }
        return result;
    }


    @Override
    public HttpResponse feedAgvErrorStatus(JSONArray from) {
        String wmsUrl = paramService.findByCode(AcsConfig.WMSURL).getValue();

        AddressDto addressDto = addressService.findByCode("feedAgvErrorStatus");
        String methods_url = addressDto.getMethods_url();
        String url = wmsUrl + methods_url;
        HttpResponse result = null;
        log.info("feedAgvErrorStatus----请求参数{}", from);

        try {
            result = HttpRequest.post(url)
                    .body(String.valueOf(from))
                    .execute();
            System.out.println(result);
            log.info("feedAgvErrorStatus----返回参数{}", result);
        } catch (Exception e) {
            String msg = e.getMessage();
            //网络不通
            //System.out.println(msg);
        }
        return result;
    }

    @Override
    public String applyTask(BaseRequest requestParam) {
        try {
            MDC.put(log_file_type, log_type);
            String api = addressService.findByCode("applyTaskToWms").getMethods_url();
            log.info("applyTaskToWms-----输入参数{}", JSON.toJSONString(requestParam, SerializerFeature.DisableCircularReferenceDetect));
            String result = LmsUtil.notifyAcs(api, requestParam);
            log.info("applyTaskToWms-----输出参数{}", result);
            return result;
        } finally {
            MDC.remove(log_file_type);
        }
    }

    @Override
    public String feedTaskStatus(BaseRequest requestParam) {
        try {
            MDC.put(log_file_type, log_type);
            String api = addressService.findByCode("feedTaskStatus").getMethods_url();
            log.info("feedTaskStatus-----输入参数{}", JSON.toJSONString(requestParam, SerializerFeature.DisableCircularReferenceDetect));
            String result = LmsUtil.notifyAcs(api, requestParam);
            log.info("feedTaskStatus-----输出参数{}", result);
            return result;
        } finally {
            MDC.remove(log_file_type);
        }
    }

    @Override
    public String notify(BaseRequest requestParam) {
        try {
            MDC.put(log_file_type, log_type);
            String api = addressService.findByCode("notify").getMethods_url();
            log.info("notify-----输入参数{}", JSON.toJSONString(requestParam, SerializerFeature.DisableCircularReferenceDetect));
            String result = LmsUtil.notifyAcs(api, requestParam);
            log.info("notify-----输出参数{}", result);
            return result;
        } finally {
            MDC.remove(log_file_type);
        }
    }

    @Override
    public String feedbackState(BaseRequest requestParam) {
        try {
            MDC.put(log_file_type, log_type);
            String api = addressService.findByCode("feedbackState").getMethods_url();
            log.info("feedbackState-----输入参数{}", JSON.toJSONString(requestParam, SerializerFeature.DisableCircularReferenceDetect));
            String result = LmsUtil.notifyAcs(api, requestParam);
            log.info("feedbackState-----输出参数{}", result);
            return result;
        } finally {
            MDC.remove(log_file_type);
        }
    }
}
