package com.zanxiang.game.module.sdk.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zanxiang.game.module.mybatis.entity.PayBox;
import com.zanxiang.game.module.mybatis.mapper.PayBoxMapper;
import com.zanxiang.game.module.sdk.pojo.dto.PayBoxDTO;
import com.zanxiang.game.module.sdk.pojo.dto.PayMerchantDTO;
import com.zanxiang.game.module.sdk.service.IPayBoxService;
import com.zanxiang.game.module.sdk.service.IPayMerchantService;
import com.zanxiang.module.util.JsonUtil;
import com.zanxiang.module.util.bean.BeanUtil;
import com.zanxiang.module.util.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 支付盒子 服务实现类
 *
 * @author xufeng
 * @date 2022-06-22 15:26
 */
@Slf4j
@Service
public class PayBoxServiceImpl extends ServiceImpl<PayBoxMapper, PayBox> implements IPayBoxService {

    @Autowired
    private IPayMerchantService payMerchantService;

    @Override
    public PayMerchantDTO getMerchantByBoxId(Long payBoxId) {
        PayBox payBox = super.getById(payBoxId);
        if (payBox == null) {
            log.error("参数错误, 支付盒子信息不存在, payBoxId : {}", payBoxId);
            throw new BaseException("参数错误, 支付盒子信息不存在");
        }
        //查询盒子绑定的商户
        String merchantNos = payBox.getMerchantNos();
        if (Strings.isBlank(merchantNos)) {
            log.error("数据错误,盒子未绑定商户, payBoxId : {}", payBoxId);
            throw new BaseException("数据错误,盒子未绑定商户");
        }
        String[] merchantNoArray = merchantNos.split(",");
        List<String> merchantNoList = Arrays.stream(merchantNoArray).collect(Collectors.toList());
        //查询商户列表
        List<PayMerchantDTO> payMerchantDTOList = payMerchantService.getByMerchantNos(merchantNoList);


        //当前时间与商户个数取模, 获得随机数
        int sit = (int) (System.currentTimeMillis() % payMerchantDTOList.size());

        log.error("盒子查询商户列表, payBoxId : {}, payMerchantDTOList : {}, sit : {}", payBoxId, JsonUtil.toString(payMerchantDTOList), sit);

        //返回商户信息
        return payMerchantDTOList.get(sit);
    }

    @Override
    public PayBoxDTO getById(Long id) {
        PayBox payBox = super.getById(id);
        if (payBox == null) {
            log.error("参数错误, 盒子信息不存在, id : {}", id);
            throw new BaseException("参数错误, 盒子信息不存在");
        }
        return BeanUtil.copy(payBox, PayBoxDTO.class);
    }
}
