package com.gree.mall.miniapp.logic.acitivy;

import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.gree.mall.miniapp.bean.PayDetail;
import com.gree.mall.miniapp.bean.order.OrderBuyBean;
import com.gree.mall.miniapp.bean.order.OrderDetailBean;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.enums.OrderStatusEnum;
import com.gree.mall.miniapp.enums.UserTypeEnum;
import com.gree.mall.miniapp.exception.RemoteServiceException;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.logic.common.SMSLogic;
import com.gree.mall.miniapp.logic.order.OrderLogic;
import com.gree.mall.miniapp.plus.entity.OrderDetail;
import com.gree.mall.miniapp.plus.entity.PromotionApply;
import com.gree.mall.miniapp.plus.entity.User;
import com.gree.mall.miniapp.plus.service.OrderDetailService;
import com.gree.mall.miniapp.plus.service.OrderInfoService;
import com.gree.mall.miniapp.plus.service.PromotionApplyService;
import com.gree.mall.miniapp.plus.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

@Service
public class PromotionApplyLogic {

    @Autowired
    PromotionApplyService promotionApplyService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    UserService userService;
    @Autowired
    OrderLogic orderLogic;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    SMSLogic smsLogic;


    //胡总电话 18928659988 ，审核人
    //private final String EXAMINE_MOBILE = "18928659988";

    /**
     * 优惠价格申请
     */
    @Transactional
    public void apply(OrderBuyBean orderBuyBean, HttpServletRequest request) throws Exception {
        //最大比例上限
        final BigDecimal maxRate = BigDecimal.valueOf(0.4);

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
        if(!currentCompanyWechat.getUser().getType().equals(UserTypeEnum.SERVICE.toString())
                || !currentCompanyWechat.getUser().getInnerr()){
            throw new RemoteServiceException("非内部分销员不可申请优惠金额");
        }
        String orderId = "";
        if(StringUtils.isNotBlank(orderBuyBean.getOrderId())) {
            orderId = orderBuyBean.getOrderId();
        }else{
            orderBuyBean.setWechatPay(false);
            PayDetail buy = orderLogic.buy(orderBuyBean, request);
            orderId = buy.getId();
        }

        OrderDetailBean detail = orderLogic.detail(orderId);
        if(StringUtils.isNotBlank(detail.getExchangeCode())){
            throw new RemoteServiceException("已使用优惠码不可申请优惠价格");
        }
        if(detail.getPayAmount().doubleValue() < orderBuyBean.getApplyAmount().doubleValue()){
            throw new RemoteServiceException("申请优惠金额不可大于待支付金额");
        }
        BigDecimal maxDiscount = detail.getPayAmount().multiply(maxRate);
        if(maxDiscount.doubleValue() < orderBuyBean.getApplyAmount().doubleValue()){
            throw new RemoteServiceException("申请减免金额异常");
        }
        if(detail.getPromotionApplyStatus() != 0 && detail.getPromotionApplyStatus() != 3){
            throw new RemoteServiceException("请勿重复申请优惠");
        }
        if(!detail.getOrderStatus().equals(OrderStatusEnum.NOPAY.toString())){
            throw new RemoteServiceException("非待支付状态不可申请");
        }
        //申请的优惠金额
        BigDecimal applyAmount = orderBuyBean.getApplyAmount();
        String applyRemark = orderBuyBean.getApplyRemark();

        detail.setPromotionApplyStatus(1);
        detail.setPromotionApplyAmount(applyAmount);
        detail.setPromotionApplyPayAmount(detail.getPayAmount().subtract(applyAmount));
        detail.setPromotionApplyRemark(applyRemark);

        //判断是否可以直接通过
        List<PromotionApply> list = promotionApplyService.lambdaQuery()
                .eq(PromotionApply::getUserId, currentCompanyWechat.getUserId())
                .eq(PromotionApply::getStatus,true)
                .orderByAsc(PromotionApply::getRate)
                .list();
        if(CollectionUtils.isNotEmpty(list)){
            PromotionApply promotionApply = list.get(0);
            BigDecimal rate = promotionApply.getRate();
            BigDecimal payAmount = detail.getPayAmount();
            BigDecimal newDiscountPayAmount = payAmount.multiply(BigDecimal.valueOf(1).subtract(rate));
            //业务员优惠折扣的金额大于等于申请优惠金额，就直接申请通过
            if(newDiscountPayAmount.doubleValue() >= applyAmount.doubleValue()){
                detail.setPromotionApplyStatus(4);
                detail.setPromotionApplyAmount(applyAmount);
                detail.setPromotionApplyPayAmount(detail.getPayAmount().subtract(applyAmount));
                detail.setPayAmount(detail.getPromotionApplyPayAmount());
            }
        }
        detail.updateById();

        //短信通知
        if(detail.getPromotionApplyStatus() == 1){
            List<User> users = userService.lambdaQuery().eq(User::getPromotionApplyExamineby, true).list();
            for(User user:users) {
                smsLogic.sendDiscountNotice(user.getMobile(),detail.getOrderId(),detail.getPayAmount(),
                        detail.getPromotionApplyAmount(),detail.getWorkerName(),detail.getReceUserName());
            }
        }
    }

    @Transactional
    public void examine(String orderId,Boolean examineReuslt,String promotionApplyRejectRemark,HttpServletRequest request){
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
        if(!currentCompanyWechat.getUser().getPromotionApplyExamineby()){
            throw new RemoteServiceException("暂无权限审核,请联系相关人员");
        }
        OrderDetailBean detail = orderLogic.detail(orderId);

        if(!detail.getOrderStatus().equals(OrderStatusEnum.NOPAY.toString())){
            throw new RemoteServiceException("非待支付订单，无需审核");
        }
        if(detail.getPromotionApplyStatus() != 1){
            throw new RemoteServiceException("非待审核状态，不可审核");
        }

        detail.setPromotionApplyStatus(examineReuslt ? 2 : 3);
        detail.setPromotionApplyRejectRemark(promotionApplyRejectRemark);
        if(examineReuslt){
            detail.setPayAmount(detail.getPromotionApplyPayAmount());
            //将订单佣金全部变成0
            detail.setTotalShareAmount(BigDecimal.valueOf(0));
            orderDetailService.lambdaUpdate()
                    .set(OrderDetail::getShareAmount,0)
                    .eq(OrderDetail::getOrderId,detail.getOrderId())
                    .update();
        }
        detail.updateById();

    }

}
