package com.cf.imes.module.executor.util.fileConversion.admin.api.webcad;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cf.imes.module.system.api.application.ApplicationApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.Future;

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.module.executor.enums.ErrorCodeConstants.*;
import static com.cf.imes.module.executor.enums.ErrorCodeConstants.ORDER_NOT_FOUND;


/**
 * api数据获取
 */
@Slf4j
@Component
public class ApiDataAchieve {

    @Resource
    private ApiDataProduction apiDataProduction;

    @Resource
    private ApplicationApi applicationApi;

    private static final int PARTS_PAGE_MAX = 100;

    // 重复使用的常量
    private static final String ORDER_NO_KEY = "order_no";
    private static final String CURR_PAGE_KEY = "curr_page";
    private static final String PAGE_COUNT_KEY  = "page_count"; //请求
    private static final String ERR_CODE_KEY = "err_code";
    private static final String ERR_MSG_KEY = "err_msg";
    private static final String ALL_PAGE_COUNT_KEY = "PageCount"; // 页数
    private static final String VALUE_KEY = "value";
    private static final String GOODS_ID = "goods_id";


    //    获得token数据
    public Future<JSONObject> getApiToken(Long organId) {
        JSONObject app = applicationApi.getApplicationByOrganId(organId);
        String appId = app.getString("appId");
        String appSecret = app.getString("appSecret");

        SSLUtils.ignoreSsl();
        JSONObject json = apiDataProduction.getApiTokenMessage(appId, appSecret);
        if (!json.getString(ERR_MSG_KEY).equals("success")) {
            log.error(APP_TOKEN_ERROR.getMsg());
            throw exception(API_MES_ERR, "身份认证-" + json.getString(ERR_MSG_KEY));
//            throw exception(APP_TOKEN_ERROR);
        }
        return new AsyncResult<>(json);
    }

    //    获取板件生产数据信息
    public JSONObject getApiPlateProData(String token, String orderNo) {
        SSLUtils.ignoreSsl();
        JSONObject jsonPlatesData = new JSONObject();
        jsonPlatesData.put(ORDER_NO_KEY, "N" + orderNo);//生产单号需要传入赋值
        jsonPlatesData.put("format", "json");
        jsonPlatesData.put("version", "3");
        JSONObject dataPlates = apiDataProduction.getApiOrderMessage(token, jsonPlatesData);
        return dataPlates;
    }

    //    获取配件信息 分页获取
    public JSONObject getApiPartsMessage(String token, String orderNo, JSONObject jsonParts) {

        SSLUtils.ignoreSsl();
        JSONObject parts = apiDataProduction.getApiOrderPartsMessage(token, jsonParts);
        if (!parts.getString(ERR_CODE_KEY).equals("0")) {
            log.error("N" + orderNo + "配件数据获取错误:" + parts.getString(ERR_MSG_KEY));
            throw exception(API_MES_ERR, "配件信息获取-" + parts.getString(ERR_MSG_KEY));
//            throw exception(PARTS_DATA_ERROR);
        }
        if (parts.getJSONObject(VALUE_KEY).getJSONArray("List") == null || parts.getJSONObject(VALUE_KEY).getJSONArray("List").isEmpty()) {
            return null;
        }
        return parts;
    }

    //    柜体信息转换
    public JSONObject getApiBodyMessage(String token, String orderNo) {

        SSLUtils.ignoreSsl();
        JSONObject jsonBody = new JSONObject();
        jsonBody.put(CURR_PAGE_KEY, 1);
        jsonBody.put(PAGE_COUNT_KEY, PARTS_PAGE_MAX);
        jsonBody.put(ORDER_NO_KEY, "N" + orderNo);
        JSONObject body = apiDataProduction.getApiOrderBodyMessage(token, jsonBody);
        if (!body.getString(ERR_CODE_KEY).equals("0")) {
            log.error("N" + orderNo + "柜体数据获取错误:" + body.getString(ERR_MSG_KEY));
            throw exception(API_MES_ERR, "柜体信息获取-" + body.getString(ERR_MSG_KEY));
//            throw exception(BODY_DATA_ERROR);
        }
        JSONObject dataBody = new JSONObject();
        for (int i = 1; i <= body.getJSONObject(VALUE_KEY).getInteger(ALL_PAGE_COUNT_KEY); i++) {
            jsonBody.put(CURR_PAGE_KEY, i);
            JSONObject value = apiDataProduction.getApiOrderBodyMessage(token, jsonBody);
            dataBody = mergeJSONObjects(dataBody, value);
        }
        return dataBody;
    }

    //    商品信息转换
    public JSONObject getApiGoodsMessage(String token, String orderNo) {


        SSLUtils.ignoreSsl();
        JSONObject jsonGoods = new JSONObject();
        jsonGoods.put(CURR_PAGE_KEY, 1);
        jsonGoods.put(PAGE_COUNT_KEY, PARTS_PAGE_MAX);
        jsonGoods.put(ORDER_NO_KEY, "N" + orderNo);
        JSONObject goods = apiDataProduction.getApiOrderGoodsMessage(token, jsonGoods);
        if (!goods.getString(ERR_CODE_KEY).equals("0")) {
            log.error("N" + orderNo + "商品信息转换失败:" + goods.getString(ERR_MSG_KEY));
            throw exception(API_MES_ERR, "商品信息获取-" + goods.getString(ERR_MSG_KEY));
//            throw exception(GOODS_DATA_ERROR);
        }
        JSONObject dataGoods = new JSONObject();
        for (int i = 1; i <= goods.getJSONObject(VALUE_KEY).getInteger(ALL_PAGE_COUNT_KEY); i++) {
            jsonGoods.put(CURR_PAGE_KEY, i);
            JSONObject value = apiDataProduction.getApiOrderGoodsMessage(token, jsonGoods);
            dataGoods = mergeJSONObjects(dataGoods, value);
        }

        return dataGoods;
    }

    //    板材明细信息转换
    public JSONObject getApiPlateDetailMessage(String token, String orderNo, JSONObject jsonPlates) {

        SSLUtils.ignoreSsl();
        JSONObject plates = apiDataProduction.getApiBlocksDataMessage(token, jsonPlates);
        if (!plates.getString(ERR_CODE_KEY).equals("0")) {
            log.error("N" + orderNo + "板材明细信息获取错误" + plates.getString(ERR_MSG_KEY));
            throw exception(API_MES_ERR, "板材明细信息获取-" + plates.getString(ERR_MSG_KEY));
//            throw exception(PLATE_DATA_ERROR);
        }
        if (plates.getJSONObject(VALUE_KEY).getJSONArray("List") == null || plates.getJSONObject(VALUE_KEY).getJSONArray("List").isEmpty()) {
            return null;
        }
        return plates;
    }

    //    加工组信息转换
    public JSONObject getApiGroupMessage(String token, String orderNo) {

        SSLUtils.ignoreSsl();
        JSONObject jsonModule = new JSONObject();
        jsonModule.put(ORDER_NO_KEY, "N" + orderNo);
        return apiDataProduction.getApiModuleTypeDataMessage(token, jsonModule);
    }

    //    板材数据信息转换
    public JSONObject getApiBlocksMessage(String token, String orderNo) {

        SSLUtils.ignoreSsl();
        JSONObject jsonBlocks = new JSONObject();
        jsonBlocks.put(CURR_PAGE_KEY, 1);
        jsonBlocks.put(PAGE_COUNT_KEY, PARTS_PAGE_MAX);
        jsonBlocks.put(ORDER_NO_KEY, "N" + orderNo);
        JSONObject blocks = apiDataProduction.getApiBlocksMessage(token, jsonBlocks);
        if (!blocks.getString(ERR_CODE_KEY).equals("0")) {
            log.error("N" + orderNo + "板材数据获取错误" + blocks.getString(ERR_MSG_KEY));
            throw exception(API_MES_ERR, "板材数据信息获取-" + blocks.getString(ERR_MSG_KEY));
        }
        JSONObject block = new JSONObject();
        for (int i = 1; i <= blocks.getJSONObject(VALUE_KEY).getInteger(ALL_PAGE_COUNT_KEY); i++) {
            jsonBlocks.put(CURR_PAGE_KEY, i);
            JSONObject value = apiDataProduction.getApiBlocksMessage(token, jsonBlocks);
            block = mergeJSONObjects(block, value);
        }
        return block;
    }

    //    商品列表信息转换
    @Async
    public Future<JSONObject> getApiGoodsMessage(String token, Long[] id) {

        SSLUtils.ignoreSsl();
        JSONObject jsonGoods = new JSONObject();
        jsonGoods.put(GOODS_ID, id);
        JSONObject good = apiDataProduction.getApiGoods(token, jsonGoods);
        if (!good.getString(ERR_CODE_KEY).equals("0")) {
            log.error(id + "配件数据获取错误" + good.getString(ERR_MSG_KEY));
            throw exception(API_MES_ERR, "配件数据信息获取-" + good.getString(ERR_MSG_KEY));

        }
        return new AsyncResult<>(good);
    }

    //    订单获取
    public JSONObject getApiOrder(String token, String orderNo) {

        SSLUtils.ignoreSsl();
        JSONObject jsonOrders = new JSONObject();
        orderNo = "N" +orderNo;
        JSONArray orderList = new JSONArray();
        orderList.add(orderNo.replace(" ", ""));
        jsonOrders.put(ORDER_NO_KEY, orderList);
        JSONObject order = apiDataProduction.getApiOrderList(token, jsonOrders);

        if (!order.getString(ProduceApiConstants.CODE).equals("0") ||
                order.getJSONArray(ProduceApiConstants.DATA) == null ||
                order.getJSONArray(ProduceApiConstants.DATA).isEmpty()) {
            throw exception(ORDER_NOT_FOUND);
        }

        return order;
    }

    //    日期格式转换
    private void getDate(String createDateMin, String createDateMax, JSONObject jsonOrders) {
        try {
            // 定义日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            // 将字符串转换为LocalDate对象
            LocalDate startTime = LocalDate.parse(createDateMin, formatter);
            LocalDate endTime = LocalDate.parse(createDateMax, formatter);
            long daysBetweenSimple = ChronoUnit.DAYS.between(startTime, endTime);
            if (daysBetweenSimple > 30) {
                throw exception(ORDER_DATE_ERR);
            }

            jsonOrders.put("create_date_min", createDateMin + " 00:00:00");
            jsonOrders.put("create_date_max", createDateMax + " 23:59:59");
        } catch (Exception e) {
            throw exception(ORDER_TIME_ERR);
        }
    }
    //    订单列表
    public Future<JSONObject> getApiOrderList(String token,String shopId,String createDateMin, String createDateMax, String orderNo, String customOrderNo) {

        SSLUtils.ignoreSsl();
        JSONObject jsonOrders = new JSONObject();
        if (createDateMin != null && createDateMax != null){
            getDate(createDateMin, createDateMax, jsonOrders);
        }

        jsonOrders.put(CURR_PAGE_KEY, 1);
        jsonOrders.put(PAGE_COUNT_KEY, PARTS_PAGE_MAX);

        if (orderNo != null) {
            jsonOrders.put(ORDER_NO_KEY, shopId + "@N" +orderNo);
        }
        if (customOrderNo != null){
            jsonOrders.put("custom_order_no", customOrderNo);
        }

        JSONObject orders = apiDataProduction.getApiOrderList(token, jsonOrders);
        if (!orders.getString(ERR_CODE_KEY).equals("0")) {
            throw exception(ORDER_READ_ERR);
        }
        JSONObject order = new JSONObject();
        int countPage = divideWithPlusOne(orders.getInteger("count"), PARTS_PAGE_MAX);
        for (int i = 1; i <= countPage; i++) {
            jsonOrders.put(CURR_PAGE_KEY, i);
            JSONObject value = apiDataProduction.getApiOrderList(token, jsonOrders);
            order = mergeData(order, value);
        }
        return new AsyncResult<>(order);
    }

    public JSONObject mergeJSONObjects(JSONObject object1, JSONObject object2) {

        // 创建新对象
        JSONObject mergedObj = new JSONObject();
        // 合并 List 属性
        JSONArray mergedList = new JSONArray();
        JSONArray list1 = null;
        if (object1.getJSONObject(VALUE_KEY) != null) {
            list1 = object1.getJSONObject(VALUE_KEY).getJSONArray("List");
            if (list1 != null) {
                for (int i = 0; i < list1.size(); i++) {
                    mergedList.add(list1.getJSONObject(i));
                }
            }
        }
        if (object1.getJSONArray("List") != null) {
            list1 = object1.getJSONArray("List");
            if (list1 != null) {
                for (int i = 0; i < list1.size(); i++) {
                    mergedList.add(list1.getJSONObject(i));
                }
            }
        }
        JSONArray list2 = object2.getJSONObject(VALUE_KEY).getJSONArray("List");
        if (list2 != null) {
            for (int i = 0; i < list2.size(); i++) {
                mergedList.add(list2.getJSONObject(i));
            }
        }

        mergedObj.put("List", mergedList);
        return mergedObj;


    }

    public int divideWithPlusOne(int dividend, int divisor) {
        // 首先检查除数是否为0，避免除以0的异常
        if (divisor == 0) {
            throw new IllegalArgumentException("除数不能为0");
        }

        // 计算商和余数
        int quotient = dividend / divisor; // 商
        int remainder = dividend % divisor; // 余数

        // 如果余数不为0，则商加一
        if (remainder != 0) {
            quotient++;
        }

        return quotient;
    }

    public JSONObject mergeData(JSONObject object1, JSONObject object2) {

        // 创建新对象
        JSONObject mergedObj = new JSONObject();
        // 合并 List 属性
        JSONArray mergedList = new JSONArray();
        JSONArray list1 = null;
        if (object1.getJSONArray("data") != null) {
            list1 = object1.getJSONArray("data");
            if (list1 != null) {
                for (int i = 0; i < list1.size(); i++) {
                    mergedList.add(list1.getJSONObject(i));
                }
            }
        }
        JSONArray list2 = object2.getJSONArray("data");
        if (list2 != null) {
            for (int i = 0; i < list2.size(); i++) {
                mergedList.add(list2.getJSONObject(i));
            }
        }

        mergedObj.put("data", mergedList);
        return mergedObj;


    }
}
