package com.hzya.frame.plugin.lets.util;

import cn.hutool.core.lang.Assert;

import com.hzya.frame.sysnew.integtationTaskLivingDetails.dao.IIntegrationTaskLivingDetailsDao;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.entity.IntegrationTaskLivingDetailsEntity;
import com.hzya.frame.uuid.UUIDLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 保存或者更新业务日志
 */
@Component
public class SaveOrUpdateBusinessLogUtil {

    Logger logger = LoggerFactory.getLogger(SaveOrUpdateBusinessLogUtil.class);

    @Autowired
    private IIntegrationTaskLivingDetailsDao iIntegrationTaskLivingDetailsDao;

    private static final Object insertOrUpdateLock = new Object();

    private static final Object queryDetailsLock = new Object();

    private static final String successY = "Y";

    private static final String failN = "N";

    /**
     * 保存或者更新
     *
     * @param integrationTaskLivingDetailsEntity 提交参数
     */
    public void saveOrUpdate(IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity) {
        Assert.notNull(integrationTaskLivingDetailsEntity, "integrationTaskLivingDetailsEntity不能为空");
        Assert.notNull(integrationTaskLivingDetailsEntity.getRootAppPk(), "源系统单号不能为空");
        Assert.notNull(integrationTaskLivingDetailsEntity.getPluginId(), "场景id不能为空");

        try {
            IntegrationTaskLivingDetailsEntity integrationTaskLivingDetails = null;
            synchronized (queryDetailsLock) {
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity1 = new IntegrationTaskLivingDetailsEntity();
                integrationTaskLivingDetailsEntity1.setRootAppPk(integrationTaskLivingDetailsEntity.getRootAppPk());
                integrationTaskLivingDetailsEntity1.setPluginId(integrationTaskLivingDetailsEntity.getPluginId());
                List<IntegrationTaskLivingDetailsEntity> integrationTaskLivingDetailsEntities = iIntegrationTaskLivingDetailsDao.query(integrationTaskLivingDetailsEntity1);
                if (integrationTaskLivingDetailsEntities != null && integrationTaskLivingDetailsEntities.size() > 0) {
                    integrationTaskLivingDetails = integrationTaskLivingDetailsEntities.get(0);
                }
            }
            if (integrationTaskLivingDetails != null) {
                //存在，则更新，可能是N→Y / N→N
                synchronized (insertOrUpdateLock) {
                    integrationTaskLivingDetailsEntity.setId(integrationTaskLivingDetails.getId());
                    updateSuccessMessage(integrationTaskLivingDetailsEntity);
                }
            } else {
                //不存在，则新增，可能是→Y / →N
                Long uuid = UUIDLong.longUUID();
                integrationTaskLivingDetailsEntity.setId(String.valueOf(uuid));
                saveSuccessMessage(integrationTaskLivingDetailsEntity);
//                logger.info("integration_task_living_details->日志保存成功，主键：{}", save.getId());
            }
        } catch (Exception e) {
            logger.error("SaveOrUpdateBusinessLogUtil对应的saveOrUpdate方法抛出异常，日志详情保存失败！", e);
            //2024年9月3日 10:26:45 如果这里往上抛出异常，没有功能搭配处理
        }
    }
    /**
     * 更新日志 存在，则更新，可能是N→Y / N→N
     * 肯定有id
     * @param integrationTaskLivingDetailsEntity
     */
    private void updateSuccessMessage(IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity) {
        IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity1 = queryIntegrationTaskLivingDetailsEntityN(integrationTaskLivingDetailsEntity.getId());
        if (successY.equals(integrationTaskLivingDetailsEntity.getNewState())) {
            //N→Y
            iIntegrationTaskLivingDetailsDao.deleteEntity(integrationTaskLivingDetailsEntity1);

            String successIdentification = "success";
            integrationTaskLivingDetailsEntity.setRootAppNewData(successIdentification);
            integrationTaskLivingDetailsEntity.setNewTransmitInfo(successIdentification);
            iIntegrationTaskLivingDetailsDao.saveSuccessLog(integrationTaskLivingDetailsEntity);

        } else if (failN.equals(integrationTaskLivingDetailsEntity.getNewState())) {
            //N→N
            String rootAppNewData = integrationTaskLivingDetailsEntity.getRootAppNewData();
            if (integrationTaskLivingDetailsEntity.getRootAppNewData() != null && !integrationTaskLivingDetailsEntity.getRootAppNewData().trim().equals("") && integrationTaskLivingDetailsEntity.getRootAppNewData().length() >= 500) {
                rootAppNewData = integrationTaskLivingDetailsEntity.getRootAppNewData().substring(0, 500);
            }
            String newTransmitInfo = integrationTaskLivingDetailsEntity.getNewTransmitInfo();
            if (integrationTaskLivingDetailsEntity.getNewTransmitInfo() != null && !integrationTaskLivingDetailsEntity.getNewTransmitInfo().trim().equals("") && integrationTaskLivingDetailsEntity.getNewTransmitInfo().length() >= 500) {
                newTransmitInfo = integrationTaskLivingDetailsEntity.getNewTransmitInfo().substring(0, 500);
            }
            integrationTaskLivingDetailsEntity.setRootAppNewData(rootAppNewData);
            integrationTaskLivingDetailsEntity.setNewTransmitInfo(newTransmitInfo);
            iIntegrationTaskLivingDetailsDao.entity_updatebyid(integrationTaskLivingDetailsEntity);
        }
    }

    /**
     * 新增日志 不存在，则新增，可能是→Y / →N
     * @param integrationTaskLivingDetailsEntity
     */
    private void saveSuccessMessage(IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity) {
        if (successY.equals(integrationTaskLivingDetailsEntity.getNewState())) {
            //→Y
            String successIdentification = "success";
            integrationTaskLivingDetailsEntity.setRootAppNewData(successIdentification);
            integrationTaskLivingDetailsEntity.setNewTransmitInfo(successIdentification);
            iIntegrationTaskLivingDetailsDao.saveSuccessLog(integrationTaskLivingDetailsEntity);

        } else if (failN.equals(integrationTaskLivingDetailsEntity.getNewState())) {
            //→N
            String rootAppNewData = integrationTaskLivingDetailsEntity.getRootAppNewData();
            if (integrationTaskLivingDetailsEntity.getRootAppNewData() != null && !integrationTaskLivingDetailsEntity.getRootAppNewData().trim().equals("") && integrationTaskLivingDetailsEntity.getRootAppNewData().length() >= 500) {
                rootAppNewData = integrationTaskLivingDetailsEntity.getRootAppNewData().substring(0, 500);
            }
            String newTransmitInfo = integrationTaskLivingDetailsEntity.getNewTransmitInfo();
            if (integrationTaskLivingDetailsEntity.getNewTransmitInfo() != null && !integrationTaskLivingDetailsEntity.getNewTransmitInfo().trim().equals("") && integrationTaskLivingDetailsEntity.getNewTransmitInfo().length() >= 500) {
                newTransmitInfo = integrationTaskLivingDetailsEntity.getNewTransmitInfo().substring(0, 500);
            }
            integrationTaskLivingDetailsEntity.setRootAppNewData(rootAppNewData);
            integrationTaskLivingDetailsEntity.setNewTransmitInfo(newTransmitInfo);
            iIntegrationTaskLivingDetailsDao.save(integrationTaskLivingDetailsEntity);
        }

    }

    /**
     * 修改成功消息
     *
     * @author liuyang
     */
//    private void updateSuccessMessage(IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity) {
//        if (integrationTaskLivingDetailsEntity != null) {
//            if (successY.equals(integrationTaskLivingDetailsEntity.getNewState())) {
//                //成功
//                String successIdentification = "success";
//                integrationTaskLivingDetailsEntity.setRootAppNewData(successIdentification);
//                integrationTaskLivingDetailsEntity.setNewTransmitInfo(successIdentification);
//                /**
//                 * integrationTaskLivingDetailsEntity.setRoot_app_new_data(JSON.toJSONString(searchPurchaseReceiptOrder));
//                 * integrationTaskLivingDetailsEntity.setNew_transmit_info(cgrkApi);
//                 */
//            } else if (failN.equals(integrationTaskLivingDetailsEntity.getNewState())) {
//                //2024年9月2日 17:09:07 如果失败，仅保留500个字符，用于平衡数据库性能
//                //2024年9月2日 17:15:19 如果该单据判断为失败，则integration_task_living_details表的root_app_new_data、new_transmit_info字段，仅保留500个长度的字符，用于平衡性能，速网、珍视名项目这一块性能很差
//                String rootAppNewData = integrationTaskLivingDetailsEntity.getRootAppNewData();
//                if (integrationTaskLivingDetailsEntity.getRootAppNewData() != null && !integrationTaskLivingDetailsEntity.getRootAppNewData().trim().equals("") && integrationTaskLivingDetailsEntity.getRootAppNewData().length() >= 500) {
//                    rootAppNewData = integrationTaskLivingDetailsEntity.getRootAppNewData().substring(0, 500);
//                }
//                String newTransmitInfo = integrationTaskLivingDetailsEntity.getNewTransmitInfo();
//                if (integrationTaskLivingDetailsEntity.getNewTransmitInfo() != null && !integrationTaskLivingDetailsEntity.getNewTransmitInfo().trim().equals("") && integrationTaskLivingDetailsEntity.getNewTransmitInfo().length() >= 500) {
//                    newTransmitInfo = integrationTaskLivingDetailsEntity.getNewTransmitInfo().substring(0, 500);
//                }
//                integrationTaskLivingDetailsEntity.setRootAppNewData(rootAppNewData);
//                integrationTaskLivingDetailsEntity.setNewTransmitInfo(newTransmitInfo);
//            } else {
//                Assert.state(false, "不合法的newState，不能为空请传递Y或者N！");
//            }
//        }
//    }

    /**
     * 根据明细id查询明细信息
     *
     * @author liuyang
     */
    public IntegrationTaskLivingDetailsEntity queryIntegrationTaskLivingDetailsEntity(String integration_task_living_details_id) {
        IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
        integrationTaskLivingDetailsEntity.setId(integration_task_living_details_id);
        IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity1 = iIntegrationTaskLivingDetailsDao.queryEntityById(integrationTaskLivingDetailsEntity);
        Assert.notNull(integrationTaskLivingDetailsEntity, "根据主键id没有查询到明细信息");
        return integrationTaskLivingDetailsEntity1;
    }

    /**
     * 根据明细id查询明细信息，成功表 integration_task_living_details_success
     */
    public IntegrationTaskLivingDetailsEntity queryIntegrationTaskLivingDetailsEntityY(IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity) {
//        Assert.notNull(integration_task_living_details_id, "业务明细id不能为空");
//        IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
//        integrationTaskLivingDetailsEntity.setId(integration_task_living_details_id);
//        integrationTaskLivingDetailsEntity.setNewState("Y");//查询成功表
        IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity1 = iIntegrationTaskLivingDetailsDao.queryEntity(integrationTaskLivingDetailsEntity);
        Assert.notNull(integrationTaskLivingDetailsEntity1, "根据主键id没有查询到明细信息");
        return integrationTaskLivingDetailsEntity1;
    }
    /**
     * 根据明细id查询明细信息，错误表 integration_task_living_details
     */
    public IntegrationTaskLivingDetailsEntity queryIntegrationTaskLivingDetailsEntityN(String integration_task_living_details_id) {
        Assert.notNull(integration_task_living_details_id, "业务明细id不能为空");
        IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
        integrationTaskLivingDetailsEntity.setId(integration_task_living_details_id);
        integrationTaskLivingDetailsEntity.setNewState("N");//查询失败表
        IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity1 = iIntegrationTaskLivingDetailsDao.queryEntity(integrationTaskLivingDetailsEntity);
        Assert.notNull(integrationTaskLivingDetailsEntity1, "根据主键id没有查询到明细信息");
        return integrationTaskLivingDetailsEntity1;
    }
}
