package com.neusoft.smart.pos.promotion.service;

import com.neusoft.smart.pos.constants.DictionaryConstant;
import com.neusoft.smart.pos.dto.promotion.request.GetPreferentialPriceRequest;
import com.neusoft.smart.pos.dto.promotion.request.PromotionPayChannelQueryRequest;
import com.neusoft.smart.pos.dto.promotion.request.PromotionPayChannelRequest;
import com.neusoft.smart.pos.dto.promotion.response.GetPreferentialPriceResponse;
import com.neusoft.smart.pos.dto.promotion.response.PromotionPayChannelResponse;
import com.neusoft.smart.pos.dto.trade.response.GetSettlementResponse;
import com.neusoft.smart.pos.framework.exception.BusinessCommonException;
import com.neusoft.smart.pos.framework.utils.BeanUtil;
import com.neusoft.smart.pos.promotion.constants.PromotionErrorCode;
import com.neusoft.smart.pos.promotion.persistent.domain.PromotionPayChannel;
import com.neusoft.smart.pos.promotion.persistent.ext.domain.PromotionPayChannelQuery;
import com.neusoft.smart.pos.promotion.persistent.repository.PromotionPayChannelRepository;
import com.neusoft.smart.pos.dto.promotion.bean.CalculateBean;
import com.neusoft.smart.pos.promotion.service.remote.RemoteMemberService;
import com.neusoft.smart.pos.promotion.service.remote.RemoteTradeSettlementService;
import com.neusoft.smart.pos.utils.PosDeviceRedisUtils;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

@Service
public class PromotionService {
    
    @Autowired
    private RemoteMemberService remoteMemberService;
    
    @Autowired
    private MemberPromotionCalculate memberPromotionCalculate;
    
    @Autowired
    private ManualPromotionCalculate manualPromotionCalculate;
    
    @Autowired
    private PaymentPromotionCalculate paymentPromotionCalculate;
    
    @Autowired
    private PromotionPayChannelRepository promotionPayChannelRepository;
    
    @Autowired
    private RemoteTradeSettlementService remoteTradeSettlementService;
    
    /**
     * @param promotionPayChannelRequest
     */
    public void create(PromotionPayChannelRequest promotionPayChannelRequest) {
        val promotionPayChannelQuery = new PromotionPayChannelQuery();
        promotionPayChannelQuery.setIsPage(false);
        promotionPayChannelQuery.setIsFilteredByRole(false);
        if (null == promotionPayChannelRequest.getStoreId()) {
            promotionPayChannelQuery.setIsStoreIdNull(true);
        } else {
            promotionPayChannelQuery.setStoreId(promotionPayChannelRequest.getStoreId());
        }
        promotionPayChannelQuery.setOrgId(promotionPayChannelRequest.getOrgId());
        promotionPayChannelQuery.setPayChannel(promotionPayChannelRequest.getPayChannel());
        promotionPayChannelQuery.setOffType(promotionPayChannelRequest.getOffType());
        val count = promotionPayChannelRepository.getCount(promotionPayChannelQuery);
        if (count > 0) {
            throw new BusinessCommonException(PromotionErrorCode.PAYMENT_PROMOTION_DUPLICATION);
        }
        promotionPayChannelRepository.create(BeanUtil.parse(promotionPayChannelRequest, PromotionPayChannel.class));
    }
    
    /**
     * @param promotionPayChannelRequest
     */
    public void update(PromotionPayChannelRequest promotionPayChannelRequest) {
        promotionPayChannelRepository.update(BeanUtil.parse(promotionPayChannelRequest, PromotionPayChannel.class));
    }
    
    /**
     * @param id
     */
    public void delete(Integer id) {
        promotionPayChannelRepository.delete(id);
    }
    
    /**
     * @param id
     * @return
     */
    public PromotionPayChannelResponse get(Integer id) {
        return BeanUtil.parse(promotionPayChannelRepository.get(id), PromotionPayChannelResponse.class);
    }
    
    public List<PromotionPayChannelResponse> getList(PromotionPayChannelQueryRequest promotionPayChannelQueryRequest) {
        if (!promotionPayChannelQueryRequest.getStoreId().equals(0)) {
            GetSettlementResponse getSettlementResponse = remoteTradeSettlementService.querySettlement(promotionPayChannelQueryRequest.getOrgId(), promotionPayChannelQueryRequest.getStoreId()).getResult();
            if (!DictionaryConstant.SETTLEMENT_TYPE_MD.getCode().equals(getSettlementResponse.getSettlementType())) {
                promotionPayChannelQueryRequest.setStoreId(0);
            }
        }
        List<PromotionPayChannel> poList = promotionPayChannelRepository.getList(BeanUtil.parse(promotionPayChannelQueryRequest, PromotionPayChannelQuery.class));
        return BeanUtil.parseList(poList, PromotionPayChannelResponse.class);
    }
    
    public Integer getCount(PromotionPayChannelQueryRequest promotionPayChannelQueryRequest) {
        return promotionPayChannelRepository.getCount(BeanUtil.parse(promotionPayChannelQueryRequest, PromotionPayChannelQuery.class));
    }
    
    /**
     * @param getPreferentialPriceRequest
     * @return
     */
    public GetPreferentialPriceResponse getPreferentialPriceNew(GetPreferentialPriceRequest getPreferentialPriceRequest) {
        GetPreferentialPriceResponse getPreferentialPriceResponse = new GetPreferentialPriceResponse();
        //充值暂时没有优惠活动,直接返回数字
        if (getPreferentialPriceRequest.getOrderType().equalsIgnoreCase(DictionaryConstant.ORDER_TYPE_HYCZ.getCode())) {
            getPreferentialPriceResponse.setActualPrice(getPreferentialPriceRequest.getTotalPrice());
            getPreferentialPriceResponse.setTotalPrice(getPreferentialPriceRequest.getTotalPrice());
            return getPreferentialPriceResponse;
        }
        //兼容posPay的app支付传商品的bug
        if (null != getPreferentialPriceRequest.getOrderItems() && getPreferentialPriceRequest.getOrderItems().size() == 1 &&
                getPreferentialPriceRequest.getOrderItems().get(0).getUnitPrice().doubleValue() <= 0 &&
                getPreferentialPriceRequest.getOrderItems().get(0).getQuantity().equals(0)) {
            getPreferentialPriceResponse.setActualPrice(getPreferentialPriceRequest.getTotalPrice());
            getPreferentialPriceResponse.setTotalPrice(getPreferentialPriceRequest.getTotalPrice());
            return getPreferentialPriceResponse;
        }
        CalculateBean calculateBean = BeanUtil.parse(getPreferentialPriceRequest, CalculateBean.class);
        calculateBean.setOrderPreferentialItems(BeanUtil.parseList(getPreferentialPriceRequest.getOrderItems(), CalculateBean.OrderPreferentialItem.class));
        //手动查询出设备的信息,然后set下
        if(!StringUtils.isEmpty(calculateBean.getSerialNo())){
            val deviceInfo = PosDeviceRedisUtils.getDeviceInfoBySerialNo(calculateBean.getSerialNo());
            calculateBean.setShopId(deviceInfo.getStoreId());
            calculateBean.setOrgId(deviceInfo.getOrganizationId());
        } else {
            calculateBean.setShopId(getPreferentialPriceRequest.getShopId());
            calculateBean.setOrgId(getPreferentialPriceRequest.getOrgId());
        }
        if (null != getPreferentialPriceRequest.getOrderItems()) {
            calculateBean.setOrderPreferentialItems(new ArrayList<>());
            CalculateBean finalCalculateBean = calculateBean;
            getPreferentialPriceRequest.getOrderItems().forEach(item -> {
                val orderPreferentialItem = BeanUtil.parse(item, CalculateBean.OrderPreferentialItem.class);
                orderPreferentialItem.setPreferentialUnitPrice(orderPreferentialItem.getUnitPrice());
                finalCalculateBean.getOrderPreferentialItems().add(orderPreferentialItem);
            });
            
        }
        
        BigDecimal totalPrice = new BigDecimal("0.00");
        //有商品,累加商品金额作为总支付金额
        //没有商品 读取传给的总支付金额
        if (null != calculateBean.getOrderItems()) {
            for (GetPreferentialPriceRequest.OrderItem item : calculateBean.getOrderItems()) {
                totalPrice = totalPrice.add(item.getUnitPrice().multiply(item.getQuantity())).setScale(2, RoundingMode.UP);
            }
        } else {
            totalPrice = calculateBean.getTotalPrice();
        }
        //原始价格
        calculateBean.setTotalPrice(totalPrice);

        //按无折扣初始化实际价格
        BigDecimal discount = new BigDecimal("1.00");
        calculateBean.setActualPrice(calculateBean.getTotalPrice().multiply(discount).setScale(2, RoundingMode.UP));
        //按无折扣初始化每一件商品的实际价格
        if (null != calculateBean.getOrderItems()) {
            BigDecimal finalDiscount = discount;
            calculateBean.getOrderPreferentialItems().forEach(item ->
                    item.setPreferentialUnitPrice(item.getUnitPrice().multiply(finalDiscount).setScale(2, RoundingMode.UP)));
        }

        //计算会员
        calculateBean = memberPromotionCalculate.calculatePrice(calculateBean);
        //计算支付营销活动
        calculateBean = paymentPromotionCalculate.calculatePrice(calculateBean);
        //计算手动营销
        calculateBean = manualPromotionCalculate.calculatePrice(calculateBean);
        BeanUtils.copyProperties(calculateBean, getPreferentialPriceResponse);
        return getPreferentialPriceResponse;
    }
    
    
//    /**
//     * 临时计算一下合计
//     *
//     * @param getPreferentialPriceRequest
//     * @return
//     */
//    public GetPreferentialPriceResponse getPreferentialPrice(GetPreferentialPriceRequest getPreferentialPriceRequest) {
//        GetPreferentialPriceResponse getPreferentialPriceResponse = new GetPreferentialPriceResponse();
//        //充值暂时没有优惠活动,直接返回数字
//        if (getPreferentialPriceRequest.getOrderType().equalsIgnoreCase(DictionaryConstant.ORDER_TYPE_HYCZ.getCode())) {
//            getPreferentialPriceResponse.setActualPrice(getPreferentialPriceRequest.getTotalPrice());
//            getPreferentialPriceResponse.setTotalPrice(getPreferentialPriceRequest.getTotalPrice());
//            return getPreferentialPriceResponse;
//        }
//
//        //兼容posPay的app支付传商品的bug
//        if (getPreferentialPriceRequest.getOrderItems().size() == 1 &&
//                getPreferentialPriceRequest.getOrderItems().get(0).getUnitPrice().doubleValue() <= 0 &&
//                getPreferentialPriceRequest.getOrderItems().get(0).getQuantity().equals(0)) {
//            getPreferentialPriceResponse.setActualPrice(getPreferentialPriceRequest.getTotalPrice());
//            getPreferentialPriceResponse.setTotalPrice(getPreferentialPriceRequest.getTotalPrice());
//            return getPreferentialPriceResponse;
//        }
//
//        BigDecimal discount = new BigDecimal("1.00");
//        //会员卡号不是空 查询一下会员卡 算出折扣
//        if (!StringUtils.isEmpty(getPreferentialPriceRequest.getMemberCardNum())) {
//            DetailedMemberResponse detailedMemberResponse = remoteMemberService.getMemberByCondition(null,
//                    getPreferentialPriceRequest.getMemberCardNum(), null, null).getResult();
//            if (null == detailedMemberResponse) {
//                throw new BusinessCommonException(PromotionErrorCode.MEMBER_CARD_NOT_EXIST);
//            }
//            discount = detailedMemberResponse.getDiscount().divide(new BigDecimal("10"), 3, RoundingMode.UP);
//        }
//
//        BigDecimal totalPrice = new BigDecimal("0.00");
//        //有商品,累加商品金额作为总支付金额
//        //没有商品 读取传给的总支付金额
//        if (null != getPreferentialPriceRequest.getOrderItems()) {
//            for (GetPreferentialPriceRequest.OrderItem item : getPreferentialPriceRequest.getOrderItems()) {
//                totalPrice = totalPrice.add(item.getUnitPrice().multiply(item.getQuantity())).setScale(2, RoundingMode.UP);
//            }
//        } else {
//            totalPrice = getPreferentialPriceRequest.getTotalPrice();
//        }
//
//        getPreferentialPriceResponse.setActualPrice(totalPrice.multiply(discount).multiply(getPreferentialPriceRequest.getDiscount())
//                .setScale(2, RoundingMode.UP).subtract(getPreferentialPriceRequest.getFloorPrice()));
//        getPreferentialPriceResponse.setTotalPrice(totalPrice);
//        if (null != getPreferentialPriceRequest.getOrderItems()) {
//            getPreferentialPriceResponse.setOrderPreferentialItems(BeanUtil.parseList(getPreferentialPriceRequest.getOrderItems(),
//                    GetPreferentialPriceResponse.OrderPreferentialItem.class));
//            BigDecimal finalDiscount = discount;
//            getPreferentialPriceResponse.getOrderPreferentialItems().forEach(item ->
//                    item.setPreferentialUnitPrice(item.getUnitPrice().multiply(finalDiscount).setScale(2, RoundingMode.UP)));
//        }
//        return getPreferentialPriceResponse;
//    }
}
