package org.jeecg.modules.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kong.unirest.HttpResponse;
import kong.unirest.RequestBodyEntity;
import kong.unirest.Unirest;
import kong.unirest.UnirestException;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.RestUtil;
import org.jeecg.modules.api.model.CabinetModel;
import org.jeecg.modules.api.model.CabinetStocks;
import org.jeecg.modules.api.model.ResponseMessage;
import org.jeecg.modules.api.model.SingleTool;
import org.jeecg.modules.cabinet.entity.Cabinet;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.List;

@Service
public class CabinetApiService {

    @Value("${cabinet.tip}")
    private String cabinetTIp;
    @Value("${cabinet.mip}")
    private String cabinetMIp;
//    @Value("${cabinet.mipPort}")
    private int mipPort = 5258 ;
    @Value("${cabinet.manufacturer}")
    private String cabinetManufacturer;
    //    @Value("${cabinet.port}")
    //    private static Integer cabinetPort;
    private static final String FUNCTION_PATH = "/ServiceHandler.ashx?function=";

    /**
     * 人员信息同步接口(每次新增成员的时候，所有人的数据都需要一次性下发)
     * @param cabinetModels
     */
    public boolean sendUsers(List<CabinetModel> cabinetModels) throws RuntimeException {
        JSONObject body = new JSONObject();
        body.put("users", JSONArray.parse(JSON.toJSONString(cabinetModels)));
        return sendRequest("receiveUsers", "users", body.toJSONString(),cabinetTIp);
    }

    /**
     * 向工具柜下发工单信息
     * @param cabinetModel
     * @return
     * @throws Exception
     */
    public boolean sendWorkOrder(CabinetModel cabinetModel, int applyType) throws RuntimeException {
        JSONObject body = JSON.parseObject(JSON.toJSONString(cabinetModel));
        // ip默认为工具柜ip
        String cabinetIp = cabinetTIp;
        // 如果是物料操作且存在物料柜ip则将IP指定为物料柜ip，如果是物料柜操作但物料柜IP配置项为空或不存在则直接返回true
        if (applyType == 0 && StringUtils.isNotBlank(cabinetMIp)) {
            cabinetIp = cabinetMIp;
        }else if (applyType == 0 && StringUtils.isBlank(cabinetMIp)) {
            return true;
        }
        if("zhonghong".equals(cabinetManufacturer)) {
            ResponseEntity<JSONObject> response = RestUtil.request("http://"+cabinetIp+"/api/cabinet/receiveOrderInfo", HttpMethod.POST, null, body);
            validateResponse(response, "sendWorkOrder");
            return true;
        }else {
            return sendRequest("receiveOrderInfo", "orderInfo", body.toJSONString(), cabinetIp);
        }
    }

    /**
     * 撤销工单信息向工具柜下发
     * @param cabinetModel
     * @return
     * @throws RuntimeException
     */
    public boolean sendCancelWorkOrder(CabinetModel cabinetModel) throws RuntimeException {
        JSONObject body = JSON.parseObject(JSON.toJSONString(cabinetModel));

        if("zhonghong".equals(cabinetManufacturer)) {
            ResponseEntity<JSONObject> response0 = RestUtil.request("http://"+cabinetTIp+"/api/cabinet/cancelOrder", HttpMethod.POST, null, body);
            validateResponse(response0, "cancelOrder");
            ResponseEntity<JSONObject> response1 = RestUtil.request("http://"+cabinetMIp+"/api/cabinet/cancelOrder", HttpMethod.POST, null, body);
            validateResponse(response1, "cancelOrder");
            return true;
        }else {
//            body.put("cancel", JSONArray.parse(JSON.toJSONString(cabinetModel)));
            return sendRequest("receiveCancelOrder", "orderId", cabinetModel.getOrderId(),cabinetTIp);
        }
    }

    /**
     * 向工具柜同步工具信息
     * @param dto
     * @return
     * @throws Exception
     */
    public boolean sendToolInfo(List<CabinetStocks> dto) throws RuntimeException {
        JSONObject body = new JSONObject();
        body.put("tools", JSONArray.parse(JSON.toJSONString(dto)));
        return sendRequest("receiveToolInfo", "tools", body.toJSONString(),cabinetTIp);
    }

    // 处理HTTP请求
    private boolean sendRequest(String function, String paramName, String data,String cabinetIp) throws RuntimeException {
        try {
            // 构建MultiValueMap
            MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
            formData.add(paramName, data);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 构建请求URL
            String url = String.format("http://%s%s%s", cabinetIp, FUNCTION_PATH, function);

            // 发送请求
            ResponseEntity<JSONObject> response = RestUtil.request1(url, HttpMethod.POST, headers, null, formData, JSONObject.class);

            // 处理响应
            validateResponse(response, function);

            return true;
        } catch (Exception e) {
            String errorMsg = String.format("%s失败: %s", function, e.getMessage());
            throw new RuntimeException(errorMsg, e);
        }
    }

    // 响应验证逻辑
    private void validateResponse(ResponseEntity<JSONObject> response, String operation) throws RuntimeException {
        if (response.getBody() == null) {
            throw new RuntimeException(operation + "失败，未获取到响应！");
        }
        if (!"200".equals(response.getBody().getString("code"))) {
            throw new RuntimeException(response.getBody().getString("message"));
        }
    }

    /**
     * 向工具柜下发信息
     * @param cabinetModels
     * @return
     * @throws Exception
     */
    public boolean sendMessages(Cabinet cabinet,List<CabinetModel> cabinetModels, String function) throws RuntimeException {
        try {
            String json = JSON.toJSONString(cabinetModels);
            String cabinetIp = cabinet.getIpAddress() + ":" + cabinet.getPort();

            HttpResponse<String> response = Unirest.post("http://" + cabinetIp + "/cabinet/" + function)
                    .header("Content-Type", "application/json")
                    .body(json)
                    .asString();

            if (response.getStatus() == 200) {
                return true;
            } else {
                // Log error or handle unsuccessful response
                System.err.println("Request failed with status: " + response.getStatus());
                return false;
            }
        } catch (UnirestException e) {
            // Log the exception
            e.printStackTrace();
            return false;
        }
    }

    public boolean sendToolMessages(Cabinet cabinet,List<SingleTool> cabinetModels) throws RuntimeException {
        try {
            String json = JSON.toJSONString(cabinetModels);
            String cabinetIp = cabinet.getIpAddress() + ":" + cabinet.getPort();

            HttpResponse<String> response = Unirest.post("http://" + cabinetIp + "/cabinet/receiveToolInfo")
                    .header("Content-Type", "application/json")
                    .body(json)
                    .asString();

            if (response.getStatus() == 200) {
                return true;
            } else {
                // Log error or handle unsuccessful response
                System.err.println("Request failed with status: " + response.getStatus());
                return false;
            }
        } catch (UnirestException e) {
            // Log the exception
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 向工具柜下发信息，支持不同对象的列表传入
     * @param cabinet 工具柜实体
     * @param datas 不同对象的列表
     * @param <T> 泛型类型
     * @return 下发成功返回true，失败返回false
     * @return 下发成功返回true，失败返回false
     * @throws RuntimeException 发生异常时抛出
     */
    public <T> boolean sendTMessages(Cabinet cabinet, List<T> datas, String function) throws RuntimeException {
        try {
            String json = "";
            if(datas!= null && datas.size() == 1){
                json = JSON.toJSONString(datas.get(0));
            }else{
                json = JSON.toJSONString(datas);
            }
            String cabinetIp = cabinet.getIpAddress() + ":" + cabinet.getPort();

            HttpResponse<String> response = Unirest.post("http://" + cabinetIp + "/cabinet/"+function)
                    .header("Content-Type", "application/json")
                    .body(json)
                    .asString();

            if (response.getStatus() == 200 && "200".equals(JSON.parseObject(response.getBody()).getString("code"))) {
                return true;
            } else {
                // Log error or handle unsuccessful response
                System.err.println("Request failed with status: " + response.getStatus());
                return false;
            }
        } catch (UnirestException e) {
            // Log the exception
            e.printStackTrace();
            return false;
        }
    }
}
