package cn.pluss.platform.merchant.move.impl;

import cn.hutool.core.date.DateUtil;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantMoveRecordsMapper;
import cn.pluss.platform.merchant.move.MerchantMoveRecordsService;
import cn.pluss.platform.merchant.move.MerchantMoveSettingService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.userApp.UserAppService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>
 * 商户动态码生成记录 服务实现类
 * </p>
 *
 * @author bzg
 * @since 2021-07-30
 */
@Service
public class MerchantMoveRecordsServiceImpl extends ServiceImpl<MerchantMoveRecordsMapper, MerchantMoveRecords> implements MerchantMoveRecordsService {

    @Autowired
    private UserAppService userAppService;

    @Autowired
    private MerchantBaseInfoService mbiService;

    @Autowired
    private MerchantChannelStatusService channelStatusService;

    @Autowired
    private MerchantMoveSettingService merchMoveSettingService;

    @Override
    public MerchantMoveRecords createToken() {
        UserApp tokenUserApp = userAppService.queryUserAppByToken();

        MerchantChannelStatus channelStatus = channelStatusService.getByMerchantCode(tokenUserApp.getMerchantCode(), 4);
        if (channelStatus == null || !Objects.equals(channelStatus.getChannel(), 4)) {
            throw new MsgException("D0通道暂未开通，请开通D0后再试");
        }

        if (Objects.equals(channelStatus.getChannel(), 4) && !MerchantChannelStatus.AUDIT_STATUS_SUCCESS.equals(channelStatus.getStatus())) {
            throw new MsgException("D0通道暂未通过，请稍后再试");
        }

        String uuid = UUID.randomUUID().toString().replace("-", "");

        Date startTime = new Date();
        long endTimestamp = startTime.getTime() + 5 * 60 * 1000;
        Date endTime = new Date(endTimestamp);

        MerchantBaseInfo mbi = mbiService.getMerchantBaseInfoByMerchantCode(tokenUserApp.getMerchantCode());
        MerchantMoveRecords merchMoveRecord = new MerchantMoveRecords();
        merchMoveRecord.setMerchantCode(mbi.getMerchantCode());
        MerchantMoveRecords exist = getOne(new QueryWrapper<>(merchMoveRecord).orderByDesc("createTime").last("limit 1"));

        // 过期或无效标识
        var flag = false;
        checkCount(tokenUserApp.getMerchantCode());

        if (exist == null) {
            merchMoveRecord.setMerchantName(mbi.getAlias());
            merchMoveRecord.setStartTime(startTime);
            merchMoveRecord.setEndTime(endTime);
            merchMoveRecord.setCreateTime(startTime);
            merchMoveRecord.setToken(uuid);
            save(merchMoveRecord);

            return merchMoveRecord;
        }

        if (exist.getPayNum() > 0) {
            flag = true;
        }

        if (DateUtil.compare(exist.getEndTime(), new Date()) < 0) {
            flag = true;
        }

        // 已经过期
        if (flag) {
            merchMoveRecord.setMerchantName(mbi.getAlias());
            merchMoveRecord.setStartTime(startTime);
            merchMoveRecord.setEndTime(endTime);
            merchMoveRecord.setCreateTime(startTime);
            merchMoveRecord.setToken(uuid);
            save(merchMoveRecord);
        } else {
            merchMoveRecord = exist;
        }

        return merchMoveRecord;
    }

    @Override
    public void checkCount(String merchantCode) {
        Date date = new Date();
        Date startTime = DateUtil.beginOfDay(date).toJdkDate();
        Date endTime = DateUtil.endOfDay(date).toJdkDate();

        LambdaQueryWrapper<MerchantMoveRecords> qWrapper = new LambdaQueryWrapper<MerchantMoveRecords>()
                .eq(MerchantMoveRecords::getMerchantCode, merchantCode)
                .between(MerchantMoveRecords::getCreateTime, startTime, endTime);

        // 当日已经生成码的次数
        int count = baseMapper.selectCount(qWrapper);

        LambdaQueryWrapper<MerchantMoveSetting> qWrapperLimit = new LambdaQueryWrapper<MerchantMoveSetting>()
                .eq(MerchantMoveSetting::getMerchantCode, merchantCode);

        MerchantMoveSetting setting = merchMoveSettingService.getOne(qWrapperLimit);
        if (setting == null) {
            setting = new MerchantMoveSetting();
            setting.setMerchantCode(merchantCode);
            setting.setPayNum(20);
            setting.setQrNum(50);
            setting.setAesKey(UUID.randomUUID().toString().replace("-", ""));
            merchMoveSettingService.save(setting);
        }
        int maxQrNum = setting.getQrNum();

        if (count > maxQrNum) {
            throw new MsgException("动态码生成次数当日已达上限");
        }
    }

}
