package cn.pluss.platform.channel;

import cn.pluss.platform.MerchantRateRecordService;
import cn.pluss.platform.entity.MerchantRate;
import cn.pluss.platform.entity.MerchantRateRecord;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.exception.RateNoChangeException;
import cn.pluss.platform.mapper.MerchantRateMapper;
import cn.pluss.platform.userApp.UserAppService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Data;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;
import java.util.Date;

@Data
public abstract class BaseMchChannelRateService implements MchChannelRateService {

    @Resource
    protected MerchantRateMapper merchantRateMapper;

    @Autowired
    protected MerchantRateRecordService merchantRateRecordService;

    @Setter(onMethod_ = {@Autowired, @Lazy})
    protected UserAppService userAppService;

    @Override
    public MerchantRate before(String userId, Integer rate) {
        if (userId == null) {
            throw new MsgException("用户id不能为空");
        }

        MerchantRate merchantRate;
        QueryWrapper<MerchantRate> merchantRateQueryWrapper = new QueryWrapper<MerchantRate>().eq("userId", userId);
        merchantRate = merchantRateMapper.selectOne(merchantRateQueryWrapper);
        if (merchantRate != null && System.currentTimeMillis() - merchantRate.getUpdateTime().getTime() < 3600 * 24 * 1000L) {
            throw new MsgException("请于一天之后再修改费率");
        }

        boolean noChangeFlag = (merchantRate == null && rate.equals(38)) || (merchantRate != null && rate.equals(merchantRate.getRate()));
        if (noChangeFlag) {
            throw new RateNoChangeException();
        }

        QueryWrapper<MerchantRate> queryWrapper = new QueryWrapper<MerchantRate>().eq("userId", userId);
        return merchantRateMapper.selectOne(queryWrapper);
    }

    @Override
    public void after(String userId, Integer rate, MerchantRate merchantRate) {
        // 更新本地数据库保存的费率
        if (merchantRate == null) {
            merchantRate = new MerchantRate().setUserId(userId);
            merchantRate.setRate(rate);
            merchantRate.setUpdateTime(new Date());
            merchantRate.setPreviousRate(38);
            merchantRateMapper.insert(merchantRate);
        } else {
            // 保存前一天的费率
            merchantRate.setPreviousRate(merchantRate.getRate());
            merchantRate.setRate(rate);
            merchantRate.setUpdateTime(new Date());
            merchantRateMapper.updateById(merchantRate);
        }

        // 保存费率修改记录
        MerchantRateRecord merchantRateRecord = new MerchantRateRecord();
        merchantRateRecord.setRate(rate);
        merchantRateRecord.setUserId(userId);
        merchantRateRecord.setCreateTime(new Date());
        merchantRateRecordService.save(merchantRateRecord);
    }
}
