package com.bohuikeji.delivery.backstage.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bohuikeji.delivery.backstage.constants.discountConst;
import com.bohuikeji.delivery.backstage.entity.TCustomer;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountMall;
import com.bohuikeji.delivery.backstage.entity.discount.TDiscountRecord;
import com.bohuikeji.delivery.backstage.mapper.TDiscountRecordMapper;
import com.bohuikeji.delivery.backstage.service.*;
import com.bohuikeji.frame.module.admin.entity.TFranchiseeInformation;
import com.bohuikeji.frame.module.admin.service.ITFranchiseeInformationService;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 发放代金券 服务实现类
 * </p>
 *
 * @author zhouliwu
 * @since 2021-03-29
 */
@Service
@Slf4j
public class TDiscountRecordServiceImpl extends ServiceImpl<TDiscountRecordMapper, TDiscountRecord> implements ITDiscountRecordService {
        @Autowired
        ITOrderService orderService;
        @Autowired
        ITDiscountRecordService discountRecordService;
        @Autowired
        ITCustomerService customerService;
        @Autowired
        ITDiscountMallService discountMallService;
        @Autowired
        ITDiscountOrderService discountOrderService;
        @Autowired
        ITFranchiseeInformationService franService;

        /**
         * 客户领取优惠券新增记录
         * @param discountMall
         * @param tCustomer
         * @return
         */
        @Override
        public boolean saveRecord(TDiscountMall discountMall, TCustomer tCustomer) {
        TDiscountRecord discountRecord = new TDiscountRecord();
        discountRecord.setDisId(discountMall.getDisId());
        discountRecord.setBeginDate(discountMall.getBeginDate());
        discountRecord.setEndDate(discountMall.getEndDate());
        discountRecord.setDisRemark(discountMall.getDisRemark());
        discountRecord.setUseExplain(discountMall.getUseExplain());
        discountRecord.setStartAmount(discountMall.getStartAmount());
        discountRecord.setCustomerId(tCustomer.getCustomerId());
        discountRecord.setDisValue(discountMall.getDisValue());
        discountRecord.setCollectionTime(LocalDateTime.now());
        discountRecord.setDisType(discountMall.getDisType());
        discountRecord.setReceiveMethod(discountMall.getReceiveMethod());
        discountRecord.setGrantType(discountMall.getGrantType());
        discountRecord.setConsType(discountMall.getConsType());
        discountRecord.setUrlPicture(discountMall.getUrlPicture());
        discountRecord.setUsageStatus("未使用");
        return save(discountRecord);
        }

        /**
         * 客户下单后整体优惠金额（会员+优惠卷）
         * @param order
         * @return
         */
        @Override
        public TOrder getDisOrder(TOrder order) {
            if(StringUtils.isNotBlank(order.getOrderFlag()) && "特惠".equals(order.getOrderFlag())){
                return order;
            }
            log.info("分享订单标识：{}",order.getShareId());
            BigDecimal prefAmount;//优惠的金额
            BigDecimal MemberDisAmount;//会员优惠金额
            BigDecimal ordDisAmount=new BigDecimal("0.00").setScale(2, BigDecimal.ROUND_DOWN);//普通优惠的金额
            TCustomer customer=customerService.getById(order.getPlayerId());

            TFranchiseeInformation franchiseeInformation = franService.getOne(new QueryWrapper<TFranchiseeInformation>().eq("fran_id",order.getFranId()));
            //未绑定直接返回计费
            if("平台".equals(franchiseeInformation.getFranController())){
                if(StringUtils.isNotBlank(customer.getTemplateId()) || "商家用户".equals(customer.getCustomerType())){
                    return order;
                }
            }
            if(customer.getOrderFrequency()<1 && !"商家用户".equals(customer.getCustomerType())){
                BigDecimal firstOrderPer = new BigDecimal("2.0");
                order.setPrefAmount(firstOrderPer.add(order.getPrefAmount()));//优惠卷金额
                order.setOrderExpectPrice(order.getOrderExpectPrice().subtract(firstOrderPer).setScale(2, RoundingMode.HALF_UP));
                log.error("新用户首单优惠:订单：{}，优惠金额：{}，预估金额：{}",order.getOrderNum(),firstOrderPer,order.getOrderExpectPrice());
                order.setPreName("首单优惠");
                return order;
            }
            if(order.getDisId() !=0){//当补充支付是重新计费不需要再走优惠业务，直接返回原定就可以
                return order;
            }
            TDiscountRecord tDiscountRecord = discountRecordService.getOne(new QueryWrapper<TDiscountRecord>().eq("customer_id",order.getPlayerId()).eq("dis_type","会员卡").eq("usage_status","使用中"));
            if(tDiscountRecord == null){//客户开通会员卡的优惠金额
                MemberDisAmount = new BigDecimal("0.00").setScale(2,RoundingMode.HALF_UP);
                if(order.getReleaseId()!=0){//客户下单选择普通优惠卷的优惠金额
                    TDiscountRecord discountRecord = discountRecordService.getOne(new QueryWrapper<TDiscountRecord>().eq("usage_status","未使用").eq("release_id",order.getReleaseId()).eq("customer_id",order.getPlayerId()));
                    if(order.getOrderExpectPrice().compareTo(discountRecord.getStartAmount()) < 0){//订单金额小于起始金额时不可使用优惠卷，默认为”0.00“元
                        ordDisAmount = new BigDecimal("0.00");
                    }else {
                        ordDisAmount = discountConst.getDisPrice(order,discountRecord);
                    }
                }else {
                    ordDisAmount = new BigDecimal("0.00");
                }
            }else {
                if("商家用户".equals(customer.getCustomerType())){
                    order.setPreName("商家优惠：8.3 折");
                }
                order.setReleaseId(0);
                order.setMemberDisId(tDiscountRecord.getReleaseId());
                MemberDisAmount = discountConst.getDisPrice(order,tDiscountRecord);
            }
            prefAmount = MemberDisAmount.add(ordDisAmount);//总共优惠的金额
            //客户开通会员后订单优惠的价格：客户下单后整体优惠金额（会员+优惠卷）
            if("加盟商".equals(franchiseeInformation.getFranController())){
                order.setPrefAmount(prefAmount);//优惠卷金额
            }else {
                order.setPrefAmount(prefAmount.add(order.getPrefAmount()));//优惠卷金额
            }
            //计算处理有惠券的金额：预估金额 - 优惠金额（可能为0/可能不为0）= 实际需要支付的金额
            order.setOrderExpectPrice(order.getOrderExpectPrice().subtract(order.getPrefAmount()).setScale(2, RoundingMode.HALF_UP));
            //log.info("计算优惠后的的金额：优惠金额：{}，预估金额：{}",prefAmount,order.getOrderExpectPrice());
            return order;
        }

        /**
         * 优惠券使用后修改优惠信息
         * @param order
         * @return
         */
        @Override
        public boolean updateRecord(TOrder order) {
            if(order.getReleaseId()!=0){//普通优惠卷使用
                TDiscountRecord discountRecord = discountRecordService.getOne(new QueryWrapper<TDiscountRecord>().eq("usage_status","未使用").eq("release_id",order.getReleaseId()).eq("customer_id",order.getPlayerId()));
                discountOrderService.saveDiscount(order,discountRecord);
                discountRecord.setUsageStatus("已使用");
                discountRecord.setUsageTime(LocalDateTime.now());
                discountRecordService.updateById(discountRecord);
            }
            if(order.getMemberDisId()!=0){//会员用户记录使用默认卷（会员自带的折扣）
                TDiscountRecord discountRecord = discountRecordService.getOne(new QueryWrapper<TDiscountRecord>().eq("usage_status","使用中").eq("dis_type","会员卡").eq("release_id",order.getMemberDisId()).eq("customer_id",order.getPlayerId()));
                discountOrderService.saveDiscount(order,discountRecord);
            }
            return true;
        }

    /**
     * 将已过期数据更改状态
     * @param customerId
     * @return
     */
    @Override
    public boolean updateOverdue(Integer customerId){
        List<TDiscountRecord> discountRecords = discountRecordService.list(new QueryWrapper<TDiscountRecord>().eq("customer_id",customerId).in("usage_status","未使用","使用中"));
        for(TDiscountRecord discountRecord : discountRecords){
            if(LocalDate.now().isAfter(discountRecord.getEndDate())){
                discountRecordService.updateById(discountRecord.setUsageStatus("已过期"));
            }
        }
        return true;
    }

    /**
     * 判断用户是否为会员用户
     * @param customerId
     * @return
     */
    @Override
    public boolean getWhetherMember(Integer customerId) {
        TDiscountRecord discountRecord = discountRecordService.getOne(new QueryWrapper<TDiscountRecord>().last("WHERE customer_id="+customerId+" AND usage_status=\"使用中\" AND dis_type=\"会员卡\""));
        if(discountRecord != null && "会员卡".equals(discountRecord.getDisType())){
            return true;
        }
        return false;
    }

}
