package com.iformall.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iformall.common.ErrorCode;
import com.iformall.common.IdWorker;
import com.iformall.domain.po.*;
import com.iformall.enums.EnumBusiness;
import com.iformall.enums.EnumCUserBasicInfoStatus;
import com.iformall.enums.EnumScoreRules;
import com.iformall.enums.EnumScoreType;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.*;
import com.iformall.service.WxCUserService;
import com.iformall.service.WxScoreRulesService;
import com.iformall.utils.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

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

@Service
public class WxScoreRulesServiceImpl implements WxScoreRulesService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxScoreRulesMapper wxScoreRulesMapper;
    @Autowired
    WxScoreHistoryMapper wxScoreHistoryMapper;
    @Autowired
    WxCUserBasicInfoMapper wxCUserBasicInfoMapper;
    @Autowired
    WxCUserMapper wxCUserMapper;
    @Autowired
    WxCUserService wxCUserService;

    @Autowired
    @Qualifier("scoreRuleRedisTemplate")
    RedisTemplate<String, WxScoreRules> scoreRulesRedisTemplate;

    @Autowired
    WxMerchantMapper wxMerchantMapper;

    @Override
    public WxScoreRules getScoreRules(String tenantId) {
        // get pushLime from cache
        String key = Constant.SCORE_RULES_KEY_PREV + tenantId;

        // 缓存存在
        if (scoreRulesRedisTemplate.hasKey(key)) {
            WxScoreRules wScoreRules = scoreRulesRedisTemplate.opsForValue().get(key);
            logger.info("WxScoreRulesServiceImpl.getScoreRules() : 从缓存中获取了成长值设置 >> " + wScoreRules.toString());
            return wScoreRules;
        }

        WxScoreRules scoreRules = new WxScoreRules();
        scoreRules.setTenantId(tenantId);
        scoreRules.setType(EnumScoreRules.SCORE.getCode());
        List<WxScoreRules> list = wxScoreRulesMapper.findList(scoreRules);
        if (list.size() > 0) {
            scoreRules = list.get(0);
            scoreRules.setRules(getScoreRulesNew(scoreRules.getRules(),EnumScoreRules.SCORE));

        } else {
            // 如果成长值规则不存在，启用默认值
            this.saveOrUpdate(scoreRules);
            //final IdWorker idWorker = IdWorker.get();
            //scoreRules.setId(idWorker.nextId());
            //scoreRules.setRules(WxScoreRules.getScoreDefaultRules());
            //
            //wxScoreRulesMapper.insert(scoreRules);
        }
        // 插入缓存
        scoreRulesRedisTemplate.opsForValue().set(key, scoreRules);
        logger.info("WxScoreRulesServiceImpl.getScoreRules() : 成长值设置插入缓存 >> " + scoreRules.toString());

        return scoreRules;
    }

    //当成长值或积分规则新增时,将新增的数据一并返回给接口调用端
    private String getScoreRulesNew(String scoreRules,EnumScoreRules enumScoreRules){
        //getJSONObject(1) 为EnumScoreType.CONSUMPTION(2, "消费")的下标值
        JSONArray jsonArrayOld = JSONArray.parseArray(scoreRules).getJSONObject(1).getJSONArray("childs");
        String defaultRules = enumScoreRules.equals(EnumScoreRules.SCORE) ? WxScoreRules.getScoreDefaultRules() : WxScoreRules.getCreditDefaultRules();
        JSONArray jsonArrayDefault = JSONArray.parseArray(defaultRules).getJSONObject(1).getJSONArray("childs");
        if (jsonArrayOld.size() < jsonArrayDefault.size()) {
            JSONArray childsJsonArray = new JSONArray();
            JSONObject otherJSONObject = new JSONObject();
            //组装新的childs
            for (int i = 0; i < jsonArrayDefault.size(); i++) {
                JSONObject defaultJSONObject = jsonArrayDefault.getJSONObject(i);
                if (i < jsonArrayOld.size()) {
                    JSONObject oldJSONObject = jsonArrayOld.getJSONObject(i);
                    if (defaultJSONObject.getString("businessId").equals(oldJSONObject.getString("businessId"))) {
                        childsJsonArray.add(oldJSONObject);
                    }else {
                        childsJsonArray.add(defaultJSONObject);
                        otherJSONObject = oldJSONObject;
                    }
                } else {
                    childsJsonArray.add(defaultJSONObject);
                }
            }
            //businessId为6的是其它需要放到最后
            childsJsonArray.remove(childsJsonArray.size()-1);
            childsJsonArray.add(otherJSONObject);
            //将变更后的childs替换
            JSONArray originalJSONArray = JSONArray.parseArray(scoreRules);
            JSONObject newJSONObject = new JSONObject();
            newJSONObject.put("id",EnumScoreType.CONSUMPTION.getCode());
            newJSONObject.put("childs",childsJsonArray);
            //移除下标为1的JSONArray 即:EnumScoreType.CONSUMPTION(2, "消费")
            originalJSONArray.remove(1);
            originalJSONArray.add(1,newJSONObject);
            return originalJSONArray.toJSONString();
        }
        return scoreRules;
    }

    @Override
    public WxScoreRules getCreditRules(String tenantId) {
        // get pushLime from cache
        String key = Constant.CREDIT_RULES_KEY_PREV + tenantId;

        // 缓存存在
        if (scoreRulesRedisTemplate.hasKey(key)) {
            WxScoreRules wScoreRules = scoreRulesRedisTemplate.opsForValue().get(key);
            logger.info("WxScoreRulesServiceImpl.getScoreRules() : 从缓存中获取了积分值设置 >> " + wScoreRules.toString());
            return wScoreRules;
        }

        WxScoreRules scoreRules = new WxScoreRules();
        scoreRules.setTenantId(tenantId);
        scoreRules.setType(EnumScoreRules.CREDIT.getCode());
        List<WxScoreRules> list = wxScoreRulesMapper.findList(scoreRules);
        if (list.size() > 0) {
            scoreRules = list.get(0);
            scoreRules.setRules(getScoreRulesNew(scoreRules.getRules(),EnumScoreRules.CREDIT));
        } else {
            // 如果积分规则不存在，启用默认值
            final IdWorker idWorker = IdWorker.get();
            scoreRules.setId(idWorker.nextId());
            scoreRules.setRules(WxScoreRules.getCreditDefaultRules());
            scoreRules.setScale(WxScoreRules.DEFAULT_SCALE);
            wxScoreRulesMapper.insert(scoreRules);
        }

        // 插入缓存
        scoreRulesRedisTemplate.opsForValue().set(key, scoreRules);
        logger.info("WxScoreRulesServiceImpl.getScoreRules() : 积分设置插入缓存 >> " + scoreRules.toString());

        return scoreRules;
    }


    @Override
    public void saveOrUpdate(WxScoreRules record) {
        Date date = new Date();
        record.setUpdateDate(date);
        if (record.getId() == null) {
            final IdWorker idWorker = IdWorker.get();
            record.setId(idWorker.nextId());
            record.setCreateDate(date);
            wxScoreRulesMapper.insert(record);
        } else {
            wxScoreRulesMapper.updateById(record);
        }

        if (record != null && record.getType().equals(EnumScoreRules.SCORE.getCode())) {
            // 缓存存在，删除缓存
            String key = Constant.SCORE_RULES_KEY_PREV + record.getTenantId();
            boolean hasKey = scoreRulesRedisTemplate.hasKey(key);
            if (hasKey) {
                scoreRulesRedisTemplate.delete(key);
                logger.info("WxScoreRulesServiceImpl.saveOrUpdate() : 从缓存中删除成长值设置 >> " + record.toString());
            }
        }
        if (record != null && record.getType().equals(EnumScoreRules.CREDIT.getCode())) {
            // 缓存存在，删除缓存
            String key = Constant.CREDIT_RULES_KEY_PREV + record.getTenantId();
            boolean hasKey = scoreRulesRedisTemplate.hasKey(key);
            if (hasKey) {
                scoreRulesRedisTemplate.delete(key);
                logger.info("WxScoreRulesServiceImpl.saveOrUpdate() : 从缓存中删除积分设置 >> " + record.toString());
            }
        }

        //更新商户数据
        //updateMerchantCreditLocked(record);
    }

    @Override
    public int cancelScore(WxScoreHistory record) {
        int num = 0;
        WxScoreHistory history = null;
        // 1. delete history
        List<WxScoreHistory> histories = wxScoreHistoryMapper.findList(record);
        if (histories.size() >= 1) {
            history = histories.get(0);
        }
        if (history != null) {
            num = wxScoreHistoryMapper.deleteById(history.getId());
            if (num != 1) {
                logger.error("删除成长值历史出错"+ history.toString());
                throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "删除成长值历史出错");
            }
        } else {
            logger.warn("未找到成长值历史");
            return 0;
        }
        // 2. user score back
        WxCUser wxCUser = wxCUserMapper.selectById(record.getCUserId());
        WxCUserBasicInfo wxCUserBasicInfo = wxCUserBasicInfoMapper.selectById(record.getCUserId());
        if (wxCUser != null) {
            WxCUser wxCUserNew = new WxCUser();
            wxCUserNew.setId(wxCUser.getId());
            wxCUserNew.setScore(wxCUser.getScore() - history.getScoreAmount());
            wxCUserNew.setUpdateDate(new Date());
            wxCUserMapper.updateById(wxCUserNew);
        }
        if (wxCUserBasicInfo != null) {
            WxCUserBasicInfo wxCUserBasicInfoNew = new WxCUserBasicInfo();
            wxCUserBasicInfoNew.setId(wxCUserBasicInfo.getId());
            wxCUserBasicInfoNew.setPoins(wxCUserBasicInfo.getPoins()-history.getScoreAmount());
            wxCUserBasicInfoNew.setUpdateDate(new Date());
            wxCUserBasicInfoMapper.updateById(wxCUserBasicInfoNew);
        }
        return num;
    }

    private void updateScore(Long userId, int addedScoreNumber) {
        // 1. 获取cUser
        WxCUser wxCUser = wxCUserService.getById(userId);
        if (wxCUser.getScore() == null) {
            wxCUser.setScore(0);
        }

        int newScore = wxCUser.getScore() + addedScoreNumber;

        // 2. update score
        wxCUser.setScore(newScore);
        wxCUserService.saveOrUpdate(wxCUser);

        // 3. 修改basic points
        if (wxCUser.getPhone() != null) {
            //修改basic表积分
            WxCUserBasicInfo wxCUserBasicInfo = new WxCUserBasicInfo();
            wxCUserBasicInfo.setId(wxCUser.getId());
            wxCUserBasicInfo.setTenantId(wxCUser.getTenantId());
            wxCUserBasicInfo.setPhone(wxCUser.getPhone());
            wxCUserBasicInfo.setPoins(newScore);
            wxCUserBasicInfoMapper.updateScore(wxCUserBasicInfo);
        }
    }



    private void resetBasicUserScore(Long userId, int scoreNumber) {
        // 1. basicUser
        WxCUserBasicInfo user = wxCUserBasicInfoMapper.selectById(userId);
        if(user == null) {
            return;
        }

        // 2. update score/ 修改basic表积分
        user.setPoins(scoreNumber);
        wxCUserBasicInfoMapper.updateScore(user);

        // 3. 修改 c_user表积分 score
        if (user.getPhone() != null) {
            WxCUser wxCUser = new WxCUser();
            wxCUser.setTenantId(user.getTenantId());
            wxCUser.setPhone(user.getPhone());
            List<WxCUser> list = wxCUserMapper.findList(wxCUser);
            if (!list.isEmpty()) {
                wxCUser = list.get(0);
                wxCUser.setScore(scoreNumber);
                wxCUserService.saveOrUpdate(wxCUser);
            }
        }
    }

    private void resetBasicUserScore(WxCUserBasicInfo user, boolean bHaveCUser) {
        // 1. basicUser
        if(user == null) {
            return;
        }

        // 2. update score/ 修改basic表积分
        // user.setPoins(scoreNumber);
        // wxCUserBasicInfoMapper.updateScore(user);

        // 3. 只修改已存在 c_user表积分 score
        if(bHaveCUser) {
            WxCUser wxCUser = new WxCUser();
            wxCUser.setId(user.getId());
            wxCUser.setScore(user.getPoins());
            wxCUserService.saveOrUpdate(wxCUser);
        }
    }

    private int checkTodayLoginScoreCount(WxCUser cUser) {
        WxScoreHistory scoreHistory = new WxScoreHistory();
        scoreHistory.setTenantId(cUser.getTenantId());
        scoreHistory.setCUserId(cUser.getId());
        scoreHistory.setScoreType(EnumScoreType.LOGIN.getCode());
        return wxScoreHistoryMapper.countTodayList(scoreHistory);
    }

    private int loginAddScore(WxCUser user) {
        int addScoreNumber = 0;

        if (checkTodayLoginScoreCount(user) > 0)
            return 0;

        // 1. score_rules
        WxScoreRules scoreRules = getScoreRules(user.getTenantId());

        // 2. 增长的成长值
        addScoreNumber = scoreRules.getRule(EnumScoreType.LOGIN,WxScoreRules.SCORE);
        updateScore(user.getId(), addScoreNumber);
        user.setScore(addScoreNumber);

        // 3. 记录历史
        recordScoreHistory(addScoreNumber, user.getTenantId(), user.getId(), EnumScoreType.LOGIN);

        return addScoreNumber;
    }

    private int payAddScore(WxOrder order, Integer businessId) {
        int addScoreNumber = 0;
        // 订单金额为0时不计入
        if (order.getPayment() == 0)
            return 0;
        // 1. 获取score rules
        WxScoreRules scoreRules = getScoreRules(order.getTenantId());

        // 2. 获取成长值 by id
        JSONObject payRule = scoreRules.getRuleObj(EnumScoreType.CONSUMPTION);
        // 3. 获取成长值 by 业态
        JSONObject busRule = null;
        JSONObject busRuleOther = null;
        JSONArray busRules = payRule.getJSONArray("childs");
        if(busRules != null) {
            for(int i=0;i<busRules.size();i++) {
                JSONObject bus = (JSONObject)busRules.get(i);
                Integer businessId1 = bus.getInteger("businessId");
                if (businessId.equals(businessId1)) {
                    busRule = bus;
                }
                if (businessId1.equals(EnumBusiness.BUSINESS_ID6.getCode())) {
                    busRuleOther = bus;
                }
            }
            if(busRule == null) {
                busRule = busRuleOther;
            }
        }
        if (busRule == null) {
            busRule = payRule;
        }
        Double priceCondition = busRule.getDouble(WxScoreRules.STEP) * 100;  // 元->分
        int baseScore = busRule.getInteger(WxScoreRules.SCORE); //   消费增长积分

        // 4. 计算成长值
        if(order.getPayment() >= priceCondition.intValue()) {
            Double dScoreT = Math.floor(order.getPayment() * 1.0D / priceCondition * baseScore);
            addScoreNumber = dScoreT.intValue();
            logger.info("RULE:" + busRule.toJSONString() + "\nAddScore: " + addScoreNumber);
            if (addScoreNumber == 0) {
                return 0;
            }
        } else {
            logger.info("RULE:" + busRule.toJSONString() + "\nAddScore: 0, not touch score limit");
            return 0;
        }


        // 5. 增长的成长值
        updateScore(order.getCUserId(), addScoreNumber);

        // 6. 记录历史
        recordPayScoreHistory(addScoreNumber, order, EnumScoreType.CONSUMPTION);

        return addScoreNumber;
    }


    private int bindCarAddScore(WxCUserCar userCar) {
        int addScoreNumber = 0;
        // 1. 获取score rules
        WxScoreRules scoreRules = getScoreRules(userCar.getTenantId());

        // 2. 获取成长值
        addScoreNumber = scoreRules.getRule(EnumScoreType.BIND_CAR,WxScoreRules.SCORE);

        // 3. 增长的成长值
        updateScore(userCar.getCUserId(), addScoreNumber);

        // 4. 记录历史
        recordScoreHistory(addScoreNumber, userCar.getTenantId(), userCar.getCUserId(), EnumScoreType.BIND_CAR);
        return addScoreNumber;
    }

    private int personAddScore(WxCUser user) {
        int addScoreNumber = 0;
        // 1. 获取score rules
        WxScoreRules scoreRules = getScoreRules(user.getTenantId());

        // 2. 获取成长值
        addScoreNumber = scoreRules.getRule(EnumScoreType.WECHAT_PERSION,WxScoreRules.SCORE);

        // 3. 增长的成长值
        updateScore(user.getId(), addScoreNumber);

        // 4. 记录历史
        recordScoreHistory(addScoreNumber, user.getTenantId(), user.getId(), EnumScoreType.WECHAT_PERSION);
        return addScoreNumber;
    }

    private int phoneAddScore(WxCUser user) {
        int addScoreNumber = 0;
        // 1. 获取score rules
        WxScoreRules scoreRules = getScoreRules(user.getTenantId());

        // 2. 获取成长值
        addScoreNumber = scoreRules.getRule(EnumScoreType.WECHAT_PHONE,WxScoreRules.SCORE);

        // 3. 增长的成长值
        updateScore(user.getId(), addScoreNumber);

        // 4. 记录历史
        recordScoreHistory(addScoreNumber, user.getTenantId(), user.getId(), EnumScoreType.WECHAT_PHONE);
        return addScoreNumber;
    }

    private int checkCompleteInfoScoreCount(WxCUser cUser) {
        WxScoreHistory scoreHistory = new WxScoreHistory();
        scoreHistory.setTenantId(cUser.getTenantId());
        scoreHistory.setCUserId(cUser.getId());
        scoreHistory.setScoreType(EnumScoreType.COMPLETE_INFO.getCode());
        return wxScoreHistoryMapper.countList(scoreHistory);
    }

    private int infoAddScore(WxCUserBasicInfo userInfo) {
        int addScoreNumber = 0;
        WxCUser user = wxCUserService.getById(userInfo.getId());

        if (user == null || checkCompleteInfoScoreCount(user) > 0)
            return 0;

        // 1. 获取score rules
        WxScoreRules scoreRules = getScoreRules(user.getTenantId());

        // 2. 获取成长值
        addScoreNumber = scoreRules.getRule(EnumScoreType.COMPLETE_INFO,WxScoreRules.SCORE);

        // 3. 增长的成长值
        updateScore(user.getId(), addScoreNumber);

        // 4. 记录历史
        recordScoreHistory(addScoreNumber, user.getTenantId(), user.getId(), EnumScoreType.COMPLETE_INFO);
        return addScoreNumber;
    }

    private int memResetScore(WxCUserBasicInfo userInfo, boolean bHaveCUser) {

        // 1. 导入成长值
        resetBasicUserScore(userInfo, bHaveCUser);

        // 2. 记录历史
        recordScoreHistory(userInfo, EnumScoreType.MEM_IMPORT);
        return userInfo.getPoins();
    }

    private int memReduceScore(WxCUserBasicInfo userInfo, String reason, Integer scoreNum) {
        int score = userInfo.getPoins() - scoreNum;

        // 1. update score/ 修改basic表积分
        userInfo.setPoins(score);
        wxCUserBasicInfoMapper.updateScore(userInfo);

        // 2. 修改 c_user表积分 score
        if (userInfo.getPhone() != null) {
            WxCUser wxCUser = new WxCUser();
            wxCUser.setId(userInfo.getId());
            wxCUser.setTenantId(userInfo.getTenantId());
            wxCUser.setPhone(userInfo.getPhone());
            wxCUser.setScore(score);
            wxCUserService.saveOrUpdate(wxCUser);;
        }

        // 2. 记录历史
        recordReduceScoreHistory(scoreNum, reason, userInfo.getTenantId(), userInfo.getId(), EnumScoreType.MEM_REDUCE);
        return score;
    }

    private void recordScoreHistory(WxCUserBasicInfo userInfo, EnumScoreType wechatPhone) {
        final IdWorker idWorker = IdWorker.get();
        WxScoreHistory history = new WxScoreHistory();
        history.setId(idWorker.nextId());
        history.setTenantId(userInfo.getTenantId());
        history.setCUserId(userInfo.getId());
        history.setCreateDate(new Date());
        history.setScoreType(wechatPhone.getCode());
        history.setScoreAmount(userInfo.getPoins());
        wxScoreHistoryMapper.insert(history);
    }

    private void recordScoreHistory(int addScoreNumber, String tenantId, Long id, EnumScoreType wechatPhone) {
        final IdWorker idWorker = IdWorker.get();
        WxScoreHistory history = new WxScoreHistory();
        history.setId(idWorker.nextId());
        history.setTenantId(tenantId);
        history.setCUserId(id);
        history.setCreateDate(new Date());
        history.setScoreType(wechatPhone.getCode());
        history.setScoreAmount(addScoreNumber);
        wxScoreHistoryMapper.insert(history);
    }

    private void recordPayScoreHistory(int addScoreNumber, WxOrder order, EnumScoreType wechatPhone) {
        final IdWorker idWorker = IdWorker.get();
        WxScoreHistory history = new WxScoreHistory();
        history.setId(idWorker.nextId());
        history.setTenantId(order.getTenantId());
        history.setCUserId(order.getCUserId());
        history.setCreateDate(new Date());
        history.setScoreType(EnumScoreType.CONSUMPTION.getCode());
        history.setOrderId(order.getId());
        history.setPayType(order.getPaymentType());
        history.setPayAmount(order.getPayment());
        history.setScoreAmount(addScoreNumber);
        history.setScoreType(wechatPhone.getCode());
        history.setScoreAmount(addScoreNumber);
        wxScoreHistoryMapper.insert(history);
    }

    private void recordReduceScoreHistory(int reduceScore, String reason, String tenantId, Long id, EnumScoreType wechatPhone) {
        final IdWorker idWorker = IdWorker.get();
        WxScoreHistory history = new WxScoreHistory();
        history.setId(idWorker.nextId());
        history.setTenantId(tenantId);
        history.setCUserId(id);
        history.setCreateDate(new Date());
        history.setScoreType(wechatPhone.getCode());
        history.setScoreAmount(reduceScore*-1);
        history.setReason(reason);
        wxScoreHistoryMapper.insert(history);
    }

    @Override
    public int addScore(EnumScoreType scoreType, Object param) {
        WxCUser wxCUser = null;
        WxCUserCar userCar = null;
        WxCUserBasicInfo userBasicInfo = null;
        Long userId = null;
        if (param instanceof WxCUser) {
            wxCUser = (WxCUser) param;
            userId = wxCUser.getId();
        }
        if (param instanceof WxCUserCar) {
            userCar = (WxCUserCar) param;
            userId = userCar.getCUserId();
        }
        if (param instanceof WxCUserBasicInfo) {
            userBasicInfo = (WxCUserBasicInfo) param;
            userId = userBasicInfo.getId();
        }
        WxCUserBasicInfo wxCUserBasicInfo = wxCUserBasicInfoMapper.selectById(userId);
        if (wxCUserBasicInfo != null && wxCUserBasicInfo.getStatus().equals(EnumCUserBasicInfoStatus.LOCKED.getCode())) {
            logger.info("会员权益被锁定:cUserId:" + userId);
            return 0;
        }
        switch (scoreType){
            case LOGIN: {
                return loginAddScore(wxCUser);
            }
            case BIND_CAR:{
                return bindCarAddScore(userCar);
            }
            case WECHAT_PERSION:{
                return personAddScore(wxCUser);
            }
            case WECHAT_PHONE:{
                return phoneAddScore(wxCUser);
            }
            case COMPLETE_INFO:{
                return infoAddScore(userBasicInfo);
            }

            default: {
            }
        }
        return 0;
    }

    @Override
    public int addScore2(EnumScoreType scoreType, Object param1, Object param2) {

        WxOrder order = null;
        WxCUserBasicInfo user = null;
        Long userId = null;
        if (param1 instanceof WxOrder) {
            order = (WxOrder) param1;
            userId = order.getCUserId();
        }
        if (param1 instanceof WxCUserBasicInfo) {
            user = (WxCUserBasicInfo) param1;
            userId = user.getId();
        }

        WxCUserBasicInfo wxCUserBasicInfo = wxCUserBasicInfoMapper.selectById(userId);
        if (wxCUserBasicInfo != null && wxCUserBasicInfo.getStatus().equals(EnumCUserBasicInfoStatus.LOCKED.getCode())) {
            logger.info("会员权益被锁定:cUserId:" + userId);
            return 0;
        }

        switch (scoreType){
            case CONSUMPTION: {
                Integer bussinessId = (Integer) param2;
                return payAddScore(order, bussinessId);
            }
            case MEM_IMPORT: {
                boolean bHaveCUser = (boolean)(param2);
                return memResetScore(user, bHaveCUser);
            }
            default:
                break;
        }
        return 0;
    }

    @Override
    public int reduceScore(EnumScoreType scoreType, Object param1, Object param2, Object param3) {
        WxCUserBasicInfo user = (WxCUserBasicInfo) param1;
        if (user != null && user.getStatus().equals(EnumCUserBasicInfoStatus.LOCKED.getCode())) {
            logger.info("会员权益被锁定:cUserId:" + user.getId());
            return 0;
        }
        switch (scoreType){
            case MEM_REDUCE: {
                String reason = (String)param2;
                Integer scoreNum = (Integer)param3;
                return memReduceScore(user, reason, scoreNum);
            }
            default:
                break;
        }
        return 0;
    }

    @Override
    public List<WxScoreRules> findList(WxScoreRules wxScoreRules) {
        return wxScoreRulesMapper.findList(wxScoreRules);
    }

    @Override
    public void updateCreditLocked(WxScoreRules wxScoreRules) {
        wxScoreRulesMapper.updateById(wxScoreRules);
        updateMerchantCreditLocked(wxScoreRules);
    }

    public void updateMerchantCreditLocked(WxScoreRules wxScoreRules) {
        WxMerchant wxMerchant = new WxMerchant();
        wxMerchant.setTenantId(wxScoreRules.getTenantId());
        wxMerchant.setStatus(wxScoreRules.getCreditLocked());
        wxMerchant.setUpdateDate(new Date());
        wxMerchantMapper.updateCreditLocked(wxMerchant);
    }
}
