package com.cf.imes.module.plan.service.orderImport;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cf.imes.framework.common.enums.OrderPackageStatusEnum;
import com.cf.imes.framework.common.exception.ErrorCode;
import com.cf.imes.framework.common.exception.ServiceException;
import com.cf.imes.framework.common.util.Assert.AssertUtils;
import com.cf.imes.framework.id.core.util.SnowflakeIdWorker3rd;
import com.cf.imes.framework.mq.rabbitmq.constant.RabbitMqConstants;
import com.cf.imes.framework.mybatis.core.generator.SnowFlakeGenerator;
import com.cf.imes.framework.organ.core.context.OrganContextHolder;
import com.cf.imes.framework.redis.config.ChenfengCacheProperties;
import com.cf.imes.framework.redis.constants.RedisKeyConstants;
import com.cf.imes.framework.redis.util.RedisLockUtil;
import com.cf.imes.module.executor.enums.DataTypeEnum;
import com.cf.imes.module.executor.enums.OrderImportStatusEnum;
import com.cf.imes.module.executor.enums.OrderImportTaskStatusEnum;
import com.cf.imes.module.executor.enums.OrderImportTypeEnum;
import com.cf.imes.module.executor.enums.OrderStatusEnum;
import com.cf.imes.module.plan.controller.admin.orderimport.webcad.vo.WebCadDataReqVO;
import com.cf.imes.module.plan.dal.dataobject.order.OrderDO;
import com.cf.imes.module.plan.dal.dataobject.orderImport.OrderImportTaskDO;
import com.cf.imes.module.plan.dal.mysql.goods.GoodsMapper;
import com.cf.imes.module.plan.dal.mysql.order.OrderMapper;
import com.cf.imes.module.plan.dal.mysql.orderBody.OrderBodyMapper;
import com.cf.imes.module.plan.dal.mysql.orderImport.OrderImportTaskMapper;
import com.cf.imes.module.plan.dal.mysql.plate.PlateMapper;
import com.cf.imes.module.plan.enums.ErrorCodeConstants;
import com.cf.imes.module.plan.service.customplateno.CustomPlateNoGenerateService;
import com.cf.imes.module.plan.service.orderImport.factory.WebCadOrderImportFactory;
import com.cf.imes.module.plan.service.orderImport.property.WebCadImportProperties;
import com.cf.imes.module.system.api.assemblyconfig.AssemblyConfigApi;
import com.cf.imes.module.system.api.systemconfig.SystemConfigApi;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;

import java.io.File;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

import static com.cf.imes.module.executor.enums.ErrorCodeConstants.ORDER_IMPORT_ORGAN_LOCK_ERROR;
import static com.cf.imes.module.plan.enums.ErrorCodeConstants.WEBCAD_ORDER_IMPORT_FAILED;
import static com.cf.imes.module.plan.enums.ErrorCodeConstants.WEBCAD_ORDER_NOT_EXISTS_ERROR;

/**
 * 订单导入服务Service实现类
 *
 * @author Gqr
 * @since 2025/3/4 10:27
 */
@Service
public class WebCadOrderImportServiceImpl implements WebCadOrderImportService {

    private static final Logger log = LoggerFactory.getLogger(WebCadOrderImportServiceImpl.class);
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private SnowFlakeGenerator snowFlakeGenerator;

    @Resource
    private OrderBodyMapper orderBodyMapper;

    @Resource
    private PlateMapper plateMapper;

    @Resource
    private SnowflakeIdWorker3rd idWorker;

    @Resource
    private CustomPlateNoGenerateService customPlateNoGenerateService;

    @Resource
    private RedisLockUtil redisLockUtil;

    @Resource
    private ChenfengCacheProperties chenfengCacheProperties;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private SystemConfigApi systemConfigApi;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private OrderImportTaskMapper orderImportTaskMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    private static final String REDIS_UNIQUEKEY = "webcad";

    @Resource
    private WebCadImportProperties webCadImportProperties;

    @Resource
    private AssemblyConfigApi assemblyConfigApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean webCadOrderImport(MultipartFile file) {
        Long organId = OrganContextHolder.getOrganId();

        // 是否同步处理
        boolean sync = true;

        Long taskId = null;
        OrderDO orderDO = null;
        JsonFactory factory = new JsonFactory();

        Long cadViewFileId;
        try (GZIPInputStream gzipInputStream = new GZIPInputStream(file.getInputStream());
             JsonParser parser = factory.createParser(gzipInputStream)) {
            factory.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE);

            int plateCount = 0;
            String fileName = null;
            while (parser.nextToken() != JsonToken.END_OBJECT) {
                String fieldName = parser.getCurrentName();
                if (StringUtils.isEmpty(fieldName)) {
                    continue;
                }

                parser.nextToken(); // 移动到字段值位置

                if ("plateCount".equals(fieldName)) {
                    plateCount = parser.getIntValue();
                } else if ("fileName".equals(fieldName)) {
                    fileName = parser.getText();
                } else if ("OrderNo".equals(fieldName)) {
                    orderDO = analyzeOrder(parser.getText(), organId);
                } else if ("blockData".equals(fieldName)) {
                    if (plateCount < webCadImportProperties.getAsyncPlateThreshold()) {
                        // 上锁
                        addSyncLock(organId);

                        // 在异步阈值范围内，直接解析整个对象
                        ObjectMapper mapper = new ObjectMapper();
                        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                        WebCadDataReqVO webCadDataReqVO = mapper.readValue(parser, WebCadDataReqVO.class);
                        WebCadOrderImportFactory webCadOrderImportFactory = new WebCadOrderImportFactory(organId, orderDO, snowFlakeGenerator, orderMapper, orderBodyMapper, plateMapper,
                                idWorker, goodsMapper, customPlateNoGenerateService, systemConfigApi, assemblyConfigApi, webCadImportProperties.getCadImportPlateNumThreshold(), jdbcTemplate);

                        // cad图纸文件id
                        cadViewFileId = webCadDataReqVO.getCadViewFileId();
                        AssertUtils.notEmpty(cadViewFileId, ErrorCodeConstants.WEBCAD_ORDER_IMPORT_CAD_VIEW_FILE_ID_EMPTY_ERROR);
                        webCadOrderImportFactory.analyzeTempData(webCadDataReqVO);
                    } else {
                        sync = false;

                        // plateCount 大于阈值时将 blockData 写入文件
                        ObjectMapper mapper = new ObjectMapper();
                        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

                        // 读取结构
                        JsonNode node = mapper.readTree(parser);

                        // 缓存请求，创建导入任务
                        taskId = initiateTask(node, organId, orderDO.getId(), fileName);

                        // 发送异步消息
                        sendMessage(taskId);

                        // 跳过当前 blockData 解析步骤
                        parser.skipChildren(); // 忽略 blockData
                    }
                } else {
                    parser.skipChildren(); // 忽略其他字段
                }
            }
        } catch (ServiceException se) {
            // 移除临时文件
            removeCacheFileWhenException(sync, taskId);

            throw se;
        } catch (Exception e) {
            // 移除临时文件
            removeCacheFileWhenException(sync, taskId);

            ErrorCode webcadOrderImportFailed = WEBCAD_ORDER_IMPORT_FAILED;
            log.error(webcadOrderImportFailed.getMsg(), e);
            throw new ServiceException(webcadOrderImportFailed);
        } finally {
            // 同步解锁
            unlock(sync, organId);
        }
        return sync;
    }

    /**
     * 解析订单信息
     *
     * @param orderNo
     */
    private OrderDO analyzeOrder(String orderNo, Long organId) {
        // 查询订单信息
        OrderDO orderDOFromOrderNo = orderMapper.selectOne(new LambdaUpdateWrapper<OrderDO>()
                .eq(OrderDO::getId, NumberUtil.parseLong(orderNo))
                .eq(OrderDO::getOrganId, organId)
                .eq(OrderDO::getDeleted, false));
        if (ObjectUtil.isNull(orderDOFromOrderNo)) {
            throw new ServiceException(WEBCAD_ORDER_NOT_EXISTS_ERROR, orderNo);
        } else {
            Integer status = orderDOFromOrderNo.getStatus();
            // 更新订单来源为webcad
            LambdaUpdateWrapper<OrderDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<OrderDO>()
                    .eq(OrderDO::getId, orderDOFromOrderNo.getId())
                    .eq(OrderDO::getOrganId, organId)
                    .set(OrderDO::getDataType, DataTypeEnum.API_IMPORT.getStatus());
            // 如果导入订单为空单，则更新为新单
            if (OrderStatusEnum.EMPTY.getStatus().equals(status)) {
                lambdaUpdateWrapper.set(OrderDO::getStatus, OrderStatusEnum.NEW_ORDER.getStatus());
            }
            // 已封包的订单修改为未封包
            if (OrderPackageStatusEnum.PACKAGED.getStatus().equals(orderDOFromOrderNo.getPackaged())) {
                lambdaUpdateWrapper.set(OrderDO::getPackaged, OrderPackageStatusEnum.UNPACKED.getStatus());
            }
            // 已经生产完成的改为生产中
            if (OrderStatusEnum.FINISH_PRODUCTION.getStatus().equals(status)) {
                lambdaUpdateWrapper.set(OrderDO::getStatus, OrderStatusEnum.IN_PRODUCTION.getStatus());
            }
            orderMapper.update(lambdaUpdateWrapper);
        }

        return orderDOFromOrderNo;
    }

    /**
     * 缓存请求，发起异步
     *
     * @param node
     * @param organId
     * @return
     * @throws IOException
     */
    private Long initiateTask(JsonNode node, Long organId, Long orderId, String fileName) throws IOException {
        // 创建任务
        Long taskId = (Long) snowFlakeGenerator.nextId(null);
        // 创建导入任务
        OrderImportTaskDO orderImportTaskDO = OrderImportTaskDO.builder()
                .id(taskId)
                .type(OrderImportTypeEnum.API.getType())
                .importStatus(OrderImportStatusEnum.IMPORT_NOT_YET.getStatus())
                .status(OrderImportTaskStatusEnum.CREATE_NOT_CONSUME.getStatus())
                .fileName(fileName)
                .orderId(orderId)
                .organId(organId)
                .build();
        orderImportTaskMapper.insert(orderImportTaskDO);
        // 缓存请求到本地磁盘
        ObjectMapper objectMapper = new ObjectMapper();
        File file = new File(webCadImportProperties.getTempFilePath() + File.separator + taskId + ".json");
        objectMapper.writeValue(file, node);

        return taskId;
    }

    /**
     * 发送异步消息
     *
     * @param taskId
     */
    private void sendMessage(Long taskId) {
        Message message = MessageBuilder
                .withBody(taskId.toString().getBytes())
                .setHeader("peek", DynamicDataSourceContextHolder.peek())
                .setExpiration("60000")  // 设置消息级 TTL（60 秒）
                .build();
        //如果处于事务中，待事务提交成功了再执行后续操作，防止事务未提交完成导致消费端查不到数据
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    // 数据库操作全部完成发送消息
                    rabbitTemplate.convertAndSend(RabbitMqConstants.ORDER_IMPORT_WEBCAD_EXCHANGE, webCadImportProperties.getNode(), message);
                }
            });
        } else {
            // 数据库操作全部完成发送消息
            rabbitTemplate.convertAndSend(RabbitMqConstants.ORDER_IMPORT_WEBCAD_EXCHANGE, webCadImportProperties.getNode(), message);
        }
    }

    /**
     * 加同步导入锁
     *
     * @param organId
     */
    private void addSyncLock(Long organId) {
        String importLockKey = String.format(RedisKeyConstants.ORDER_IMPORT_LOCK_KEY, organId);
        // 检查机构导入锁
        boolean lockResult = redisLockUtil.acquireLock(importLockKey, REDIS_UNIQUEKEY, chenfengCacheProperties.getLockTimeout());
        if (!lockResult) {
            throw new ServiceException(ORDER_IMPORT_ORGAN_LOCK_ERROR);
        }
    }

    /**
     * 解锁
     */
    private void unlock(boolean sync, Long organId) {
        if (sync) {
            // 解同步锁
            redisLockUtil.releaseLock(String.format(RedisKeyConstants.ORDER_IMPORT_LOCK_KEY, organId), REDIS_UNIQUEKEY);
        }
    }


    /**
     * 异常时移除临时文件
     */
    private void removeCacheFileWhenException(boolean sync, Long taskId) {
        if (!sync && ObjectUtil.isNotNull(taskId)) {
            String filePath = webCadImportProperties.getTempFilePath() + File.separator + taskId + ".json";
            try {
                FileUtil.del(filePath);
            } catch (IORuntimeException e) {
                // 可以记录日志
                log.warn("删除任务缓存文件失败: {}", filePath, e);
            }
        }
    }
}
