package com.sqx.modules.callback.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.callback.dao.UniAdCallBackDTO;
import com.sqx.modules.callback.entity.UniAdCallbackRecord;
import com.sqx.modules.callback.service.UniAdCallbackRecordService;
import com.sqx.modules.callback.mapper.UniAdCallbackRecordMapper;
import com.sqx.modules.common.dao.CommonInfoDao;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.redisService.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
* @author Administrator
* @description 针对表【uni_ad_callback_record】的数据库操作Service实现
* @createDate 2024-12-23 10:37:52
*/
@Service
@Slf4j
public class UniAdCallbackRecordServiceImpl extends ServiceImpl<UniAdCallbackRecordMapper, UniAdCallbackRecord>
    implements UniAdCallbackRecordService{
    @Value("${sqx.uni.adSecret}")
    private String adSecurity;

    private final UserDao userDao;
    private final CommonInfoDao commonInfoDao;

    private final RedisService redisService;

    public UniAdCallbackRecordServiceImpl(UserDao userDao, CommonInfoDao commonInfoDao, RedisService redisService) {
        this.userDao = userDao;
        this.commonInfoDao = commonInfoDao;
        this.redisService = redisService;
    }

    private String getBaseErrInfo(UniAdCallbackRecord callbackRecord) {
        return StrUtil.format("广告获取免费观看时长回调异常： {}, 用户id: {}, 广告播放回调trans_id: {}",
                callbackRecord.getErrMsg(), callbackRecord.getUserId(), callbackRecord.getTransId());
    }

    // 生成签名
    public static String generateSign(String secret, String transId) {
        // 生成待加密的字符串
        String data = secret + ":" + transId;

        // 使用SHA-256生成签名
        return DigestUtil.sha256Hex(data);
    }

    // 验证签名
    public static boolean validateSign(String secret, String transId, String providedSign) {
        // 生成系统计算出来的签名
        String generatedSign = generateSign(secret, transId);

        // 比较计算出来的签名和提供的签名
        return StrUtil.equalsIgnoreCase(generatedSign, providedSign);
    }

    @Override
    public Map<String, Object> adCallBack(UniAdCallBackDTO callBackDTO) {
        HashMap<String, Object> respData = new HashMap<>();
        UniAdCallbackRecord one = getOne(new LambdaQueryWrapper<UniAdCallbackRecord>()
                .eq(UniAdCallbackRecord::getTransId, callBackDTO.getTrans_id()));
        if (one != null) {
            log.warn("回调重复, {}", one.getTransId());
            respData.put("isValid", false);
            return respData;
        }
        UniAdCallbackRecord callbackRecord = new UniAdCallbackRecord();
        callbackRecord.setUserId(Long.valueOf(callBackDTO.getUser_id()));
        callbackRecord.setPlatform(callBackDTO.getPlatform());
        callbackRecord.setTransId(callBackDTO.getTrans_id());
        callbackRecord.setAdpid(callBackDTO.getAdpid());
        callbackRecord.setProvider(callBackDTO.getProvider());
        callbackRecord.setSign(callBackDTO.getSign());
        callbackRecord.setExtra(callBackDTO.getExtra());
        callbackRecord.setCreateTime(DateUtil.date());
        callbackRecord.setIsEnded(1);

        boolean flag = validateSign(adSecurity, callBackDTO.getTrans_id(), callBackDTO.getSign());
        if (!flag) {
            callbackRecord.setErrMsg("签名验证失败");
            log.warn(getBaseErrInfo(callbackRecord));
            save(callbackRecord);
            respData.put("isValid", false);
            return respData;
        }

        UserEntity userEntity = userDao.selectById(callBackDTO.getUser_id());
        if (userEntity == null) {
            callbackRecord.setErrMsg("用户不存在");
            log.warn(getBaseErrInfo(callbackRecord));
            save(callbackRecord);
            respData.put("isValid", false);
            return respData;
        }

        CommonInfo info = commonInfoDao.findOne(921);
        if (info == null || StrUtil.isBlank(info.getValue())){
            callbackRecord.setErrMsg("CommonInfo时长时间未配置");
            log.warn(getBaseErrInfo(callbackRecord));
            save(callbackRecord);
            respData.put("isValid", false);
            return respData;
        }

        redisService.setFreeWatchTime(callbackRecord.getUserId(), Integer.parseInt(info.getValue()) * 60, true);
        save(callbackRecord);
        respData.put("isValid", true);
        return respData;
    }

    @Override
    public HashMap<String, Object> getStateByExtraKey(Long userId, String extraKey) {
        UniAdCallbackRecord one = getOne(new LambdaQueryWrapper<UniAdCallbackRecord>().eq(UniAdCallbackRecord::getUserId, userId)
                .eq(UniAdCallbackRecord::getExtra, extraKey));
        return new HashMap<String, Object>(){{
            put("isEnded", one == null ? 0 : 1);
        }};
    }
}




