/**
 *
 */

package com.yc.ship.module.trade.framework.web;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.yc.ship.framework.common.lang.Asserts;
import com.yc.ship.module.otc.api.store.StoreApi;
import com.yc.ship.module.otc.api.store.dto.StoreMachineDTO;
import com.yc.ship.module.trade.framework.annotation.StoreMachine;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


/**
 * &#064;Description 门店设备自定义参数Resolver
 * &#064;Author qsl
 * &#064;Date 2025/8/8 14:41
 */
public class StoreMachineHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Resource
    @Lazy
    private StoreApi storeApi;

    private RequestResponseBodyMethodProcessor handlerMethodArgumentResolver;

    public StoreMachineHandlerMethodArgumentResolver(RequestResponseBodyMethodProcessor handlerMethodArgumentResolver) {
        this.handlerMethodArgumentResolver = handlerMethodArgumentResolver;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
         return parameter.hasParameterAnnotation(StoreMachine.class) && parameter.getParameterType().isAssignableFrom(StoreMachineDTO.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest webRequest, WebDataBinderFactory factory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String machineId = ServletUtil.getHeader(request,"machine-id","utf-8");
        Asserts.isTrue(StrUtil.isNotBlank(machineId),"未识别设备参数");
        StoreMachineDTO storeMachineDTO =  storeApi.getMachineByMachineId(machineId).getCheckedData();
        return storeMachineDTO;
    }
}
