package cn.freemud.service.universal.impl;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.entities.bo.CreateOrderBo;
import cn.freemud.entities.vo.CreateOrderBaseVo;
import cn.freemud.entities.vo.CreateOrderSaasVo;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.universal.UniversalOrderService;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.request.create.CreateOrderRequest;
import com.freemud.sdk.api.assortment.order.response.order.CreateOrderResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.springframework.stereotype.Service;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.util.Iterator;
import java.util.Set;

@Service
public class SaasOrderService extends UniversalOrderService {

    @Override
    public void getCustomCreateOrderBo(CreateOrderBo createOrderBo) {

    }

    @Override
    public void validParam(CreateOrderBaseVo createOrderBaseVo) {
        CreateOrderSaasVo createOrderSaasVo = (CreateOrderSaasVo) createOrderBaseVo;
        // 利用 HibernateValidator 校验  标签参数是否满足
        HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class)
                .configure()
                .failFast(false);
        ValidatorFactory validatorFactory = configuration.buildValidatorFactory();
        Set<ConstraintViolation<CreateOrderBaseVo>> set = validatorFactory.getValidator().validate(createOrderSaasVo);
        if (CollectionUtils.isNotEmpty(set)) {
            Iterator<ConstraintViolation<CreateOrderBaseVo>> iterator = set.iterator();
            if (iterator.hasNext()) {
                ConstraintViolation<CreateOrderBaseVo> constraintViolation = iterator.next();
                throw new ServiceException(ResponseResult.PARAMETER_MISSING, constraintViolation.getMessage());
            }
        }
    }

    @Override
    protected CreateOrderRequest absGetCreateOrderRequest(CreateOrderBo createOrderBo) {
        // fisherman 可以直接转换对象  下面代码先留着 和其他的地方有 重复
        return super.createOrderAdapter.convent2CreateOrderRequest(createOrderBo);
    }

    /**
     *  扣减库存订单
     * @param createOrderBo
     * @param createOrderResponse
     * @return
     */
    @Override
    protected BaseResponse sendActivityUpdateStock(CreateOrderBo createOrderBo, CreateOrderResponse createOrderResponse) {
        return super.defalutSendActivityUpdateStock(createOrderBo, createOrderResponse);
    }

    @Override
    public OrderExtInfoDto getExtInfo(CreateOrderBo createOrderBo) {
        OrderExtInfoDto extInfo = super.getExtInfoUniversal(createOrderBo);
        createOrderBo.setExtInfo(extInfo);
        return extInfo;
    }


}
