package com.qnfhq.modules.user.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qnfhq.common.redis.RedisUtils;
import com.qnfhq.common.service.impl.CrudServiceImpl;
import com.qnfhq.modules.user.dao.AppWalletRecordDao;
import com.qnfhq.modules.user.dto.AppWalletRecordDTO;
import com.qnfhq.modules.user.entity.AppWalletRecordEntity;
import com.qnfhq.modules.user.enums.CachePrefix;
import com.qnfhq.modules.user.service.AppWalletRecordService;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * 用户账变信息
 *
 * @author yelz 30262728@qq.com
 * @since 1.0.0 2025-11-20
 */
@Service
public class AppWalletRecordServiceImpl extends CrudServiceImpl<AppWalletRecordDao, AppWalletRecordEntity, AppWalletRecordDTO> implements AppWalletRecordService {

    private final RedisUtils redisUtils;

    public AppWalletRecordServiceImpl(RedisUtils redisUtils) {
        super();
        this.redisUtils = redisUtils;
    }

    @Override
    public QueryWrapper<AppWalletRecordEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<AppWalletRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);

        return wrapper;
    }

    @Override
    public void generateRecord(Long userId, BigDecimal amount, int type, String createBy, String serialId, String remark,
                               BigDecimal before, BigDecimal after, String symbol, String adminParentIds) {
        AppWalletRecordEntity record = new AppWalletRecordEntity();

        record.setSerialId(serialId);
        record.setUserId(userId);
        record.setAmount(amount);
        record.setCreateTime(new Date());
        record.setType(type);
        record.setRemark(remark);
        record.setCreateBy(createBy);
        record.setBeforeAmount(before);
        record.setAfterAmount(after);
        record.setSymbol(symbol);
        record.setAdminParentIds(adminParentIds);
        record.setOperateTime(new Date());
        try {
            if (!symbol.equals("usdt")){
                BigDecimal price = Convert.toBigDecimal(redisUtils.get(CachePrefix.CURRENCY_PRICE.getPrefix() + symbol.toLowerCase()));
                if(price == null) price = BigDecimal.ZERO;
                log.warn("帐变记录获取汇率：  币种："+symbol+"  汇率："+price+"");
                record.setUAmount(amount.multiply(price));
            }else{
                record.setUAmount(amount);
            }
        } catch (Exception e) {
            log.error("in generateRecord err:"+e.getMessage());
        }

        record.setCreateTime(new Date());
        insert(record);
    }
}