package com.hzs.config.pub.controller;

import com.hzs.common.core.constant.SystemFieldConstants;
import com.hzs.common.core.enums.EBusinessType;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.reflect.ReflectUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.third.mq.IDelayedMessageApi;
import com.hzs.third.mq.dto.DelayedMessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 配置controller
 * @Author: sui q
 * @Time: 2023/3/10 15:45
 * @Classname: ConfigBaseController
 * @PackageName: com.hzs.config.pub.controller
 */
@Slf4j
public abstract class ConfigBaseController extends BaseController {

    @DubboReference
    private IDelayedMessageApi delayedMessageApi;

    protected boolean sendDelayedMessage(Object config, Integer delayBusType, String key, String... otherKey) {
        Integer pkId = null;
        if (isLong(ReflectUtils.invokeGetter(config, SystemFieldConstants.PK_ID_VALUE))) {
            pkId = ReflectUtils.invokeGetter(config, SystemFieldConstants.PK_ID_VALUE);
        } else {
            //Long转Integer
            Long pkIdL = ReflectUtils.invokeGetter(config, SystemFieldConstants.PK_ID_VALUE);
            if (pkIdL != null) {
                pkId = pkIdL.intValue();
            }
        }

        Date effectiveDate = ReflectUtils.invokeGetter(config, SystemFieldConstants.EFFECTIVE_DATE_VALUE);
        if (effectiveDate == null) {
            effectiveDate = DateUtils.currentDate();
        }
        boolean flag = DateUtils.compareDateTimeAfter(effectiveDate, DateUtils.currentDateTime());
        if (flag) {
            List<String> keyList = new ArrayList<>();
            keyList.add(key);
            if (otherKey != null && otherKey.length > 0) {
                keyList.addAll(Arrays.asList(otherKey));
            }
            DelayedMessageDTO delayedMessageDTO = DelayedMessageDTO.builder()
                    .pkId(pkId)
                    .keyList(keyList)
                    .type(EBusinessType.REDIS_KEY.getValue())
                    .businessType(delayBusType)
                    .effectDate(effectiveDate).build();
            delayedMessageApi.sendDelayedMessage(delayedMessageDTO);
        }
        return flag;
    }

    /**
     * @description: 校验object的属性值是Long类型还是Integer
     * @author: zhang jing
     * @date: 2024/5/20 16:01
     * @param: [field, object]
     **/
    public static boolean isLong(Object object) {
        if (object instanceof Long) {
            return false;
        } else if (object instanceof Integer) {
            return true;
        } else {
            return false;
        }
    }
}
