package com.iformall.controller.datatower;

import com.github.pagehelper.PageInfo;
import com.iformall.annotation.SystemControllerLog;
import com.iformall.common.ErrorCode;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.domain.dto.WxCUserBasicInfoDto;
import com.iformall.domain.po.*;
import com.iformall.domain.po.base.BaseEntity;
import com.iformall.domain.vo.UserCountVo;
import com.iformall.domain.vo.UserStructureVo;
import com.iformall.enums.*;
import com.iformall.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Api(description = "会员洞察")
@RequestMapping("userAnalysis")
public class WxUserStructureController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxCUserBasicInfoService wxCUserBasicInfoService;

    @Autowired
    private WxCUserService wxCUserService;

    @Autowired
    private WxLevelConfigService wxLevelConfigService;

    @Autowired
    private WxCUserCarService wxCUserCarService;

    @Autowired
    private WxCUserTagsService wxCUserTagsService;

    @Autowired
    private WxUserChannelService wxUserChannelService;

    @Autowired
    private WxScoreRulesService wxScoreRulesService;

    /***************************会员结构*****************************/

    @ApiOperation("查询会员性别结构")
    @GetMapping("/findUserSexStructure")
    @SystemControllerLog(description = "会员管理-查询会员性别结构")
    public ResultData findUserSexStructure(Date startTime, Date endTime) {
        logger.debug("[" + getIpAddr() + "] WxUserStructureController::findUserSexStructure");
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(getTenantId());
        dto.setStartTime(startTime);
        dto.setEndTime(endTime);
        //保密
        dto.setSex(EnumCUserBaseInfoSex.UNKNOWN.getCode());
        long secrecy = wxCUserBasicInfoService.findCountBySex(dto);
        dto.setSex(EnumCUserBaseInfoSex.MALE.getCode());
        long boy = wxCUserBasicInfoService.findCountBySex(dto);
        dto.setSex(EnumCUserBaseInfoSex.FEMALE.getCode());
        long girl = wxCUserBasicInfoService.findCountBySex(dto);
        Long all = secrecy + boy + girl;
        List<UserStructureVo> vos = new ArrayList<>();
        vos.add(getVo(boy, all, "男", 1));
        vos.add(getVo(girl, all, "女", 2));
        vos.add(getVo(secrecy, all, "保密", 3));
        return new ResultData(vos);
    }

    @ApiOperation("查询会员年龄结构")
    @GetMapping("/findUserAgeStructure")
    @SystemControllerLog(description = "会员管理-查询会员年龄结构")
    public ResultData findUserAgeStructure(Date startTime, Date endTime) {
        logger.debug("[" + getIpAddr() + "] WxUserStructureController::findUserAgeStructure");
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(getTenantId());
        dto.setStartTime(startTime);
        dto.setEndTime(endTime);
        long all = wxCUserBasicInfoService.findCount(dto);
        List<UserStructureVo> vos = new ArrayList<>();
        Calendar c = Calendar.getInstance();
        for (EnumAgeInfo a : EnumAgeInfo.values()) {
            c.clear();
            c.setTime(new Date());
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            long count = getCountByAge(a, c, dto);
            vos.add(getVo(count, all, a.getDesc(), a.getSortNum()));
        }
        return new ResultData(vos);
    }

    @ApiOperation("查询会员成长值结构")
    @GetMapping("/findUserLevelStructure")
    @SystemControllerLog(description = "会员管理-查询会员成长值结构")
    public ResultData findUserLevelStructure(Date startTime, Date endTime) {
        logger.debug("[" + getIpAddr() + "] WxUserStructureController::findUserAgeStructure");
        WxLevelConfig wxLevelConfig = new WxLevelConfig();
        wxLevelConfig.setTenantId(getTenantId());
        wxLevelConfig.setSortColumns(BaseEntity.SortField.Points_ASC);
        List<WxLevelConfig> levelList = wxLevelConfigService.findList(wxLevelConfig);

        for( int i = 0; i < levelList.size(); i++) {

            WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
            dto.setTenantId(getTenantId());
            dto.setStartTime(startTime);
            dto.setEndTime(endTime);
            if (i + 1 < levelList.size()) {
                dto.setLevelStartScore(levelList.get(i).getPoints());
                dto.setLevelEndScore(levelList.get(i+1).getPoints());
            }else{
                dto.setLevelStartScore(levelList.get(i).getPoints());
            }

            long all = wxCUserBasicInfoService.findCountByScore(dto);

            levelList.get(i).setCount(all);
        }

        WxLevelConfig other = new WxLevelConfig();
        //没有等级的会员
        other.setLevel(WxLevelConfigService.DEFAULT_LEVEL);
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setStartTime(startTime);
        dto.setEndTime(endTime);
        other.setCount(wxCUserBasicInfoService.findCount(dto)
                - levelList.stream().map(WxLevelConfig::getCount).reduce(Long::sum).orElse(0L));

        levelList.add(other);
        return new ResultData(levelList);
    }

    @ApiOperation("查询会员绑车牌结构")
    @GetMapping("/findUserCarStructure")
    @SystemControllerLog(description = "会员管理-查询会员绑车牌结构")
    public ResultData findCarLevelStructure(Date startTime, Date endTime) {
        logger.debug("[" + getIpAddr() + "] WxUserStructureController::findCarLevelStructure");
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(getTenantId());
        dto.setStartTime(startTime);
        dto.setEndTime(endTime);
        long total = wxCUserBasicInfoService.findCount(dto);


        long userCountWithCar = wxCUserCarService.countUser(dto);
        Map userWithCar = new HashMap();
        userWithCar.put("title","已绑定车牌");
        userWithCar.put("count",userCountWithCar);


        long userCountWithoutCar = total-userCountWithCar;

        Map userWithoutCar = new HashMap();
        userWithoutCar.put("title","未绑定车牌");
        userWithoutCar.put("count",userCountWithoutCar);

        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);

        if(userCountWithoutCar + userCountWithCar>0) {
            userWithCar.put("percentage",nf.format(userCountWithCar/new Double(userCountWithoutCar + userCountWithCar).doubleValue()));
            userWithoutCar.put("percentage",nf.format(userCountWithoutCar/new Double(userCountWithoutCar + userCountWithCar).doubleValue()));
        } else {
            userWithCar.put("percentage","--");
            userWithoutCar.put("percentage","--");
        }

        List<Map> list = new ArrayList<>();
        list.add(userWithCar);
        list.add(userWithoutCar);
        return new ResultData(list);
    }


    @ApiOperation("查询会员手机品牌结构")
    @GetMapping("/findUserPhoneBandStructure")
    @SystemControllerLog(description = "会员管理-查询会员手机品牌结构")
    public ResultData findUserPhoneBandStructure(Date startTime, Date endTime) {
        logger.debug("[" + getIpAddr() + "] WxUserStructureController::findUserPhoneBandStructure");
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(getTenantId());
        dto.setStartTime(startTime);
        dto.setEndTime(endTime);
        long total = wxCUserBasicInfoService.findCount(dto);

        List<WxTags> tagList = new ArrayList<>();

        EnumTag[] tags = {EnumTag.ID_49,
                EnumTag.ID_50,
                EnumTag.ID_51,
                EnumTag.ID_52,
                EnumTag.ID_53,
                EnumTag.ID_54};

        for (int i = 0; i < tags.length; i++) {
            WxTags tag = new WxTags();
            tag.setName(tags[i].getMessage());
            tag.setCount(wxCUserTagsService.countUser(getTenantId(), tags[i].getCode(), startTime, endTime));
            tagList.add(tag);
            total -= tag.getCount();
        }

        WxTags tag = new WxTags();
        tag.setName("暂未获取");
        tag.setCount(total);
        tagList.add(tag);

        return new ResultData(tagList);
    }


    @ApiOperation("查询会员活跃结构")
    @GetMapping("/findUserActivityStructure")
    @SystemControllerLog(description = "会员管理-查询会员活跃结构")
    public ResultData findUserActivityStructure(Date startTime, Date endTime) {
        logger.debug("[" + getIpAddr() + "] WxUserStructureController::findUserActivityStructure");
        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(getTenantId());
        dto.setStartTime(startTime);
        dto.setEndTime(endTime);
        long total = wxCUserBasicInfoService.findCount(dto);

        List<WxTags> tagList = new ArrayList<>();

        EnumTag[] tags = {
                EnumTag.ID_112,
                EnumTag.ID_111,
                EnumTag.ID_110
        };

        for (int i = 0; i < tags.length; i++) {
            WxTags tag = new WxTags();
            tag.setName(tags[i].getMessage());
            tag.setCount(wxCUserTagsService.countUser(getTenantId(), tags[i].getCode(), startTime, endTime));
            tagList.add(tag);
            total -= tag.getCount();
        }

        WxTags tag = new WxTags();
        tag.setName("休眠");
        tag.setCount(total);
        tagList.add(tag);

        return new ResultData(tagList);
    }

    /********************************会员数据**************************************/

    private Date addDay(Date date , int addDayAmount) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, addDayAmount);
        Date result = c.getTime();
        return result;
    }

    private Date addMonth(Date date, int addMountAmount) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.MONTH, addMountAmount);
        Date result = c.getTime();
        return result;
    }

    private Date addYear(Date date, int addYearAmount) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.YEAR, addYearAmount);
        Date result = c.getTime();
        return result;
    }

    @ApiOperation("查询会员数量")
    @GetMapping("/findUserDataCount")
    @SystemControllerLog(description = "会员管理-查询会员数量")
    public ResultData findUserCount(Date startTime, Date endTime, Integer reportType) {
        logger.debug("[" + getIpAddr() + "] WxUserStructureController::findUserCount");


        //昨日同比
        Map<String, Object> map = new HashMap<>();

        WxCUserBasicInfoDto dto = new WxCUserBasicInfoDto();
        dto.setTenantId(getTenantId());
        dto.setEndTime(new Date());
        //微信用户数据
        long wxTotalCount = wxCUserService.findCount(dto);//总量
        //微信用户数据
        long memTotalCount = wxCUserBasicInfoService.findCount(dto);//总量

        map.put("wxTotalCount",wxTotalCount);
        map.put("memTotalCount",memTotalCount);

        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        Date today = c.getTime();
        dto.setStartTime(today);
        dto.setEndTime(null);
        long wxTodayCount = wxCUserService.findCount(dto);//今天新增
        long memTodayCount = wxCUserBasicInfoService.findCount(dto);//今天新增

        map.put("wxTodayCount",wxTodayCount);
        map.put("memTodayCount",memTodayCount);

        //昨日同比
        c.clear();
        c.setTime(today);
        c.add(Calendar.DAY_OF_YEAR, -1);
        dto.setStartTime(c.getTime());
        c.add(Calendar.DAY_OF_YEAR, 1);
        dto.setEndTime(c.getTime());
        long wxYesterdayCount = wxCUserService.findCount(dto);
        long memYesterdayCount = wxCUserBasicInfoService.findCount(dto);
        if (wxYesterdayCount > 0) {
            double yesterday = (double) (wxTodayCount - wxYesterdayCount) / wxYesterdayCount * 100;
            double zrhb = new BigDecimal(yesterday).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            map.put("wxhb", zrhb + "%");
        } else {
            map.put("wxhb", "--%");
        }
        if (memYesterdayCount > 0) {
            double yesterday = (double) (wxTodayCount - memYesterdayCount) / memYesterdayCount * 100;
            double zrhb = new BigDecimal(yesterday).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            map.put("memhb", zrhb + "%");
        } else {
            map.put("memhb", "--%");
        }

        if (startTime == null || endTime == null) {
            startTime = addMonth(new Date(), -1);
            endTime = new Date();
            reportType = EnumUserCountReportType.DAY.getCode();
        }

        dto.setTenantId(getTenantId());
        dto.setStartTime(startTime);
        dto.setEndTime(endTime);
        dto.setReportType(reportType);

        List<UserCountVo> wxCountList = new ArrayList<>();//每日新增会员数
        List<UserCountVo> wxCounts = wxCUserService.findCountHistory(dto);//每日新增会员数
        List<UserCountVo> memCountList = new ArrayList<>();//每日新增会员数
        List<UserCountVo> memCounts = wxCUserBasicInfoService.findCountHistory(dto);//每日新增会员数

        SimpleDateFormat sdf;
        SimpleDateFormat fsdf;
        if (reportType.equals(EnumUserCountReportType.YEAR.getCode())) {
            sdf = new SimpleDateFormat("yyyy");
            fsdf = new SimpleDateFormat("yyyy");
        }else if (reportType.equals(EnumUserCountReportType.MONTH.getCode())) {
            sdf = new SimpleDateFormat("yyyy-MM");
            fsdf = new SimpleDateFormat("yyyy-MM");
        }else {
            sdf = new SimpleDateFormat("yyyy-MM-dd");
            fsdf = new SimpleDateFormat("MM-dd");
        }

        Date curTime = new Date(startTime.getTime());
        do {
            UserCountVo wxUc = new UserCountVo();
            UserCountVo memUc = new UserCountVo();
            wxUc.setReportTime(fsdf.format(curTime));
            memUc.setReportTime(fsdf.format(curTime));

            final Date ct = new Date(curTime.getTime());

            if (ct.before(new Date()) || ct.equals(new Date())) {
                //用户
                Optional<UserCountVo> opWxUserCountVo =
                        wxCounts.stream().filter(md -> md.getReportTime().equals(sdf.format(ct))).findFirst();
                if (opWxUserCountVo.isPresent()) {
                    wxUc.setIncCount(opWxUserCountVo.get().getIncCount());
                    wxUc.setTotalCount(opWxUserCountVo.get().getTotalCount());
                } else {
                    wxUc.setIncCount(0L);
                    wxUc.setTotalCount(0L);
                }

                //会员
                Optional<UserCountVo> opMemUserCountVo =
                        memCounts.stream().filter(md -> md.getReportTime().equals(sdf.format(ct))).findFirst();
                if (opMemUserCountVo.isPresent()) {
                    memUc.setIncCount(opMemUserCountVo.get().getIncCount());
                    memUc.setTotalCount(opMemUserCountVo.get().getTotalCount());
                } else {
                    memUc.setIncCount(0L);
                    memUc.setTotalCount(0L);
                }
            }
            memCountList.add(memUc);
            wxCountList.add(wxUc);
            if (reportType.equals(EnumUserCountReportType.YEAR.getCode())) {
                curTime = addYear(curTime, 1);
            } else if (reportType.equals(EnumUserCountReportType.MONTH.getCode())) {
                curTime = addMonth(curTime, 1);
            } else {
                curTime = addDay(curTime, 1);
            }

        }while (curTime.before(endTime) || curTime.equals(endTime));


        if (wxCountList.size() > 0
                && wxCountList.get(0).getTotalCount() != null
                && wxCountList.get(0).getTotalCount() == 0) {
            WxCUserBasicInfoDto pdto = new WxCUserBasicInfoDto();
            pdto.setTenantId(getTenantId());
            pdto.setEndTime(startTime);
            wxCountList.get(0).setTotalCount(wxCUserService.findCount(pdto));
        }
        for (int i = 1; i < wxCountList.size(); i++){
            if (wxCountList.get(i).getTotalCount() != null &&
                    wxCountList.get(i-1).getTotalCount() != null &&
                    wxCountList.get(i).getTotalCount() < wxCountList.get(i-1).getTotalCount()){
                wxCountList.get(i).setTotalCount(wxCountList.get(i-1).getTotalCount());
            }
        }

        if (memCountList.size() > 0
                && memCountList.get(0).getTotalCount() != null
                && memCountList.get(0).getTotalCount() == 0) {
            WxCUserBasicInfoDto pdto = new WxCUserBasicInfoDto();
            pdto.setTenantId(getTenantId());
            pdto.setEndTime(startTime);
            memCountList.get(0).setTotalCount(wxCUserBasicInfoService.findCount(pdto));
        }
        for (int i = 1; i < memCountList.size(); i++){
            if ( memCountList.get(i).getTotalCount() != null &&
                    memCountList.get(i-1).getTotalCount() != null &&
                    memCountList.get(i).getTotalCount() < memCountList.get(i-1).getTotalCount()){
                memCountList.get(i).setTotalCount(memCountList.get(i-1).getTotalCount());
            }
        }

        map.put("wxCountList", wxCountList);//累计/新增用户列表（ 日期和数量list）
        map.put("memCountList", memCountList);//累计/新增会员列表（ 日期和数量list）

        return new ResultData(map);
    }


    @ApiOperation("拓客分析")
    @GetMapping("/findUserByChannel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)})
    @SystemControllerLog(description = "会员管理-拓客分析")
    public ResultData findUserByChannel(@ModelAttribute WxCUser wxCUser,
                                        Integer pageNum, Integer pageSize) {
        logger.debug("[" + getIpAddr() + "] WxUserStructureController::findUserByChannel");
        List<String> sceneList = null;
        if (StringUtils.isNotBlank(wxCUser.getChannelName())) {
            WxUserChannel c = new WxUserChannel();
            c.setChannelName(wxCUser.getChannelName());
            PageInfo<WxUserChannel> page = wxUserChannelService.listAsPage(c, 1, 100);
            if (page.getSize() > 0) {
                sceneList = new ArrayList<>();
                for (WxUserChannel wuc : page.getList()) {
                    sceneList.add(wuc.getSceneAddress());
                }
            }
        }
        wxCUser.setSceneList(sceneList);
        PageInfo<WxCUser> page = wxCUserService.listByChannel(wxCUser, pageNum, pageSize);
        for (WxCUser u : page.getList()) {
            WxUserChannel c = new WxUserChannel();
            c.setSceneAddress(u.getSceneAddress());
            PageInfo<WxUserChannel> uc = wxUserChannelService.listAsPage(c, 1, 1);
            if (uc.getSize() > 0) {
                u.setChannelName(uc.getList().get(0).getChannelName());
                u.setSceneDescription(uc.getList().get(0).getDescription());
            } else {
                u.setChannelName("其他来源");
                u.setSceneDescription("不详");
            }
        }

        return new ResultData(page);
    }

    @ApiOperation("获取用户所有渠道")
    @GetMapping("/findUserStructureByChannel")
    @SystemControllerLog(description = "会员管理-获取用户所有渠道")
    public ResultData findUserStructureByChannel(@ModelAttribute WxCUser wxCUser) {
        logger.debug("[" + getIpAddr() + "] WxUserStructureController::findUserStructureByChannel");
        List<WxUserChannel> channelStructureList = new ArrayList<>();
        List<WxUserChannel> senceStructureList = new ArrayList<>();

        List<WxUserChannel> channels = wxUserChannelService.findDistinctChannel();
        for (WxUserChannel w : channels) {
            WxUserChannel c = new WxUserChannel();
            c.setChannelName(w.getChannelName());
            PageInfo<WxUserChannel> page = wxUserChannelService.listAsPage(c, 1, 1000);
            if (page.getSize() > 0) {
                List<String> sceneList = new ArrayList<>();
                for (WxUserChannel uc : page.getList()) {
                    List<String> scene = new ArrayList<>();
                    scene.add(uc.getSceneAddress());
                    wxCUser.setSceneList(scene);
                    WxUserChannel senceStructure = new WxUserChannel();
                    senceStructure.setDescription(uc.getDescription());
                    senceStructure.setCount(wxCUserService.countByChannel(wxCUser));
                    senceStructureList.add(senceStructure);
                    sceneList.add(uc.getSceneAddress());
                }

                wxCUser.setSceneList(sceneList);
                WxUserChannel channelStructure = new WxUserChannel();
                channelStructure.setChannelName(w.getChannelName());
                channelStructure.setCount(wxCUserService.countByChannel(wxCUser));
                channelStructureList.add(channelStructure);
            }
        }

        HashMap result = new HashMap();
        Collections.sort(senceStructureList, (s1,s2) -> ((int)(s2.getCount()-s1.getCount())));

        result.put("channelList",channelStructureList);
        result.put("senceList",senceStructureList.subList(0,10));
        return new ResultData(result);
    }



    @ApiOperation("获取用户所有渠道")
    @GetMapping("/findAllUserChannel")
    @SystemControllerLog(description = "会员管理-获取用户所有渠道")
    public ResultData findAllUserChannel() {
        logger.debug("[" + getIpAddr() + "] WxUserStructureController::findAllUserChannel");
        List<WxUserChannel> channels = wxUserChannelService.findDistinctChannel();
        List<String> vos = new ArrayList<>();
        for (WxUserChannel w : channels) {
            vos.add(w.getChannelName());
        }
        return new ResultData(vos);
    }


    private long getCountByAge(EnumAgeInfo a, Calendar c, WxCUserBasicInfoDto dto) {
        if (a.getStart() != 0 || a.getEnd() != 0) {
            c.add(Calendar.YEAR, -a.getEnd());
            Date startTime = c.getTime();
            c.clear();
            c.setTime(startTime);
            c.add(Calendar.YEAR, a.getEnd() - a.getStart());
            Date endTime = c.getTime();
            dto.setBirthStartTime(startTime);
            dto.setBirthEndTime(endTime);
        } else {

            dto.setBirthStartTime(null);
            dto.setBirthEndTime(null);
        }

        return wxCUserBasicInfoService.findCountByAge(dto);
    }

    private UserStructureVo getVo(long count, long all, String name, Integer num) {
        UserStructureVo vo = new UserStructureVo();
        vo.setSortNum(num);
        vo.setName(name);
        vo.setCount(count);
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);//控制保留小数点后几位，2：表示保留2位小数点
        if (all > 0) {
            vo.setPercentage(nf.format(new Long(count).doubleValue() / new Long(all).doubleValue()));
        } else {
            vo.setPercentage("0.00%");
        }
        return vo;
    }

    // 成长值扣除
    @ApiOperation(value = "用户成长值扣减", notes = "{\"userId\":\"Long\", \"reason\":\"String\", \"score\":\"Integer\"}")
    @PostMapping("/scoreReduce")
    @SystemControllerLog(description = "会员管理-用户成长值扣减")
    public ResultData scoreReduce(@RequestBody Map<String, String> params) {
        logger.debug("[" + getIpAddr() + "] WxUserStructureController::scoreReduce");

        String userIdStr = params.get("userId");
        String reason = params.get("reason");
        String scoreStr = params.get("score");
        if (StringUtils.isBlank(userIdStr)) {
            logger.error("userId为空:" + userIdStr);
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "userId为空");
        }
        if (StringUtils.isBlank(reason)) {
            logger.error("reason为空:" + reason);
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "reason为空");
        }
        if (StringUtils.isBlank(scoreStr)) {
            logger.error("score为空:" + scoreStr);
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "score为空");
        }

        Long userId = null;
        Integer score = null;

        try {
            userId = Long.valueOf(userIdStr);
            score = Integer.valueOf(scoreStr);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if(userId == null || userId == 0) {
            logger.error(ErrorCode.USER_IS_EMPTY.getMessage());
            return new ResultData(ErrorCode.USER_IS_EMPTY);
        }
        if(score == null ) {
            logger.error(ErrorCode.SYS_PARAMETER_NOT_NULL.getMessage());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "score不能为空");
        }

        // 1. 检查用户积分
        WxCUserBasicInfo info = wxCUserBasicInfoService.getById(userId);
        if(info == null) {
            logger.error(ErrorCode.USER_IS_EMPTY.getMessage());
            return new ResultData(ErrorCode.USER_IS_EMPTY);
        }
        info.setPoins(info.getPoins() == null ? 0 : info.getPoins());
        if(info.getPoins() < score) {
            logger.error(ErrorCode.MEM_SCORE_NOT_ENOUGH.getMessage());
            return new ResultData(ErrorCode.MEM_SCORE_NOT_ENOUGH);
        }
        // 2. 扣减积分
        wxScoreRulesService.reduceScore(EnumScoreType.MEM_REDUCE, info, reason, score);

        return new ResultData();
    }


}
