package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.LifeUserExpertOrder;
import shop.alien.entity.store.LifeUserExpertPurchase;
import shop.alien.entity.store.LifeUserExpertWorks;
import shop.alien.entity.store.StoreAliPayLog;
import shop.alien.entity.store.vo.LifeUserExpertVo;
import shop.alien.mapper.LifeUserExpertMapper;
import shop.alien.mapper.LifeUserExpertOrderMapper;
import shop.alien.mapper.LifeUserExpertPurchaseMapper;
import shop.alien.mapper.LifeUserExpertWorksMapper;
import shop.alien.store.service.LifeUserExpertPurchaseService;
import shop.alien.store.util.ali.AliApi;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: fcw
 * @CreateTime: 2025-03-06
 * @Description: 用户购买达人推广商品
 */

@Service
@RequiredArgsConstructor
public class LifeUserExpertPurchaseServiceImpl extends ServiceImpl<LifeUserExpertPurchaseMapper, LifeUserExpertPurchase> implements LifeUserExpertPurchaseService {

    private final LifeUserExpertPurchaseMapper lifeUserExpertPurchaseMapper;

    private final LifeUserExpertOrderMapper lifeUserExpertOrderMapper;

    private final LifeUserExpertWorksMapper lifeUserExpertWorksMapper;

    private final AliApi aliApi;

    private final LifeUserExpertMapper lifeUserExpertMapper;


    @Override
    public Map<String, Object> purchaseTalentPromotedProduct(LifeUserExpertPurchase lifeUserExpertPurchase) {
        Map<String, Object> returnMap = new HashMap<>();
        lifeUserExpertPurchaseMapper.insert(lifeUserExpertPurchase);
        // 用户购买商品 修改达人订单信息
        LifeUserExpertOrder lifeUserExpertOrder = lifeUserExpertOrderMapper.selectById(lifeUserExpertPurchase.getOrderId());
        // 判断达人是否完成商户推广套餐订单 播放量 GMV 金额
        // 金额 将新增加的金额添加到原有的金额上
        BigDecimal decimal = lifeUserExpertOrder.getAccountMoney();
        BigDecimal add = lifeUserExpertPurchase.getPurchaseAmount().add(decimal);
        BigDecimal orderMoney = lifeUserExpertOrder.getOrderMoney();
        lifeUserExpertOrder.setAccountMoney(add);

        // 播放量
        List<LifeUserExpertWorks> lifeUserExpertWorksList = lifeUserExpertWorksMapper.selectList(new LambdaQueryWrapper<LifeUserExpertWorks>().eq(LifeUserExpertWorks::getOrderId, lifeUserExpertPurchase.getOrderId()));
        // 初始化总播放次数
        int totalPlayCount = 0;

        // 遍历查询结果，累加播放次数
        for (LifeUserExpertWorks lifeUserExpertWorks : lifeUserExpertWorksList) {
            totalPlayCount += lifeUserExpertWorks.getPlayCount();
        }
        // GMV
        if (add.compareTo(lifeUserExpertOrder.getOrderMoney()) == 1 || totalPlayCount > lifeUserExpertOrder.getOrderPlayCount() || add.intValue() > lifeUserExpertOrder.getOrderGmv().intValue()) {
            // 达到订单标准 将尾款转账到达人账户 修改订单状态为已完成
            LifeUserExpertVo talentIdentityInformation = lifeUserExpertMapper.getTalentIdentityInformation(lifeUserExpertOrder.getExpertId());
            if (talentIdentityInformation == null) {
                returnMap.put("error", "未找到对应的达人身份信息");
                return returnMap;
            }

            // 平台收取10%服务费
            BigDecimal amountAfterServiceFeeDeduction = orderMoney.subtract(orderMoney.multiply(BigDecimal.valueOf(0.1))).divide(new BigDecimal(100), 0, RoundingMode.HALF_UP);
            // 支付合同金额(扣完10%服务费)的50%
            BigDecimal lastArrivalAmount = new BigDecimal(amountAfterServiceFeeDeduction.intValue() * 0.5).divide(new BigDecimal(100), 0, RoundingMode.HALF_UP);
            StoreAliPayLog pay = aliApi.pay(talentIdentityInformation.getRealName(), talentIdentityInformation.getIdCard(), talentIdentityInformation.getUserPhone(), String.valueOf(lastArrivalAmount));
            if (null == pay) {
                returnMap.put("transferFailure", "尾笔打款失败，请联系平台");
            }
            returnMap.put("transferSuccess", "尾笔打款成功");
            lifeUserExpertOrder.setFirstPaymentTime(new Date());
            lifeUserExpertOrder.setStatus(2);
        }
        lifeUserExpertOrderMapper.updateById(lifeUserExpertOrder);
        returnMap.put("success", "更新信息成功");
        return returnMap;
    }
}
