package com.ruoyi.app.order;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.app.service.WalletService;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.PosOrderPromotionMapper;
import com.ruoyi.system.service.IInfoUserService;
import com.ruoyi.system.service.IPosStoreService;
import com.ruoyi.system.service.IUserBillingService;
import com.ruoyi.system.service.IVipUserQuanyiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;

/**
 * 订单账单生成服务（商家分成、骑手分成）
 */
@Service
public class OrderService {

    @Autowired
    private IUserBillingService userBillingService;
    @Autowired
    private IPosStoreService posStoreService;
    @Autowired
    private IInfoUserService infoUserService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private IVipUserQuanyiService userQuanyiService;

    /**
     * 执行商户分成
     */
    public void setSanghuBilling(PosOrder posOrder) {
        long count = userBillingService.count(new LambdaQueryWrapper<UserBilling>()
                .eq(UserBilling::getUserId, posOrder.getShId())
                .eq(UserBilling::getType, "0")
                .eq(UserBilling::getDdId, posOrder.getDdId()));
        if (count <= 0) {
            UserBilling billing = new UserBilling();
            DecimalFormat df = new DecimalFormat("#.00");

            // 判断是否为摊位订单
            PosStore store = posStoreService.getById(posOrder.getMdId());
            boolean isStall = store != null && store.getIsStall() != null && store.getIsStall() == 1 && store.getNightMarketId() != null;

            InfoUser user;
            if (isStall) {
                user = infoUserService.getById(store.getNightMarketId());
            } else {
                user = infoUserService.getById(posOrder.getShId());
            }
            Double fcbili = user.getCommission() == null ? 0.00 : user.getCommission();
            JSONArray list = JSONArray.parseArray(posOrder.getFood());
            int fenc = 0;
            for (int i = 0; i < list.size(); i++) {
                JSONObject foods = list.getJSONObject(i);
                int price = foods.getInteger("price");
                int otherPrice = foods.getInteger("otherPrice");
                int num = foods.getInteger("number");
                int age = (price + otherPrice) * num;
                fenc += age;
            }
            String remark = "";
            if (posOrder.getMdYhId() != null && posOrder.getMdDiscountAmount() != null) {
                VipUserQuanyi userQuanyi = userQuanyiService.getById(posOrder.getMdYhId());
                if (userQuanyi != null && "1".equals(userQuanyi.getType())) {
                    fenc = fenc - posOrder.getMdDiscountAmount();
                    String yhmcMessage = MessageUtils.message("no.posorder.md.yh.mc.messag");
                    yhmcMessage = StrUtil.format(yhmcMessage, posOrder.getMdYhName());
                    remark += yhmcMessage;
                    String yhAmount = MessageUtils.message("no.posorder.md.yh.jiner.messag");
                    yhAmount = StrUtil.format(yhAmount, posOrder.getMdDiscountAmount());
                    remark += yhAmount;
                }
            }
            if (posOrder.getMdSalesName() != null && posOrder.getMdSalesReduction() != null) {
                fenc = fenc - posOrder.getMdSalesReduction();
                String cxNameMessage = MessageUtils.message("no.posorder.md.cx.mc.messag");
                cxNameMessage = StrUtil.format(cxNameMessage, posOrder.getMdSalesName());
                remark += cxNameMessage;
                String cxAmount = MessageUtils.message("no.posorder.md.cx.jiner.messag");
                cxAmount = StrUtil.format(cxAmount, posOrder.getMdSalesReduction());
                remark += cxAmount;
            }
            billing.setIllustrate(remark);
            Double chouc = fenc * fcbili;
            Double shfc = fenc - chouc;
            billing.setUserId(posOrder.getShId());
            billing.setDdId(String.valueOf(posOrder.getDdId()));
            billing.setType("0");
            billing.setAmount(Double.valueOf(df.format(shfc)));
            billing.setDivvy(Double.valueOf(df.format(chouc)));
            billing.setState("0");
            billing.setMdId(posOrder.getMdId());
            billing.setUserType("1");
            billing.setDivvyRate(fcbili);
            if (isStall) {
                billing.setStoreId(Long.valueOf(store.getId()));
                walletService.addStallBalance(Long.valueOf(store.getId()), BigDecimal.valueOf(billing.getAmount()), billing);
            } else {
                walletService.addBalance(billing.getUserId(), BigDecimal.valueOf(billing.getAmount()), billing);
            }
        }
    }

    /**
     * 执行骑手分成
     */
    public void setQishouBilling(PosOrder posOrder) {
        long count = userBillingService.count(new LambdaQueryWrapper<UserBilling>()
                .eq(UserBilling::getUserId, posOrder.getQsId())
                .eq(UserBilling::getType, "0")
                .eq(UserBilling::getDdId, posOrder.getDdId()));
        if (count <= 0) {
            UserBilling billing = new UserBilling();
            DecimalFormat df = new DecimalFormat("#.00");
            InfoUser user = infoUserService.getById(posOrder.getQsId());
            if (user == null) {
                System.out.println("订单无骑手");
            } else {
                Double fcbili = user.getCommission() == null ? 0.00 : user.getCommission();
                Double fenc = posOrder.getFreight();
                Double chouc = fenc * fcbili;
                Double shfc = fenc - chouc;
                List<SysDictData> taxBl = DictUtils.getDictCache("sys_qs_freight_bl");
                if (taxBl != null && taxBl.get(0) != null) {
                    Double tax = shfc * Double.parseDouble(taxBl.get(0).getDictValue());
                    billing.setTax(BigDecimal.valueOf(tax));
                    billing.setTaxRate(taxBl.get(0).getDictValue());
                    shfc = shfc - tax;
                }
                billing.setUserId(posOrder.getQsId());
                billing.setDdId(String.valueOf(posOrder.getDdId()));
                billing.setType("0");
                billing.setAmount(Double.valueOf(df.format(shfc)));
                billing.setDivvy(Double.valueOf(df.format(chouc)));
                billing.setState("0");
                billing.setMdId(posOrder.getMdId());
                billing.setUserType("2");
                billing.setDivvyRate(user.getCommission());
                if ("1".equals(posOrder.getCollectPayment())) {
                    billing.setBehalfAmount(Double.valueOf(posOrder.getAmount()));
                }
                walletService.addBalance(billing.getUserId(), BigDecimal.valueOf(billing.getAmount()), billing);
            }
        }
    }
}
