package cn.iocoder.yudao.module.member.service.amount;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.member.controller.admin.business.vo.StatisticsVo;
import cn.iocoder.yudao.module.member.controller.app.user.vo.AppUserInfoCardVO;
import cn.iocoder.yudao.module.member.dal.dataobject.card.CardDO;
import cn.iocoder.yudao.module.member.dal.dataobject.order.DishOrderDO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.enums.CostTypeEnum;
import cn.iocoder.yudao.module.member.enums.TimePeriodEnum;
import cn.iocoder.yudao.module.member.service.business.BusinessService;
import cn.iocoder.yudao.module.member.service.card.CardService;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import com.sun.istack.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.CASH_AMOUNT_NOT_ENOUGH;
import static cn.iocoder.yudao.module.member.service.amount.LockManager.getUserLock;


/**
 * 餐盘统一扣款 Service 实现类
 *
 * @author 开发账号
 */

@Service
@Slf4j
public class DeductionServiceImpl implements DeductionService {

    @Resource
    private StringRedisTemplate deductionRedisTemplate;
    @Resource
    private CardService cardService;
    @Resource
    private MemberUserService userService;
    @Resource
    private BusinessService businessService;

    private static final List<String> CHECK_LIST = Arrays.asList(CostTypeEnum.SHOPPING.getCode());

    @Override
    public void deduction(DishOrderDO dishOrderDO) {
        Long userId = dishOrderDO.getUserId();

        BigDecimal newMoney;
        BigDecimal changeMoney;
        BigDecimal wxNewMoney;
        BigDecimal giftNewMoney;
        BigDecimal cashNewMoney;

        String name;

        synchronized (getUserLock(userId)) {
            MemberUserDO user = userService.getUser(userId);

            //新的总价
            String s = deductionRedisTemplate.opsForValue().get(dishOrderDO.getDiningPlatesNum() + "-" + dishOrderDO.getStoreId());
            BigDecimal total = new BigDecimal(StrUtil.isBlank(s) ? "0" : s);
            //现有金额
            BigDecimal money = user.getMoney();
            //计算减免价格
            BigDecimal reductionAmount = BigDecimal.ZERO;
            if (total.compareTo(BigDecimal.ZERO) > 0) {
                reductionAmount = userService.getReductionAmount(userId, total, dishOrderDO.getCreateTime());
            }
            if (dishOrderDO.getReductionAmount().compareTo(BigDecimal.ZERO) > 0) {
                reductionAmount = reductionAmount.add(dishOrderDO.getReductionAmount());
                dishOrderDO.setReductionAmount(reductionAmount);
            } else {
                dishOrderDO.setReductionAmount(reductionAmount);
            }
            dishOrderDO.setReductionState(reductionAmount.compareTo(BigDecimal.ZERO) > 0 ? "1" : "0");
            //计算减免后的总价
            if (total.compareTo(reductionAmount) < 0) {
                total = BigDecimal.ZERO;
            } else {
                total = total.subtract(reductionAmount);
            }

            BigDecimal wxAmount = user.getWxAmount();
            BigDecimal giftAmount = user.getGiftAmount();
            BigDecimal cashAmount = user.getCashAmount();

            user.setMoney(money.subtract(total));

            //待支付金额 最大退款金额
            dishOrderDO.setRefundAmount(total);
            if (money.compareTo(BigDecimal.ZERO) <= 0) {
                dishOrderDO.setPayAmount(total);
                dishOrderDO.setRefundAmount(BigDecimal.ZERO);
            } else {
                if (total.compareTo(money) > 0) {
                    dishOrderDO.setPayAmount(total.subtract(money));
                    dishOrderDO.setRefundAmount(money);
                }
            }

            if (total.compareTo(money) > 0) {
                dishOrderDO.setOrderStatus(DishOrderDO.TOCOMPLETE);
                dishOrderDO.setWxAmount(wxAmount);
                dishOrderDO.setCashAmount(cashAmount);
                dishOrderDO.setGiftAmount(giftAmount);

                user.setWxAmount(BigDecimal.ZERO);
                user.setCashAmount(BigDecimal.ZERO);
                user.setGiftAmount(BigDecimal.ZERO);
            } else {
                dishOrderDO.setOrderStatus(DishOrderDO.COMPLETE);
                //计算金额
                if (total.compareTo(cashAmount) <= 0) {
                    user.setCashAmount(cashAmount.subtract(total));
                    dishOrderDO.setCashAmount(total);
                } else {
                    user.setCashAmount(BigDecimal.ZERO);
                    dishOrderDO.setCashAmount(cashAmount);
                    BigDecimal total1 = total.subtract(cashAmount);
                    if (total1.compareTo(giftAmount) <= 0) {
                        user.setGiftAmount(giftAmount.subtract(total1));
                        dishOrderDO.setGiftAmount(total1);
                    } else {
                        user.setGiftAmount(BigDecimal.ZERO);
                        dishOrderDO.setGiftAmount(giftAmount);
                        BigDecimal total2 = total1.subtract(giftAmount);

                        user.setWxAmount(wxAmount.subtract(total2));
                        dishOrderDO.setWxAmount(total2);
                    }
                }
            }

            userService.updateById(user);
            newMoney = user.getMoney();
            wxNewMoney = user.getWxAmount();
            giftNewMoney = user.getGiftAmount();
            cashNewMoney = user.getCashAmount();
            changeMoney = total;
            name = user.getNickname();
        }


        //记录消费记录
        CardDO cardDO = new CardDO();
        cardDO.setType(TimePeriodEnum.getTimePeriod(dishOrderDO.getCreateTime()));
        cardDO.setUserId(userId);
        cardDO.setChangeMoney(changeMoney);
        cardDO.setFlag(CardDO.MINUS);
        cardDO.setMoney(newMoney);
        cardDO.setCashAmount(cashNewMoney);
        cardDO.setWxAmount(wxNewMoney);
        cardDO.setGiftAmount(giftNewMoney);

        cardService.insertOne(cardDO);

        dishOrderDO.setTotalMoney(changeMoney);
        dishOrderDO.setUpdateTime(LocalDateTime.now());
        deductionRedisTemplate.delete(dishOrderDO.getDiningPlatesNum() + "-" + dishOrderDO.getStoreId());

        //更新营业数据
        if (dishOrderDO.getOrderStatus().equals(DishOrderDO.COMPLETE)) {
            StatisticsVo statisticsVo = new StatisticsVo();
            statisticsVo.setCarteenId(dishOrderDO.getStoreId());
            statisticsVo.setTotalMoney(dishOrderDO.getTotalMoney());
            statisticsVo.setOrderSum(1);
            statisticsVo.setReduceMoney(dishOrderDO.getReductionAmount());
            statisticsVo.setTime(dishOrderDO.getCreateTime());
            statisticsVo.setOrderId(dishOrderDO.getId());
            businessService.updateStatistics(statisticsVo);
        }

        //更新redis
        updateRedis(userId,name,newMoney);
    }


    @Override
    public void cashDraw(Long userId, BigDecimal money, String type) {

        BigDecimal newMoney;
        BigDecimal wxNewMoney;
        BigDecimal giftNewMoney;
        BigDecimal cashNewMoney;
        String name;

        synchronized (getUserLock(userId)) {
            MemberUserDO user = userService.getUser(userId);
            if (ObjectUtil.isEmpty(user) || user.getCashAmount().compareTo(BigDecimal.ZERO) < 1
                    || money.compareTo(user.getCashAmount()) > 0) {
                throw exception(CASH_AMOUNT_NOT_ENOUGH);
            }
            user.setMoney(user.getMoney().subtract(money));
            user.setCashAmount(user.getCashAmount().subtract(money));
            userService.updateById(user);
            newMoney = user.getMoney();
            wxNewMoney = user.getWxAmount();
            giftNewMoney = user.getGiftAmount();
            cashNewMoney = user.getCashAmount();
            name = user.getNickname();
        }

        CardDO cardDO = new CardDO();
        cardDO.setUserId(userId);
        cardDO.setFlag(CardDO.MINUS);
        cardDO.setChangeMoney(money);
        cardDO.setType(type);
        cardDO.setWxAmount(wxNewMoney);
        cardDO.setGiftAmount(giftNewMoney);
        cardDO.setMoney(newMoney);
        cardDO.setCashAmount(cashNewMoney);
        cardService.insertOne(cardDO);

        //更新redis
        updateRedis(userId,name,newMoney);
    }


    @Override
    public void wxDraw(Integer amount, Long userId) {
        BigDecimal newMoney;
        BigDecimal wxNewMoney;
        BigDecimal giftNewMoney;
        BigDecimal cashNewMoney;
        String name;
        BigDecimal changeMoney = new BigDecimal(amount).divide(new BigDecimal("100"));

        synchronized (getUserLock(userId)) {
            MemberUserDO user = userService.getUser(userId);
            user.setWxAmount(user.getWxAmount().subtract(changeMoney));
            user.setMoney(user.getMoney().subtract(changeMoney));
            userService.updateById(user);
            newMoney = user.getMoney();
            wxNewMoney = user.getWxAmount();
            giftNewMoney = user.getGiftAmount();
            cashNewMoney = user.getCashAmount();
            name = user.getNickname();
        }


        //获取最新余额
        CardDO cardDO = new CardDO();
        cardDO.setUserId(userId);
        cardDO.setFlag(CardDO.MINUS);
        cardDO.setChangeMoney(changeMoney);
        cardDO.setType("7");

        cardDO.setWxAmount(wxNewMoney);
        cardDO.setGiftAmount(giftNewMoney);
        cardDO.setMoney(newMoney);
        cardDO.setCashAmount(cashNewMoney);
        cardService.insertOne(cardDO);


        //更新redis
        updateRedis(userId,name,newMoney);
    }

    @Override
    public void refund(Long userId, BigDecimal money, DishOrderDO dishOrderDO) {
        //获取最新余额
        BigDecimal newMoney2;
        BigDecimal wxNewMoney;
        BigDecimal giftNewMoney;
        BigDecimal cashNewMoney;
        String name;

        synchronized (getUserLock(userId)) {
            MemberUserDO user = userService.getUser(userId);
            BigDecimal oldMoney = user.getMoney();

            user.setMoney(oldMoney.add(money));

            BigDecimal wxAmount = user.getWxAmount();
            BigDecimal cashAmount = user.getCashAmount();
            BigDecimal giftAmount = user.getGiftAmount();

            BigDecimal dishWxAmount = dishOrderDO.getWxAmount();
            BigDecimal dishCashAmount = dishOrderDO.getCashAmount();
            BigDecimal dishGiftAmount = dishOrderDO.getGiftAmount();

            BigDecimal newMoney = money;
            if (oldMoney.compareTo(BigDecimal.ZERO) < 0) {
                newMoney = user.getMoney();
            }


            if (user.getMoney().compareTo(BigDecimal.ZERO) <= 0) {
                user.setWxAmount(BigDecimal.ZERO);
                user.setGiftAmount(BigDecimal.ZERO);
                user.setCashAmount(BigDecimal.ZERO);
            } else {
                if (newMoney.compareTo(dishGiftAmount) <= 0) {
                    user.setGiftAmount(giftAmount.add(newMoney));
                } else {
                    user.setGiftAmount(giftAmount.add(dishGiftAmount));
                    BigDecimal money1 = newMoney.subtract(dishGiftAmount);

                    if (money1.compareTo(dishCashAmount) <= 0) {
                        user.setCashAmount(cashAmount.add(money1));
                    } else {
                        user.setCashAmount(cashAmount.add(dishCashAmount));
                        BigDecimal money2 = money1.subtract(dishCashAmount);
                        if (money2.compareTo(dishWxAmount) <= 0) {
                            user.setWxAmount(wxAmount.add(money2));
                        } else {
                            user.setWxAmount(wxAmount.add(dishWxAmount));
                        }

                    }
                }
            }
            userService.updateById(user);
            newMoney2 = user.getMoney();
            wxNewMoney = user.getWxAmount();
            giftNewMoney = user.getGiftAmount();
            cashNewMoney = user.getCashAmount();
            name = user.getNickname();
        }

        CardDO cardDO = new CardDO();
        cardDO.setUserId(userId);
        cardDO.setFlag(CardDO.ADD);
        cardDO.setChangeMoney(money);
        cardDO.setType(CostTypeEnum.REFUND.getCode());
        cardDO.setWxAmount(wxNewMoney);
        cardDO.setGiftAmount(giftNewMoney);
        cardDO.setMoney(newMoney2);
        cardDO.setCashAmount(cashNewMoney);

        cardService.insertOne(cardDO);

        //更新redis
        updateRedis(userId,name,newMoney2);
    }

    @Override
    public void reduction(Long userId, BigDecimal money, BigDecimal giftAmount, BigDecimal cashAmount, BigDecimal wxAmount) {

        BigDecimal newMoney;
        BigDecimal giftNewAmount;
        BigDecimal cashNewAmount;
        BigDecimal wxNewAmount;
        String name;

        synchronized (getUserLock(userId)) {
            MemberUserDO user = userService.getUser(userId);
            user.setMoney(user.getMoney().add(money));
            user.setCashAmount(user.getCashAmount().add(cashAmount));
            user.setGiftAmount(user.getGiftAmount().add(giftAmount));
            user.setWxAmount(user.getWxAmount().add(wxAmount));
            userService.updateById(user);

            newMoney = user.getMoney();
            wxNewAmount = user.getWxAmount();
            giftNewAmount = user.getGiftAmount();
            cashNewAmount = user.getCashAmount();
            name = user.getNickname();
        }
        CardDO cardDO = new CardDO();
        cardDO.setUserId(userId);
        cardDO.setFlag(CardDO.ADD);
        cardDO.setChangeMoney(money);
        cardDO.setType(CostTypeEnum.REFUND.getCode());
        cardDO.setMoney(newMoney);
        cardDO.setWxAmount(wxNewAmount);
        cardDO.setCashAmount(cashNewAmount);
        cardDO.setGiftAmount(giftNewAmount);
        cardService.insertOne(cardDO);

        //更新redis
        updateRedis(userId,name,newMoney);
    }

    @Override
    public BigDecimal storeDeduction(BigDecimal total, @NotNull Long userId) {

        BigDecimal newMoney;
        BigDecimal wxNewMoney;
        BigDecimal giftNewMoney;
        BigDecimal cashNewMoney;
        String name;
        synchronized (getUserLock(userId)) {
            MemberUserDO user = userService.getUser(userId);
            BigDecimal money = user.getMoney();
            if (total.compareTo(money) > 0){
                return money.subtract(total);
            }
            BigDecimal wxAmount = user.getWxAmount();
            BigDecimal giftAmount = user.getGiftAmount();
            BigDecimal cashAmount = user.getCashAmount();
            user.setMoney(money.subtract(total));

            //计算金额
            if (total.compareTo(cashAmount) <= 0) {
                user.setCashAmount(cashAmount.subtract(total));
            } else {
                user.setCashAmount(BigDecimal.ZERO);
                BigDecimal total1 = total.subtract(cashAmount);
                if (total1.compareTo(giftAmount) <= 0) {
                    user.setGiftAmount(giftAmount.subtract(total1));
                } else {
                    user.setGiftAmount(BigDecimal.ZERO);
                    BigDecimal total2 = total1.subtract(giftAmount);
                    user.setWxAmount(wxAmount.subtract(total2));
                }
            }
            userService.updateById(user);
            newMoney = user.getMoney();
            wxNewMoney = user.getWxAmount();
            giftNewMoney = user.getGiftAmount();
            cashNewMoney = user.getCashAmount();
            name = user.getNickname();
        }

        CardDO cardDO = new CardDO();
        cardDO.setUserId(userId);
        cardDO.setChangeMoney(total);
        cardDO.setFlag(CardDO.MINUS);
        cardDO.setMoney(newMoney);
        cardDO.setWxAmount(wxNewMoney);
        cardDO.setCashAmount(cashNewMoney);
        cardDO.setGiftAmount(giftNewMoney);
        cardService.insertOne(cardDO);


        //更新redis
        updateRedis(userId,name,newMoney);

        return cardDO.getMoney();
    }


    public void updateRedis(Long userId,String name, BigDecimal newMoney) {
        //更新缓存
        String redisKey = "USER_" + userId;
        AppUserInfoCardVO appUserInfoCardVO = new AppUserInfoCardVO();
        appUserInfoCardVO.setName(name);
        appUserInfoCardVO.setMoney(newMoney);
        deductionRedisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(appUserInfoCardVO));
    }

    @Override
    public void deduct(Long userId, BigDecimal money, String type) {
        BigDecimal newMoney;
        BigDecimal wxNewMoney;
        BigDecimal giftNewMoney;
        BigDecimal cashNewMoney;
        String name;

        synchronized (getUserLock(userId)) {
            MemberUserDO user = userService.getUser(userId);

            if (user.getMoney().compareTo(money) < 0) {
                if (CHECK_LIST.contains(type)) {
                    throw exception(CASH_AMOUNT_NOT_ENOUGH);
                }
                user.setWxAmount(BigDecimal.ZERO);
                user.setCashAmount(BigDecimal.ZERO);
                user.setGiftAmount(BigDecimal.ZERO);
            }else {
                BigDecimal wxAmount = user.getWxAmount();
                BigDecimal giftAmount = user.getGiftAmount();
                BigDecimal cashAmount = user.getCashAmount();
                //计算金额
                if (money.compareTo(cashAmount) <= 0) {
                    user.setCashAmount(cashAmount.subtract(money));
                } else {
                    user.setCashAmount(BigDecimal.ZERO);
                    BigDecimal total1 = money.subtract(cashAmount);
                    if (total1.compareTo(giftAmount) <= 0) {
                        user.setGiftAmount(giftAmount.subtract(total1));
                    } else {
                        user.setGiftAmount(BigDecimal.ZERO);
                        BigDecimal total2 = total1.subtract(giftAmount);
                        user.setWxAmount(wxAmount.subtract(total2));
                    }
                }
            }

            user.setMoney(user.getMoney().subtract(money));
            userService.updateById(user);
            newMoney = user.getMoney();
            wxNewMoney = user.getWxAmount();
            giftNewMoney = user.getGiftAmount();
            cashNewMoney = user.getCashAmount();
            name = user.getNickname();
        }

        CardDO cardDO = new CardDO();
        cardDO.setUserId(userId);
        cardDO.setFlag(CardDO.MINUS);
        cardDO.setChangeMoney(money);
        cardDO.setType(type);
        cardDO.setWxAmount(wxNewMoney);
        cardDO.setGiftAmount(giftNewMoney);
        cardDO.setMoney(newMoney);
        cardDO.setCashAmount(cashNewMoney);
        cardService.insertOne(cardDO);

        //更新redis
        updateRedis(userId,name,newMoney);
    }
}

