package com.jeequan.jeepay.member.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.utils.JsonKit;
import com.jeequan.jeepay.db.entity.MchConfig;
import com.jeequan.jeepay.db.entity.MchStore;
import com.jeequan.jeepay.db.entity.MemberRechargeRule;
import com.jeequan.jeepay.service.impl.MchConfigService;
import com.jeequan.jeepay.service.impl.MchStoreService;
import com.jeequan.jeepay.service.impl.MemberRechargeRuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 商户充值规则服务类
 *
 * @author zx
 * @date 2023/4/8 17:40
 */

@Service
@Slf4j
public class MchRechargeRuleEntryService {

    @Autowired
    private MemberRechargeRuleService memberRechargeRuleService;
    @Autowired
    private MchStoreService mchStoreService;
    @Autowired
    private MchConfigService mchConfigService;

    /**
     * 获取商户充值规则
     */
    public ApiRes getMchRechargeRule(MchAppConfigContext mchAppConfigContext) {

        String mchNo = mchAppConfigContext.getMchNo();

        // 查询商户充值规则
        List<MemberRechargeRule> rechargeRuleList = memberRechargeRuleService.list(MemberRechargeRule.gw()
                .select(MemberRechargeRule::getRuleId, MemberRechargeRule::getRechargeAmount, MemberRechargeRule::getGiveAmount, MemberRechargeRule::getSort)
                .eq(MemberRechargeRule::getMchNo, mchNo)
                .eq(MemberRechargeRule::getState, CS.YES)
                .orderByAsc(MemberRechargeRule::getSort)
                .orderByDesc(MemberRechargeRule::getCreatedAt)
        );

        // 自定义充值配置查询
        MchConfig mchConfig = mchConfigService.getByMchNoAndConfigKey(mchNo, MchConfig.SELF_MEMBER_CUSTOM_AMOUNT_STATE);
        // 自定义充值金额配置
        JSONObject extJson = JsonKit.newJson(MchConfig.SELF_MEMBER_CUSTOM_AMOUNT_STATE, mchConfig == null ? MchConfig.NO : mchConfig.getConfigVal());

        IPage<MemberRechargeRule> iPage = new Page<>();
        iPage.setRecords(rechargeRuleList);

        return ApiRes.page(iPage, extJson);
    }

    /**
     * 获取商户充值规则 适用门店
     */
    public ApiRes getMchRechargeRuleStore(MchAppConfigContext mchAppConfigContext) {
        String mchNo = mchAppConfigContext.getMchNo();

        return ApiRes.ok(mchStoreService.list(MchStore.gw()
                .select(MchStore::getStoreName)
                .eq(MchStore::getMchNo, mchNo)));
    }

}
