package com.jeequan.jeepay.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.db.entity.MchStore;
import com.jeequan.jeepay.db.entity.MemberRechargeRule;
import com.jeequan.jeepay.service.mapper.MemberRechargeRuleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 会员充值规则表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2023-04-12
 */
@Service
public class MemberRechargeRuleService extends ServiceImpl<MemberRechargeRuleMapper, MemberRechargeRule> {
    @Autowired
    private MemberRechargeRuleMapper memberRechargeRuleMapper;
    @Autowired
    private MchStoreService mchStoreService;

    public void saveDB(MemberRechargeRule rechargeRule){
        if (rechargeRule.getIsAllStore().equals(0)){
            //0代表同步所有门店
            List<MchStore> storeList = mchStoreService.list(MchStore.gw().eq(MchStore::getMchNo, rechargeRule.getMchNo()));
            //新增之前先将之前数据清理
            memberRechargeRuleMapper.delete(MemberRechargeRule.gw().eq(MemberRechargeRule::getMchNo,rechargeRule.getMchNo()));
            for (MchStore mchStore : storeList) {
                //新增规则表信息
                rechargeRule.setStoreId(mchStore.getStoreId());
                rechargeRule.setStoreName(mchStore.getStoreName());
                rechargeRule.setRuleId("R" + DateUtil.format(new Date(), "yyMMdd")+ RandomUtil.randomNumbers(6));
                memberRechargeRuleMapper.insert(rechargeRule);
                //将该信息存入门店表进行关联
                mchStore.setRuleId(rechargeRule.getRuleId());
                mchStoreService.updateById(mchStore);
            }
        } else if (rechargeRule.getIsAllStore().equals(1)) {
            //1代表指定门店
            //取出指定门店id
            String[] split = rechargeRule.getStoreId().split(",");
            for (String s : split) {
                //新增规则表信息
                MchStore mchStore = mchStoreService.getById(s);
                //新增之前先将指定数据清理
                memberRechargeRuleMapper.delete(MemberRechargeRule.gw().eq(MemberRechargeRule::getMchNo,rechargeRule.getMchNo())
                        .eq(MemberRechargeRule::getStoreId,mchStore.getStoreId())
                        .eq(MemberRechargeRule::getStoreName,mchStore.getStoreName()));
                rechargeRule.setStoreId(mchStore.getStoreId());
                rechargeRule.setStoreName(mchStore.getStoreName());
                rechargeRule.setRuleId("R" + DateUtil.format(new Date(), "yyMMdd")+ RandomUtil.randomNumbers(6));
                memberRechargeRuleMapper.insert(rechargeRule);
                //将该信息存入门店表进行关联
                mchStore.setRuleId(rechargeRule.getRuleId());
                mchStoreService.updateById(mchStore);
            }
        }
    }

}
