package com.jeequan.jeepay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.converter.MchInfoConverter;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.db.entity.MchStore;
import com.jeequan.jeepay.db.entity.RedPacketRule;
import com.jeequan.jeepay.service.mapper.RedPacketRuleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 红包规则表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2024-01-17
 */
@Service
public class RedPacketRuleService extends ServiceImpl<RedPacketRuleMapper, RedPacketRule>{

    @Autowired private MchStoreService mchStoreService;

    @Autowired private MchInfoConverter mchInfoConverter;
    /**
     * 判断用户和门店是否开通了红包规则
     * @param mchNo
     * @param storeId
     * @return
     */
    public boolean isCheckStoreRedRule(String mchNo, String storeId) {
        RedPacketRule rule = getRuleByMchStrore(mchNo, storeId);
        return rule == null || CS.NO == rule.getState() ? false : true;
    }

    public RedPacketRule getRuleByMchStrore(String mchNo, String storeId) {
        LambdaQueryWrapper<RedPacketRule> wrapper = RedPacketRule.gw().eq(RedPacketRule::getMchNo,mchNo).eq(RedPacketRule::getStoreId,storeId);
        return getOne(wrapper);
    }

    /**
     * 新增保存
     * @param info
     */
    public void addSave(RedPacketRule info) {
        info.preCheck();
        List<String> storeIdList = info.getStoreIdList();
        if(info.getConfigType().intValue() == RedPacketRule.ALL){
            storeIdList = mchStoreService.listByMchNo(info.getMchNo());
        }
        if(storeIdList == null || storeIdList.isEmpty()){
            throw new BizException("当前商户暂未创建门店信息，无法绑定");
        }
        List<RedPacketRule> ruleList = new ArrayList<>(storeIdList.size());
        List<MchStore> list = mchStoreService.listByIds(storeIdList);
        for (MchStore store:list) {
            RedPacketRule saveData = new RedPacketRule();
            mchInfoConverter.cp(info,saveData);
            saveData.setStoreId(store.getStoreId());
            saveData.setStoreName(store.getStoreName());
            ruleList.add(saveData);
        }
        try {
            saveBatch(ruleList);
        }catch (Exception e){
            throw new BizException("每个门店只支持一种红包规则");
        }
    }
}
