package com.zd.exam.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zd.common.core.domain.R;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.SecurityUtils;
import com.zd.common.core.utils.SpringUtils;
import com.zd.common.core.utils.StringUtils;
import com.zd.common.datascope.annotation.DataScope;
import com.zd.common.security.service.TokenService;
import com.zd.common.security.utils.SaveUtil;
import com.zd.exam.domain.*;
import com.zd.exam.domain.dto.ElPointsRecordDTO;
import com.zd.exam.domain.vo.*;
import com.zd.common.core.enums.PointRecordType;
import com.zd.exam.mapper.*;
import com.zd.exam.service.IElPointsRecordService;
import com.zd.system.api.domain.SysUser;
import com.zd.system.api.face.factory.RemoteFaceFallbackFactory;
import io.netty.util.internal.StringUtil;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;


/**
 * 用户积分记录Service业务层处理
 *
 * @author zd
 * @date 2021-09-07
 */
@Service
public class ElPointsRecordServiceImpl implements IElPointsRecordService {
    @Autowired
    private ElPointsRecordMapper elPointsRecordMapper;

    @Autowired
    private ElPointsLogInfoMapper elPointsLogInfoMapper;

    @Autowired
    private ElPassMarkconfigMapper elPassMarkconfigMapper;

    @Autowired
    private ElPointOrderMapper elPointOrderMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ElPointTradeNoMapper elPointTradeNoMapper;

    private static final Logger log = LoggerFactory.getLogger(ElPointsRecordServiceImpl.class);

    /**
     * 创建积分记录， 默认不记录创建人信息
     *
     * @param joinUserId 积分关联用户
     * @param points     积分变动
     * @param model      行为 参考字典表
     * @param recordType 记录类型
     * @param remark     详情
     * @return
     */
    @Override
    public Boolean createRecord(Long joinUserId, Long points, Integer model, PointRecordType recordType, String remark) {

        return createRecord(joinUserId, points, model, recordType, remark, false);
    }

    /**
     * 创建积分记录
     *
     * @param joinUserId 积分关联用户
     * @param points     积分变动
     * @param model      行为 参考字典表
     * @param recordType 记录类型
     * @param f          是否设置创建人信息
     * @param remark     详情
     * @return
     */
    @Override
    public Boolean createRecord(Long joinUserId, Long points, Integer model, PointRecordType recordType, String remark, Boolean f) {
        Assert.notNull(recordType, "recordType：记录类型不能为空！");
        if (PointRecordType.USE.equals(recordType)) {
            Assert.isTrue(points <= 0, "积分变动错误,请检查积分值！");
        } else if (PointRecordType.GET.equals(recordType)) {
            Assert.isTrue(points >= 0, "积分变动错误,请检查积分值！");
        } else {
            return false;
        }
        //构建积分记录保存对象
        ElPointsRecord pointsRecord = new ElPointsRecordDTO();
        //积分需要修改的代码
//        pointsRecord.setPoints(points);
//        pointsRecord.setJoinUserId(joinUserId);
//        pointsRecord.setMode(model);
//        pointsRecord.setRemark(remark);
//        pointsRecord.setRecordType(recordType);
//        if (f) {
//            //如果是后台行为没有当前用户会报错，所以f给false
//            pointsRecord.setCreateBy(SecurityUtils.getUsername());
//            pointsRecord.setUserId(SecurityUtils.getUserId());
//            SysUser sysUser = SpringUtils.getBean(TokenService.class).getLoginUser().getSysUser();
//            pointsRecord.setDeptId(sysUser.getDeptId());
//            pointsRecord.setDeptName(sysUser.getDeptName());
//        }
        return insertElPointsRecord(pointsRecord) == 1;
    }


    /**
     * 查询用户积分记录
     *
     * @param id 用户积分记录主键
     * @return 用户积分记录
     */
    @Override
    public ElPointsRecord selectElPointsRecordById(Long id) {
        return elPointsRecordMapper.selectElPointsRecordById(id);
    }

    /**
     * 查询用户积分记录列表
     *
     * @param elPointsRecord 用户积分记录
     * @return 用户积分记录
     */
    @Override
    public List<ElPointsRecord> selectElPointsRecordList(ElPointsRecord elPointsRecord) {
        return elPointsRecordMapper.selectElPointsRecordList(elPointsRecord);
    }

    /**
     * 查询用户积分记录列表VO
     *
     * @param elPointsRecord 用户积分记录
     * @return 用户积分记录
     */
    @Override
    @DataScope(deptAlias = "u" , permi = PerPrefix.POINTS_RECORD)
    public List<ElPointsRecordListVO> selectElPointsRecordVOList(ElPointsRecordDTO elPointsRecord) {
        return elPointsRecordMapper.selectElPointsRecordVOList(elPointsRecord);
    }


    /**
     * 查询用户积分记录列表VO
     *
     * @param elPointsRecord 用户积分记录
     * @return 用户积分记录
     */
    @Override
    public Integer selectElCountPointsRecord(ElPointsRecordDTO elPointsRecord) {
        return elPointsRecordMapper.selectElCountPointsRecord(elPointsRecord);
    }

    /**
     * 新增用户积分记录
     *
     * @param elPointsRecord 用户积分记录
     * @return 结果
     */
    @Override
    public int insertElPointsRecord(ElPointsRecord elPointsRecord) {
        elPointsRecord.setCreateTime(DateUtils.getNowDate());
        return elPointsRecordMapper.insertElPointsRecord(elPointsRecord);
    }

    /**
     * 修改用户积分记录
     *
     * @param elPointsRecord 用户积分记录
     * @return 结果
     */
    @Override
    public int updateElPointsRecord(ElPointsRecord elPointsRecord) {
        elPointsRecord.setUpdateTime(DateUtils.getNowDate());
        return elPointsRecordMapper.updateElPointsRecord(elPointsRecord);
    }

    /**
     * 初始化信用积分，用于证书获取后，给予一个基础分值。
     *
     * @param initMap 初始化信用积分，用于证书获取后，给予一个基础分值。
     * @return 结果
     */
    @Override
//    @Transactional(rollbackFor = Exception.class)
    public int initCreditPoints(Map <String,Object> initMap) {
        ElPointsRecord elPointsRecord = new ElPointsRecord();
        elPointsRecord.setJoinUserId(Long.parseLong(initMap.get("joinUserId")+""));
        List<ElPointsRecord> elPointsRecordsList = elPointsRecordMapper.selectElPointsRecordList(elPointsRecord);
        int flag=500;
        //查看积分列表当前用户是否存在
        if(elPointsRecordsList.size()==0){
            ElPassMarkconfigVO elPassMarkconfigVO = getPassMarkconfig();
            if(elPassMarkconfigVO==null){
                throw new ServiceException("获取配置项错误！！");
            }
            int maxCount = 0;
            int nowCount = 0;
            if(elPassMarkconfigVO.getGainSafeCert()!=-1){
                if(elPassMarkconfigVO.getGainSafeCert()==Integer.parseInt(initMap.get("gainSafeCert")+"")){
                    nowCount++;
                }
                maxCount++;
            }
            if(elPassMarkconfigVO.getGainSubSafeCert()!=-1){
                if(elPassMarkconfigVO.getGainSubSafeCert()==Integer.parseInt(initMap.get("gainSubSafeCert")+"")){
                    nowCount++;
                }
                maxCount++;
            }
            if(maxCount!=0){
                if(nowCount==maxCount){
                    //获取配置项的合格分
                    Long creditScore = elPassMarkconfigVO.getPassMark();
                    Long totalPoints = creditScore;
                    //添加个人积分列表统计数据
                    ElPointsRecord elPointsRecordNew = new ElPointsRecord();
                    elPointsRecordNew.setNickName(initMap.get("nickName")+"");
                    elPointsRecordNew.setJoinUserId(Long.parseLong(initMap.get("joinUserId")+""));
                    elPointsRecordNew.setUserName(initMap.get("userName")+"");
                    elPointsRecordNew.setCreditScore(creditScore);
                    elPointsRecordNew.setBonusPoints(0L);
                    elPointsRecordNew.setDeductPoints(0L);
                    elPointsRecordNew.setTotalPoints(totalPoints);
                    elPointsRecordNew.setCreateBy("系统");
                    elPointsRecordNew.setCreateTime(new Date());
                    elPointsRecordMapper.insertElPointsRecord(elPointsRecordNew);
                    //给个人积分日志插入数据
                    ElPointsLoginfo elPointsLoginfo = new ElPointsLoginfo();
                    elPointsLoginfo.setPointsId(elPointsRecordNew.getId());
                    elPointsLoginfo.setPointsType(1L);
                    elPointsLoginfo.setPoints(creditScore);
                    elPointsLoginfo.setSurplusPoints(creditScore);
                    elPointsLoginfo.setMessageContent(initMap.get("reason")+"");
                    elPointsLoginfo.setCreateBy("系统");
                    elPointsLoginfo.setCreateTime(new Date());
                    elPointsLogInfoMapper.insertElPointsLogInfo(elPointsLoginfo);
                    flag = 200;
                    return flag;
                }
            }
        }
        return flag;
    }

    /**
     * 根据用户id，修改积分内容
     *
     * @param recoveryMap 根据用户id，修改积分内容
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int recoveryPoints(Map <String,Object> recoveryMap) {
        ElPointsRecord elPointsRecord = new ElPointsRecord();
        elPointsRecord.setJoinUserId(Long.parseLong(recoveryMap.get("joinUserId")+""));
        List<ElPointsRecord> elPointsRecordsList = elPointsRecordMapper.selectElPointsRecordList(elPointsRecord);
        int flag=500;
        //查看积分列表当前用户是否存在
        if(elPointsRecordsList.size()>0){
            ElPassMarkconfigVO elPassMarkconfigVO = getPassMarkconfig();
            if(elPassMarkconfigVO==null){
                throw new ServiceException("获取配置项错误！！");
            }
            //计算，需要把信用分丢失的计算出来，然后补回去，写入日志
            ElPointsRecord elPointsRecordOld = elPointsRecordsList.get(0);
            Long creditScore = elPassMarkconfigVO.getPassMark()-elPointsRecordOld.getCreditScore();
            Long totalPoints = elPointsRecordOld.getTotalPoints()+creditScore;
            //修改个人积分列表统计数据
            ElPointsRecord elPointsRecordNew = new ElPointsRecord();
            elPointsRecordNew.setId(elPointsRecordOld.getId());
            elPointsRecordNew.setCreditScore(elPointsRecordOld.getCreditScore()+creditScore);
            elPointsRecordNew.setTotalPoints(totalPoints);
            elPointsRecordNew.setUpdateBy("系统");
            elPointsRecordNew.setUpdateTime(new Date());
            elPointsRecordMapper.updateElPointsRecord(elPointsRecordNew);
            //给个人积分日志插入数据
            ElPointsLoginfo elPointsLoginfo = new ElPointsLoginfo();
            elPointsLoginfo.setPointsId(elPointsRecordNew.getId());
            elPointsLoginfo.setPointsType(1L);
            elPointsLoginfo.setPoints(creditScore);
            elPointsLoginfo.setSurplusPoints(elPointsRecordOld.getCreditScore()+creditScore);
            elPointsLoginfo.setMessageContent(recoveryMap.get("reason")+"");
            if(tokenService.getLoginUser()!=null){
                elPointsLoginfo.setCreateBy(tokenService.getLoginUser().getNickName());
            }else{
                elPointsLoginfo.setCreateBy("系统");
            }
            elPointsLoginfo.setCreateTime(new Date());
            elPointsLogInfoMapper.insertElPointsLogInfo(elPointsLoginfo);
            flag = 200;
            return flag;
        }
        return flag;
    }


    /**
     * 根据积分类型，扣除积分相关内容
     *
     * @param deductionMap 根据积分类型，扣除积分相关内容
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deductionPoints(Map <String,Object> deductionMap) {
        ElPointsRecord elPointsRecord = new ElPointsRecord();
        elPointsRecord.setJoinUserId(Long.parseLong(deductionMap.get("joinUserId")+""));
        List<ElPointsRecord> elPointsRecordsList = elPointsRecordMapper.selectElPointsRecordList(elPointsRecord);
        int flag=500;
        //查看积分列表当前用户是否存在
        if(elPointsRecordsList.size()>0){
            //修改日志列表，计算分值
            ElPointsRecord elPointsRecordOld = elPointsRecordsList.get(0);
            Long creditScore = 0L;
            Long totalPoints = 0L;
            if("1".equals(deductionMap.get("pointsType")+"")){
                creditScore = elPointsRecordOld.getCreditScore()-Long.parseLong(deductionMap.get("deductPoints")+"");
                totalPoints = elPointsRecordOld.getTotalPoints()-Long.parseLong(deductionMap.get("deductPoints")+"");
                if(creditScore<0){
                    creditScore = 0L;
                    totalPoints = elPointsRecordOld.getBonusPoints();
                }
                elPointsRecordOld.setCreditScore(creditScore);
            }else if("2".equals(deductionMap.get("pointsType")+"")){
                creditScore = elPointsRecordOld.getBonusPoints()-Long.parseLong(deductionMap.get("deductPoints")+"");
                if(creditScore<0){
                    throw new ServiceException("奖励积分余额不足!!");
                }
                totalPoints = elPointsRecordOld.getTotalPoints()-Long.parseLong(deductionMap.get("deductPoints")+"");
                elPointsRecordOld.setBonusPoints(creditScore);
            }

            elPointsRecordOld.setTotalPoints(totalPoints);
            elPointsRecordOld.setUpdateBy("系统");
            elPointsRecordOld.setUpdateTime(new Date());
            elPointsRecordMapper.updateElPointsRecord(elPointsRecordOld);
            //给个人积分日志插入数据
            ElPointsLoginfo elPointsLoginfo = new ElPointsLoginfo();
            elPointsLoginfo.setPointsId(elPointsRecordOld.getId());
            elPointsLoginfo.setPointsType(Long.parseLong(deductionMap.get("pointsType")+""));
            elPointsLoginfo.setPoints(-Long.parseLong(deductionMap.get("deductPoints")+""));
            elPointsLoginfo.setSurplusPoints(creditScore);
            elPointsLoginfo.setMessageContent(deductionMap.get("reason")+"");
            if(tokenService.getLoginUser()!=null){
                elPointsLoginfo.setCreateBy(tokenService.getLoginUser().getNickName());
            }else{
                elPointsLoginfo.setCreateBy("系统");
            }
            elPointsLoginfo.setCreateTime(new Date());
            elPointsLogInfoMapper.insertElPointsLogInfo(elPointsLoginfo);
            flag = 200;
            return flag;
        }
        return 0;
    }


    /**
     * 获取奖励积分
     *
     * @param obtainBonusPoints 获取奖励积分
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int obtainBonusPoints(Map <String,Object> obtainBonusPoints) {
        ElPointsRecord elPointsRecord = new ElPointsRecord();
        elPointsRecord.setJoinUserId(Long.parseLong(obtainBonusPoints.get("joinUserId")+""));
        List<ElPointsRecord> elPointsRecordsList = elPointsRecordMapper.selectElPointsRecordList(elPointsRecord);
        int flag=500;
        //查看积分列表当前用户是否存在
        if(elPointsRecordsList.size()>0){
            //修改日志列表，计算分值
            ElPointsRecord elPointsRecordOld = elPointsRecordsList.get(0);
            Long creditScore = elPointsRecordOld.getBonusPoints()+Long.parseLong(obtainBonusPoints.get("deductPoints")+"");
            Long totalPoints = elPointsRecordOld.getTotalPoints()+Long.parseLong(obtainBonusPoints.get("deductPoints")+"");
            elPointsRecordOld.setBonusPoints(creditScore);
            elPointsRecordOld.setTotalPoints(totalPoints);
            elPointsRecordOld.setUpdateBy("系统操作");
            elPointsRecordOld.setUpdateTime(new Date());
            elPointsRecordMapper.updateElPointsRecord(elPointsRecordOld);
            //给个人积分日志插入数据
            ElPointsLoginfo elPointsLoginfo = new ElPointsLoginfo();
            elPointsLoginfo.setPointsId(elPointsRecordOld.getId());
            elPointsLoginfo.setPointsType(2L);
            elPointsLoginfo.setPoints(Long.parseLong(obtainBonusPoints.get("deductPoints")+""));
            elPointsLoginfo.setSurplusPoints(creditScore);
            elPointsLoginfo.setMessageContent(obtainBonusPoints.get("reason")+"");
            if(obtainBonusPoints.get("channelType")!=null){
                elPointsLoginfo.setChannelType(obtainBonusPoints.get("channelType")+"");
            }
            if(obtainBonusPoints.get("channelSource")!=null){
                elPointsLoginfo.setChannelSource(Integer.parseInt(obtainBonusPoints.get("channelSource")+""));
            }
            elPointsLoginfo.setCreateBy("系统");
            elPointsLoginfo.setCreateTime(new Date());
            elPointsLogInfoMapper.insertElPointsLogInfo(elPointsLoginfo);
            flag = 200;
            return flag;
        }
        return 0;
    }


    /**
     * 获取上月未违规记录列表
     *
     * @param obtainBonusPoints 获取上月未违规记录列表
     * @return 结果
     */
    @Override
    public List<ElPointsRecord> getLastMonthViolation(Map <String,Object> obtainBonusPoints) {
        ElPointsRecord elPointsRecord = new ElPointsRecord();
        return elPointsRecordMapper.getLastMonthViolation(elPointsRecord);
    }

    //获取信用积分配置表初始配置数据。
    public ElPassMarkconfigVO getPassMarkconfig(){
        List<ElPassMarkconfigVO> elPassMarkconfigVOS = elPassMarkconfigMapper.selectElPassMarkconfigList(new ElPassMarkconfig());
        if(elPassMarkconfigVOS.size()>0){
            return elPassMarkconfigVOS.get(0);
        }
        return null;
    }

    /**
     * 批量删除用户积分记录
     *
     * @param ids 需要删除的用户积分记录主键
     * @return 结果
     */
    @Override
    public int deleteElPointsRecordByIds(Long[] ids) {
        return elPointsRecordMapper.deleteElPointsRecordByIds(ids);
    }

    /**
     * 删除用户积分记录信息
     *
     * @param id 用户积分记录主键
     * @return 结果
     */
    @Override
    public int deleteElPointsRecordById(Long id) {
        return elPointsRecordMapper.deleteElPointsRecordById(id);
    }

    @Override
    public List <ElPointsLoginfo> getPointsLoglist(ElPointsLoginfoVO elPointsLoginfoVO) {
        return elPointsLogInfoMapper.getPointsLoglist(elPointsLoginfoVO);
    }

    @Override
    public List <ElPointsLoginfo> getMyPointsLoglist(ElPointsLoginfoVO elPointsLoginfoVO) {
        List <ElPointsLoginfo> elPointsLoginfoList = elPointsLogInfoMapper.getPointsLoglist(elPointsLoginfoVO);
        return elPointsLoginfoList;
    }

    @Override
    public ElPointsCountVO monthAllCount(ElPointsLoginfoVO elPointsLoginfoVO) {
        ElPointsRecord elPointsRecord = new ElPointsRecord();
        elPointsRecord.setJoinUserId(SecurityUtils.getUserId());
        List<ElPointsRecord> elPointsRecordList = elPointsRecordMapper.selectElPointsRecordList(elPointsRecord);
        if(elPointsRecordList.size()>0){
            ElPointsRecord elPointsRecordNew = elPointsRecordList.get(0);
            elPointsLoginfoVO.setPointsId(elPointsRecordNew.getId());
            ElPointsCountVO elPointsCountVO = elPointsLogInfoMapper.monthAllCount(elPointsLoginfoVO);
            if(elPointsCountVO==null || (elPointsCountVO.getDeductPoints()==null && elPointsCountVO.getObtainPoints()==null)){
                elPointsCountVO = new ElPointsCountVO();
                elPointsCountVO.setYearMonth("");
                elPointsCountVO.setDeductPoints(0L);
                elPointsCountVO.setObtainPoints(0L);
                return elPointsCountVO;
            }
            return elPointsCountVO;
        }else{
            ElPointsCountVO elPointsCountVO = new ElPointsCountVO();
            elPointsCountVO.setYearMonth("");
            elPointsCountVO.setDeductPoints(0L);
            elPointsCountVO.setObtainPoints(0L);
            return elPointsCountVO;
        }
    }

    @Override
    public List <ElPointsCountVO> monthCountPoints(ElPointsLoginfoVO elPointsLoginfoVO) {
//        ElPointsRecord elPointsRecord = new ElPointsRecord();
//        elPointsRecord.setJoinUserId(SecurityUtils.getUserId());
//        List<ElPointsRecord> elPointsRecordList = elPointsRecordMapper.selectElPointsRecordList(elPointsRecord);
//        if(elPointsRecordList.size()>0){
//            ElPointsRecord elPointsRecordNew = elPointsRecordList.get(0);
//            elPointsLoginfoVO.setPointsId(elPointsRecordNew.getId());
            List <ElPointsCountVO> elPointsCountVOList = elPointsLogInfoMapper.monthCountPoints(elPointsLoginfoVO);

            Optional.ofNullable(elPointsCountVOList).orElseGet(Collections::emptyList).stream().forEach(a->{
                elPointsLoginfoVO.setYearMonth(a.getYearMonth());
                a.setElPointsLoginfoList(elPointsLogInfoMapper.getPointsLoglist(elPointsLoginfoVO));
            });
            if(elPointsCountVOList.size()==0){
                elPointsCountVOList = new ArrayList <>();
                ElPointsCountVO elPointsCountVO = new ElPointsCountVO();
                elPointsCountVO.setYearMonth(elPointsLoginfoVO.getYearMonth().replace("-","年")+"月");
                elPointsCountVO.setObtainPoints(0L);
                elPointsCountVO.setDeductPoints(0L);
                elPointsCountVOList.add(elPointsCountVO);
            }
            return elPointsCountVOList;
    }


    @Override
    public ElUserPointsLoginfoVO getMyPointsLogInfo(ElPointsLoginfoVO elPointsLoginfoVO) {
        ElPointsRecordDTO elPointsRecord = new ElPointsRecordDTO();
        elPointsRecord.setJoinUserId(tokenService.getLoginUser().getUserid());
        elPointsRecord.setPointsType(elPointsLoginfoVO.getPointsType());
        List<ElPointsRecordListVO> elPointsRecordListVOList = elPointsRecordMapper.selectElPointsRecordVOList(elPointsRecord);
        if(elPointsRecordListVOList.size()>0){
            ElUserPointsLoginfoVO elUserPointsLoginfoVO = new ElUserPointsLoginfoVO();
            elUserPointsLoginfoVO.setNickName(tokenService.getLoginUser().getSysUser().getNickName());
            elUserPointsLoginfoVO.setDeptName(elPointsRecordListVOList.get(0).getDeptName());
            elUserPointsLoginfoVO.setCreditScore(elPointsRecordListVOList.get(0).getCreditScore());
            elUserPointsLoginfoVO.setBonusPoints(elPointsRecordListVOList.get(0).getBonusPoints());
            elUserPointsLoginfoVO.setObtainPoints(elPointsRecordListVOList.get(0).getAllBonusPoints());
            elUserPointsLoginfoVO.setExchangePoints(elPointsRecordListVOList.get(0).getConsumeBonusPoints());
            elUserPointsLoginfoVO.setSurplusPoints(elPointsRecordListVOList.get(0).getBonusPoints());
            elUserPointsLoginfoVO.setAvatar(elPointsRecordListVOList.get(0).getAvatar());
            elUserPointsLoginfoVO.setUserStatus(elPointsRecordListVOList.get(0).getUserStatus());
            return elUserPointsLoginfoVO;
        }else{
            ElUserPointsLoginfoVO elUserPointsLoginfoVO = new ElUserPointsLoginfoVO();
            elUserPointsLoginfoVO.setNickName(tokenService.getLoginUser().getSysUser().getNickName());
            elUserPointsLoginfoVO.setDeptName(tokenService.getLoginUser().getSysUser().getDeptName());
            elUserPointsLoginfoVO.setCreditScore(0L);
            elUserPointsLoginfoVO.setBonusPoints(0L);
            elUserPointsLoginfoVO.setObtainPoints(0);
            elUserPointsLoginfoVO.setExchangePoints(0);
            elUserPointsLoginfoVO.setSurplusPoints(0L);
            elUserPointsLoginfoVO.setAvatar(tokenService.getLoginUser().getSysUser().getAvatar());
            elUserPointsLoginfoVO.setUserStatus(0);
            return elUserPointsLoginfoVO;
        }

    }


    @Override
    public List<ElPointsLoginfo> myRewardPointList(ElPointsLoginfo pointsLoginfo) {
        return elPointsLogInfoMapper.myRewardPointList(pointsLoginfo);
    }

    @Override
    public List<ElPointsRecordListVO> findByUserId(Long userId) {

        return elPointsRecordMapper.findByUserId(userId);
    }


    /**
     * 兑换机服务接口
     *
     * @param machineMap json数据
     * @return 返回兑换机json数据
     */
    @Override
    public Map<String,String> exchangeMachineService(Map<String, String> machineMap) {
        log.error("======================兑换机服务接口:"+machineMap);
        Map<String,String> retMap = new HashMap<>();
        if(machineMap.get("FunCode").equals("1000")){//上货接口
            //保存或修改上报数据，根据兑换机编码和货道判断
            ElPointTradeNo elPointTradeNo = new ElPointTradeNo();
            elPointTradeNo.setMachineId(machineMap.get("MachineID"));
            elPointTradeNo.setSlotNo(machineMap.get("SlotNo"));
            List<ElPointTradeNo> elPointTradeNoList = elPointTradeNoMapper.selectElPointTradeNoList(elPointTradeNo);
            int flag;
            if(elPointTradeNoList.size()>0){
                elPointTradeNo.setId(elPointTradeNoList.get(0).getId());
                elPointTradeNo.setMachineId(null);
                elPointTradeNo.setSlotNo(null);
                elPointTradeNo.setTradeNo(machineMap.get("TradeNo"));
                elPointTradeNo.setKeyNum(machineMap.get("KeyNum"));
                elPointTradeNo.setStatus(machineMap.get("Status"));
                elPointTradeNo.setQuantity(machineMap.get("Quantity"));
                elPointTradeNo.setStock(machineMap.get("Stock"));
                elPointTradeNo.setCapacity(machineMap.get("Capacity"));
                elPointTradeNo.setProductId(machineMap.get("ProductID"));
                elPointTradeNo.setPrice(machineMap.get("Price"));
                elPointTradeNo.setType(machineMap.get("Type"));
                elPointTradeNo.setIntroduction(machineMap.get("Introduction"));
                elPointTradeNo.setName(machineMap.get("Name"));
                elPointTradeNo.setUpdateTime(new Date());
                flag = elPointTradeNoMapper.updateElPointTradeNo(elPointTradeNo);
            }else{
                elPointTradeNo.setFunCode(machineMap.get("FunCode"));
                elPointTradeNo.setTradeNo(machineMap.get("TradeNo"));
                elPointTradeNo.setKeyNum(machineMap.get("KeyNum"));
                elPointTradeNo.setStatus(machineMap.get("Status"));
                elPointTradeNo.setQuantity(machineMap.get("Quantity"));
                elPointTradeNo.setStock(machineMap.get("Stock"));
                elPointTradeNo.setCapacity(machineMap.get("Capacity"));
                elPointTradeNo.setProductId(machineMap.get("ProductID"));
                elPointTradeNo.setPrice(machineMap.get("Price"));
                elPointTradeNo.setType(machineMap.get("Type"));
                elPointTradeNo.setIntroduction(machineMap.get("Introduction"));
                elPointTradeNo.setName(machineMap.get("Name"));
                elPointTradeNo.setCreateTime(new Date());
                flag = elPointTradeNoMapper.insertElPointTradeNo(elPointTradeNo);
            }
            if(flag>0){
                //返回json数据
                retMap.put("Status","0");
                retMap.put("Err","success");
            }else{
                //返回json数据
                retMap.put("Status","1");
                retMap.put("Err","重新上传");
            }
            retMap.put("SlotNo",machineMap.get("SlotNo"));
            retMap.put("TradeNo",machineMap.get("TradeNo"));
            retMap.put("ImageUrl","");
            retMap.put("ImageDetailUrl", "");
            retMap.put("ImageDetailUrl", "");
            return retMap;
        }else if(machineMap.get("FunCode").equals("4000")){//远程控制出货接口
            log.error("======================兑换机服务接口FunCode:"+machineMap.get("FunCode"));
            ElPointOrder elPointOrder = new ElPointOrder();
            elPointOrder.setMachineId(machineMap.get("MachineID"));
            elPointOrder.setOrderStatus(0);
            List<ElPointOrder> elPointOrderList = elPointOrderMapper.selectElPointOrderList(elPointOrder);
            if(elPointOrderList.size()>0){
                //保存或修改上报数据，根据兑换机编码和货道判断
                ElPointTradeNo elPointTradeNo = new ElPointTradeNo();
                elPointTradeNo.setMachineId(elPointOrderList.get(0).getMachineId());
                elPointTradeNo.setSlotNo(elPointOrderList.get(0).getSlotNo());
                List<ElPointTradeNo> elPointTradeNoList = elPointTradeNoMapper.selectElPointTradeNoList(elPointTradeNo);
                if(elPointTradeNoList.size()>0){
                    ElPointOrder elPointOrderNew = new ElPointOrder();
                    elPointOrderNew.setId(elPointOrderList.get(0).getId());
                    elPointOrderNew.setOrderStatus(1);
                    elPointOrderNew.setUpdateBy("系统");
                    elPointOrderNew.setUpdateTime(new Date());
                    elPointOrderNew.setTradeNo(elPointTradeNoList.get(0).getTradeNo());
                    int flag = elPointOrderMapper.updateElPointOrder(elPointOrderNew);
                    if(flag>0){
                        retMap.put("Status","0");
                        retMap.put("MsgType","0");
                        retMap.put("TradeNo",elPointTradeNoList.get(0).getTradeNo());
                        retMap.put("SlotNo",elPointOrderList.get(0).getSlotNo());
                        retMap.put("ProductID",elPointOrderList.get(0).getProductId());
                        retMap.put("Err", "成功");
                    }else{
                        retMap.put("Status","1");
                        retMap.put("MsgType","0");
                        retMap.put("TradeNo","");
                        retMap.put("SlotNo","");
                        retMap.put("ProductID","");
                        retMap.put("Err", "失败");
                    }
                }else{
                    retMap.put("Status","1");
                    retMap.put("MsgType","0");
                    retMap.put("TradeNo","");
                    retMap.put("SlotNo","");
                    retMap.put("ProductID","");
                    retMap.put("Err", "失败");
                }
                log.error("======================兑换机服务接口返回json数据:"+retMap);
                return retMap;
            }
        }else if(machineMap.get("FunCode").equals("5000")){//出货反馈接口
            ElPointOrder elPointOrder = new ElPointOrder();
            elPointOrder.setMachineId(machineMap.get("MachineID"));
            elPointOrder.setOrderStatus(1);
            elPointOrder.setTradeNo(machineMap.get("TradeNo"));
            elPointOrder.setSlotNo(machineMap.get("SlotNo"));
            //判断Status0: 确认成功反馈  其他失败
            if(machineMap.get("Status").equals("0")){
                List<ElPointOrder> elPointOrderList = elPointOrderMapper.selectElPointOrderList(elPointOrder);
                if(elPointOrderList.size()>0){
                    retMap.put("Status","0");
                    retMap.put("TradeNo",elPointOrderList.get(0).getTradeNo()+"");
                    retMap.put("SlotNo",elPointOrderList.get(0).getSlotNo());
                    retMap.put("Err","成功");
                }else{
                    retMap.put("Status","0");
                    retMap.put("TradeNo",machineMap.get("TradeNo"));
                    retMap.put("SlotNo",machineMap.get("SlotNo"));
                    retMap.put("Err","反馈失败， 请联系管理员");
                }
                return retMap;
            }else{
                //出货未成功，查询货品订单，需要回退积分
                List<ElPointOrder> elPointOrderList = elPointOrderMapper.selectElPointOrderList(elPointOrder);
                if(elPointOrderList.size()>0){
                    Map<String,Object> obtainMap = new HashMap<>();
                    obtainMap.put("joinUserId",elPointOrderList.get(0).getJoinUserId());
                    obtainMap.put("deductPoints",elPointOrderList.get(0).getAmount());
                    obtainMap.put("reason","消费"+machineMap.get("Name")+"出货失败，积分退回。");
                    obtainBonusPoints(obtainMap);
                    retMap.put("Status","0");
                    retMap.put("TradeNo",machineMap.get("TradeNo"));
                    retMap.put("SlotNo",machineMap.get("SlotNo"));
                    retMap.put("Err","机器故障,回退积分");
                }else{
                    retMap.put("Status","0");
                    retMap.put("TradeNo",machineMap.get("TradeNo"));
                    retMap.put("SlotNo",machineMap.get("SlotNo"));
                    retMap.put("Err","订单不存在");
                }

                return retMap;
            }
        }
        return retMap;
    }

    /**
     * 兑换机消费奖励分兑换接口
     *
     * @param objJson 消费的json数据
     * @return 结果
     */
    @Override
    public int exchangePoints(String objJson) {
        log.error("======================兑换机消费奖励分json:"+objJson);
        //这里获取兑换的json数据
        JSONObject jsonObject = JSON.parseObject(objJson);
        Map<String,Object> deducMap = new HashMap<>();
        deducMap.put("joinUserId", tokenService.getLoginUser().getUserid());
        deducMap.put("pointsType", 2);
        deducMap.put("deductPoints", jsonObject.get("pri"));
        deducMap.put("reason", "兑换了商品编号("+jsonObject.get("pri")+")。");
        int flag = deductionPoints(deducMap);
        if(flag>0){
            ElPointOrder elPointOrder = new ElPointOrder();
            elPointOrder.setMachineId(jsonObject.getString("mid"));
            elPointOrder.setJoinUserId(tokenService.getLoginUser().getUserid());
            elPointOrder.setOrderStatus(0);
            elPointOrder.setSlotNo(jsonObject.getString("sid"));
            elPointOrder.setProductId(jsonObject.getString("pid"));
            elPointOrder.setAmount(jsonObject.getString("pri"));
            elPointOrder.setCreateBy("系统");
            elPointOrder.setCreateTime(new Date());
            return elPointOrderMapper.insertElPointOrder(elPointOrder);
        }else{
            throw new ServiceException("积分不够！！",500);
        }
    }


    /**
     * 兑换机回退商品积分
     *
     * @param objJson 消费的json数据
     * @return 结果
     */
    @Override
    public int rollBackPoints(String objJson) {
        log.error("======================兑换机消费奖励分json:"+objJson);
//        //这里获取退回商品的json数据
//        JSONObject jsonObject = JSON.parseObject(objJson);
//        //这里获取退回商品的列表
//        JSONArray jsonArray = jsonObject.getJSONArray(jsonObject.getString(""));
//        for(Object obj : jsonArray){
//            //这里循环调用需要退回的商品需要扣减的积分
//            obtainBonusPoints(map);
//        }
        return 200;
    }
}
