package cn.pluss.platform.life;

import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.constants.Constant;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantMemberCode.MerchantMemberCodeService;
import cn.pluss.platform.merchantMenber.MerchantMenberService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * TODO
 * 生活圈接口相关处理handler
 * @author crystal
 * @date 2022/5/13 17:02
 */
@Slf4j
@Component
public class LifeApiHandler {

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private MerchantStoreService merchantStoreService;

    @Resource
    private MerchantMenberService merchantMenberService;

    @Resource
    private MerchantMemberCodeService merchantMemberCodeService;

    @Resource
    private MerchantBaseInfoService merchantBaseInfoService;

    private static String LIFE_MEMBER_CARD_SYSTEM_KEY = "life_member_card_refresh_time";

    /**
     * 获取会员卡默认的过期时间
     * @return
     */
    public String getCardExpire() {
        String value = systemConfigService.querySystemConfigValue(LIFE_MEMBER_CARD_SYSTEM_KEY);
        if(StringUtil.isEmpty(value)){
            value = Constant.DEFAULT_LIFE_MEMBER_CARD_REFRESH_TIME.toString();
        }
        return value;
    }

    /**
     * 刷新会员卡code
     * @param code
     * @return
     */
    public Result<Object> refreshCardCode(MerchantMemberCode code) {
        code.check();
        MerchantStore store = merchantStoreService.getById(code.getStoreId());
        MsgException.checkNull(store,"门店信息有误！");
        MerchantMenber menber = merchantMenberService.getByCardNo(code.getCardNo());
        MsgException.checkNull(menber,"会员卡号异常！");
        MsgException.check(!menber.getMerchantCode().equals(store.getMerchantCode()),"当前会员卡不属于该门店的会员！");
        merchantMemberCodeService.removeByCardNo(code.getCardNo());
        String cardExpire = getCardExpire();
        code.conver(menber,Integer.valueOf(cardExpire));
        merchantMemberCodeService.save(code);
        return ResultGenerator.genSuccessResult("刷新成功",code);
    }

    /**
     * 获取商户信息
     * @param param
     * @return
     */
    public Result<Object> getMerchantInfo(LifeParam param) {
        param.check();
        MerchantStore store = merchantStoreService.getById(param.getSyb_m_id());
        MsgException.checkNull(store,"门店信息异常");
        MerchantBaseInfo merchant = merchantBaseInfoService.getMerchantBaseInfoByMerchantCode(store.getMerchantCode());
        return ResultGenerator.genSuccessResult("获取成功",merchant);
    }
}
