package cn.pluss.platform.realFans.impl;

import cn.pluss.platform.entity.*;
import cn.pluss.platform.fans.FansService;
import cn.pluss.platform.mapper.*;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.merchantProfit.MerchantProfitService;
import cn.pluss.platform.notice.NoticeService;
import cn.pluss.platform.realFans.RealFansService;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userIntegral.UserIntegralService;
import cn.pluss.platform.util.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@RequiredArgsConstructor
@Slf4j
@Service
public class RealFansServiceImpl extends ServiceImpl<RealFansMapper, RealFans> implements RealFansService {

    private final FansService fansService;
    private final MerchantBaseInfoMapper merchantBaseInfoMapper;
    private final UserAppService userAppService;
    private final NoticeService noticeService;
    private final MerchantOrderService merchantOrderService;
    private final MerchantProfitService merchantProfitService;
    private final UserIntegralService userIntegralService;

    @Autowired
    private GeneralPushUtil generalPushUtil;

    @Override
    public void removeProfit(String orderNumber) {
        log.info("去除分润开始,订单编号：{}<==========================",orderNumber);
        //TODO 去除推广分润
        QueryWrapper<MerchantProfit> queryWrapper = new QueryWrapper<MerchantProfit>();
        queryWrapper.eq("orderNumber",orderNumber);
        merchantProfitService.remove(queryWrapper);
        //TODO 去除粉丝分润
        Fans fans = new Fans();
        fans.setOrderNumber(orderNumber);
        List<Fans> fansList = fansService.queryFansList(fans);
        if(!fansList.isEmpty()){
            Fans fansInfo = fansList.get(0);
            fansInfo.setShareMoney("0.00");
            fansService.updateFans(fansInfo);
        }
        UpdateWrapper<MerchantOrder> updateWrapper = new UpdateWrapper<MerchantOrder>()
                .set("fansShareMoney",0)
                .set("profitShareMoney",0)
                .eq("orderNumber",orderNumber);
        merchantOrderService.update(updateWrapper);
        //删除积分
        QueryWrapper<UserIntegral> integralWrapper = new QueryWrapper<UserIntegral>();
        integralWrapper.eq("orderNumber",orderNumber);
        userIntegralService.remove(integralWrapper);
        log.info("======================>去除分润分润结束<==========================");
    }

    @Override
    public void removeProfit(MerchantOrder order, BigDecimal refundAmt,BigDecimal useRefundAmt) {
        BigDecimal consumeFee = BigDecimal.valueOf(order.getConsumeFee());
        if(refundAmt.compareTo(consumeFee) == 0){
            removeProfit(order.getOrderNumber());
        }else{
            QueryWrapper<MerchantProfit> queryWrapper = new QueryWrapper<MerchantProfit>();
            queryWrapper.eq("orderNumber",order.getOrderNumber());
            merchantProfitService.remove(queryWrapper);
            BigDecimal fee = consumeFee.subtract(refundAmt).subtract(useRefundAmt);
            order.setConsumeFee(fee.doubleValue());
            merchantProfitService.createOrderProfitV2(order,"1");
        }
    }

    @Override
    public Page<RealFans> pageData(Page<RealFans> page, RealFans realFans) {
        return baseMapper.pageData(page,realFans);
    }

    /**
     * @description:创建粉丝分润
     * @date: 2021/8/19 17:24
     * @param order:
     */
    @Override
    public void createFansProfit(MerchantOrder order) {
        log.info("【粉丝分润计算】创建粉丝分润开始，待创建粉丝分润的订单号为:{},订单类型为：{}",order.getOrderNumber(),order.getOrderType());
        if(StringUtil.isNotEmpty(order.getMercUserId())){
            if("2".equals(order.getOrderType()) || "7".equals(order.getOrderType()) || "9".equals(order.getOrderType()) || "10".equals(order.getOrderType())){
                //插入粉丝和消费记录
                insertRealFansAndFans(order);
            }
            log.info("【粉丝分润计算】创建粉丝分润结束，订单号为:{}的订单分润创建成功！",order.getOrderNumber());
        }else{
            log.info("【粉丝分润计算】创建粉丝分润结束，订单号为:{}的订单mercUserId为空创建失败！",order.getOrderNumber());
        }
    }
    /**
     * @description:插入粉丝分润
     * @date: 2021/8/23 14:08
     * @param order:
     */
    private void insertRealFansAndFans(MerchantOrder order) {
        List<RealFans> realFansList = baseMapper.queryBySoleId(order.getMercUserId());
        if (realFansList.isEmpty()) {
            RealFans realFans = order.convertRealFans();
            baseMapper.insert(realFans);
            insertFans(order);
        }else{
            Fans f = fansService.getByLockOrderNumber(order.getOrderNumber());
            if(f == null){
                Fans lastFans = fansService.queryLastFansByUserId(order.getMercUserId());
                Fans fans = new Fans();
                fans.convert(order);
                if (lastFans!= null && StringUtil.isNotEmpty(lastFans.getConsumTime())
                        && DateUtils.differentDaysByHours(lastFans.getConsumTime(),DateUtils.currentDate()) < 24
                        && !order.getMerchantCode().equals(lastFans.getMerchantCode())) {
                    // 说明有上次的记录并且上次消费时间跟本次消费是在同一天 本次消费给上一次消费的商家分润
                    fans.setLastconsumTime(lastFans.getConsumTime());
                    if (StringUtil.isNotEmpty(lastFans.getMerchantCode())) {
                        fans.setLastMerchantCode(lastFans.getMerchantCode());
                    }
                    if (StringUtil.isNotEmpty(lastFans.getOrderNumber())) {
                        fans.setLastOrderNumber(lastFans.getOrderNumber());
                    }
                    String lastMerchantCode = fans.getLastMerchantCode();
                    MerchantBaseInfo merchantBaseInfo = merchantBaseInfoMapper.queryByMerchantCode(lastMerchantCode);
                    if (StringUtil.isNotEmpty(lastMerchantCode)) {
                        String userId = merchantBaseInfo.getUserId();// 当前商户的userId
                        UserApp userApp = new UserApp();
                        userApp.setUserId(Long.parseLong(userId));
                        if (StringUtil.isNotEmpty(userId)) {
                            userApp = userAppService.queryUserApp(userApp);// 当前商户的信息
                            if (Double.parseDouble(fans.getShareMoney()) >= 0.0001d ) {
                                List<String> alias = new ArrayList<String>();
                                alias.add(userApp.getUserId() + "");
                                try {
                                    String notificationContent = "本次分润金额：" + fans.getShareMoney() + "元";
                                    generalPushUtil.sendAllPlatByAlias(alias, "粉丝分润通知", notificationContent, "0");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                Notice notice = new Notice(0, 6, userApp);
                                notice.setConrtent("您有一笔" + fans.getShareMoney() + "元的粉丝分润");
                                notice.setUniqueKey(order.getMercUserId() + order.getOrderNumber() + "fansProft");
                                noticeService.saveNotice(notice);
                            }
                        }
                    }
                }else{
                    fans.setShareMoney("0");
                }
                order.setFansShareMoney(Double.parseDouble(fans.getShareMoney()));
                fansService.saveFans(fans);
            }
        }
    }

    private void insertFans(MerchantOrder order) {
        Fans fans = new Fans();
        fans.setShareMoney("0");
        fans.convert(order);
        fansService.saveFans(fans);
    }
}
