package com.sonic.frog.service.impl;

import com.sonic.common.utils.CloudFrontSignerUtils;
import com.sonic.frog.domain.entity.AiUserAlbum;
import com.sonic.frog.domain.entity.AiUserHeartbeatRelation;
import com.sonic.frog.domain.entity.MeetUnlock;
import com.sonic.frog.domain.input.BuyCreateImageCountInput;
import com.sonic.frog.domain.input.UnlockLikeYouInput;
import com.sonic.frog.domain.output.ViewUnlockAlbumImgOutput;
import com.sonic.frog.enums.ToastResultCode;
import com.sonic.frog.service.*;
import com.sonic.frog.utils.KeyGenerator;
import com.sonic.lion.lib.client.PayClient;
import com.sonic.lion.lib.enums.BizType;
import com.sonic.lion.lib.input.BalanceCheckoutInput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @description:
 * @author: mzc
 * @date: 2025-09-10 17:50
 **/
@Service
@Slf4j
public class PayServiceImpl implements PayService {

    @Autowired
    private AiUserAlbumService aiUserAlbumService;
    @Autowired
    private CloudFrontSignerUtils cloudFrontSignerUtils;
    @Autowired
    private PayClient payClient;
    @Autowired
    private BuyCreateCountRecordService buyCreateCountRecordService;
    @Autowired
    private UserCreateCountStatService userCreateCountStatService;
    @Autowired
    private AiUserAlbumUnlockService aiUserAlbumUnlockService;
    @Autowired
    private MeetUnlockService meetUnlockService;
    @Autowired
    private AiUserHeartbeatRelationService aiUserHeartbeatRelationService;
    @Autowired
    private UserAiMeetService userAiMeetService;

    @Override
    public void buyCreateImageCount(BuyCreateImageCountInput input, Long userId) {
        Integer count = input.getCount();
        //调用支付服务扣款
        String orderNo = KeyGenerator.instance().generatorUniqueKey("");
        Long totalAmount = count * 70 * 100L;
        BalanceCheckoutInput balanceCheckoutInput = BalanceCheckoutInput.builder()
                .platform("Balance")
                .outTradeNo(orderNo)
                .bizType(BizType.CREATE_AI_IMAGE)
                .name(BizType.CREATE_AI_IMAGE.getDesc())
                //付款人
                .srcAccountId(userId)
                //收款人
                .desAccountId(-1L)
                //总金额 次数*单价*100
                .productAmount(totalAmount)
                //折扣金额
                .promoAmount(0L)
                .build();
        payClient.checkoutToB(balanceCheckoutInput);
        //保存购买记录
        buyCreateCountRecordService.add(userId, totalAmount, count, orderNo);
        //给用户增加创作次数-购买次数
        userCreateCountStatService.addBuyNum(userId, count);
    }

    @Override
    public ViewUnlockAlbumImgOutput unlockLikeYou(UnlockLikeYouInput input, Long userId) {
        Long albumId = input.getAlbumId();
        AiUserAlbum aiUserAlbum = aiUserAlbumService.getById(albumId);
        ToastResultCode.ALBUM_NOT_EXIST.check(aiUserAlbum == null);

        //调用支付服务扣款
        Long totalAmount = 5000L;
        String orderNo = KeyGenerator.instance().generatorUniqueKey("");
        BalanceCheckoutInput balanceCheckoutInput = BalanceCheckoutInput.builder()
                .platform("Balance")
                .outTradeNo(orderNo)
                .bizType(BizType.UNLOCK_ADMIRERS)
                .name(BizType.UNLOCK_ADMIRERS.getDesc())
                //付款人
                .srcAccountId(userId)
                //收款人
                .desAccountId(-1L)
                //总金额
                .productAmount(totalAmount)
                //折扣金额
                .promoAmount(0L)
                .build();
        payClient.checkoutToB(balanceCheckoutInput);

        //保存相册解锁记录
        aiUserAlbumUnlockService.addUnlockAlbumRecord(userId, albumId, orderNo);
        //保存关系数据
        aiUserHeartbeatRelationService.initAiUserHeartbeatRelation(userId, input.getAiId());
        //保存解锁记录
        MeetUnlock meetUnlock = MeetUnlock.builder()
                .userId(userId)
                .aiId(input.getAiId())
                .orderNo(orderNo)
                .createTime(LocalDateTime.now())
                .build();
        meetUnlockService.save(meetUnlock);
        //添加meet关系数据
        userAiMeetService.addMeet(userId, input.getAiId());

        //返回可见的图片
        //解锁，需要ip和过期时间签名的图片
        String fileUrl = aiUserAlbum.getImgUrl();
        //计算图片的失效时间从当前时间开始+12小时
        Long expTime = System.currentTimeMillis() + 12 * 60 * 60 * 1000L;
        String ipAddress = input.getIpAddress();
        //如果是ipv4 则把日期和ip一起签名
        String img1Url = null;
        String img2Url = null;
        String img3Url = null;
        try {
            img1Url = cloudFrontSignerUtils.signer(fileUrl + CloudFrontSignerUtils.IMG_468_600, new Date(expTime), ipAddress);
            img2Url = cloudFrontSignerUtils.signer(fileUrl + CloudFrontSignerUtils.IMG_800_800, new Date(expTime), ipAddress);
            img3Url = cloudFrontSignerUtils.signer(fileUrl + CloudFrontSignerUtils.ORG_IMG, new Date(expTime), ipAddress);
        } catch (Exception e) {
            log.error("viewUnlockAlbumImg 图片签名失败", e);
        }
        ViewUnlockAlbumImgOutput output = new ViewUnlockAlbumImgOutput();
        output.setImg1(img1Url);
        output.setImg2(img2Url);
        output.setImg3(img3Url);
        return output;
    }
}
