package com.neusoft.smart.pos.strategy.controller;

import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.order.request.PostCreateOrderRequest;
import com.neusoft.smart.pos.dto.order.request.VariableFee;
import com.neusoft.smart.pos.framework.dto.ResponseData;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.order.constants.TradeErrorCode;
import com.neusoft.smart.pos.strategy.service.StrategyService;
import com.neusoft.smart.pos.utils.PosDeviceRedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@Api(value = "策略管理使用接口", description = "策略管理使用接口")
@RestController
@RequestMapping(path = "/strategy")
@Validated
public class StrategyController {

    @Autowired
    private StrategyService strategyService;

    @ApiOperation(value = "订单试算接口", notes = "订单试算方法")
    @PostMapping("/doTrial")
    public ResponseData<PostCreateOrderRequest> doTrial(@RequestBody PostCreateOrderRequest createOrderRequest) {
        //根据设备SN校正orgId和shopId
        if(createOrderRequest.getSerialNo() != null && !createOrderRequest.getSerialNo().isEmpty()) {
            //1.查询订单信息，并进行校验
            val deviceInfo = PosDeviceRedisUtils.getDeviceInfoBySerialNo(createOrderRequest.getSerialNo());
            if (null == deviceInfo) {
                throw new BusinessCommonException(TradeErrorCode.DEVICE_ORG_EMPTY);
            }

            createOrderRequest.setOrgId(deviceInfo.getOrganizationId());
            createOrderRequest.setShopId(deviceInfo.getStoreId());
        }

        //如果订单类型参数为空，默认为普通订单
        if(createOrderRequest.getOrderType() == null || createOrderRequest.getOrderType().isEmpty()){
            createOrderRequest.setOrderType(DictionaryConstant.ORDER_TYPE_ZC.getCode());
        }

        List<VariableFee> fees = strategyService.doCalculation(createOrderRequest);
        createOrderRequest.setVariableFees(fees);
        return new ResponseData<>(createOrderRequest);
    }
}
