package com.flossom.system.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.flossom.common.core.domain.entity.WxUserIntegralLog;
import com.flossom.common.core.domain.entity.WxUserMember;
import com.flossom.common.core.enums.Status;
import com.flossom.common.core.mapper.WxUserIntegralLogMapper;
import com.flossom.common.core.mapper.WxUserMemberMapper;
import com.flossom.common.core.utils.DateUtils;
import com.flossom.common.security.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.flossom.system.service.IWxUserIntegralLogService;

/**
 * 微信用户积分流水Service业务层处理
 *
 * @author flossom
 * @date 2023-12-14
 */
@Service
public class WxUserIntegralLogServiceImpl implements IWxUserIntegralLogService {
    @Autowired
    private WxUserIntegralLogMapper wxUserIntegralLogMapper;

    @Autowired
    private WxUserMemberMapper wxUserMemberMapper;

    /**
     * 查询微信用户积分流水
     *
     * @param id 微信用户积分流水主键
     * @return 微信用户积分流水
     */
    @Override
    public WxUserIntegralLog selectWxUserIntegralLogById(Long id) {
        return wxUserIntegralLogMapper.selectWxUserIntegralLogById(id);
    }

    /**
     * 查询微信用户积分流水列表
     *
     * @param wxUserIntegralLog 微信用户积分流水
     * @return 微信用户积分流水
     */
    @Override
    public List<WxUserIntegralLog> selectWxUserIntegralLogList(WxUserIntegralLog wxUserIntegralLog) {
        return wxUserIntegralLogMapper.selectWxUserIntegralLogList(wxUserIntegralLog);
    }

    /**
     * 新增微信用户积分流水
     *
     * @param wxUserIntegralLog 微信用户积分流水
     * @return 结果
     */
    @Override
    public int insertWxUserIntegralLog(WxUserIntegralLog wxUserIntegralLog) {
        wxUserIntegralLog.setCreateTime(DateUtils.getNowDate());
        return wxUserIntegralLogMapper.insertWxUserIntegralLog(wxUserIntegralLog);
    }

    /**
     * 修改微信用户积分流水
     *
     * @param wxUserIntegralLog 微信用户积分流水
     * @return 结果
     */
    @Override
    public int updateWxUserIntegralLog(WxUserIntegralLog wxUserIntegralLog) {
        return wxUserIntegralLogMapper.updateWxUserIntegralLog(wxUserIntegralLog);
    }

    /**
     * 批量删除微信用户积分流水
     *
     * @param ids 需要删除的微信用户积分流水主键
     * @return 结果
     */
    @Override
    public int deleteWxUserIntegralLogByIds(Long[] ids) {
        return wxUserIntegralLogMapper.deleteWxUserIntegralLogByIds(ids);
    }

    /**
     * 删除微信用户积分流水信息
     *
     * @param id 微信用户积分流水主键
     * @return 结果
     */
    @Override
    public int deleteWxUserIntegralLogById(Long id) {
        return wxUserIntegralLogMapper.deleteWxUserIntegralLogById(id);
    }

    @Override
    public void countUserExpireIntegral(List<Long> idList) {
        // 1、获取所有用户
        List<WxUserMember> wxUserMembers = new ArrayList<>();
        if (idList != null && idList.size() > 0) {
            for (Long aLong : idList) {
                WxUserMember wxUserMember = wxUserMemberMapper.selectWxUserMemberById(aLong);
                if (wxUserMember != null) {
                    wxUserMembers.add(wxUserMember);
                }
            }
        } else {
            WxUserMember wxUserMember = new WxUserMember();
            wxUserMember.setUserType(1);    // 会员
            wxUserMember.setStatus(Status.OK.getCode());
            wxUserMembers = wxUserMemberMapper.selectWxUserMemberList(wxUserMember);
        }

        for (WxUserMember userMember : wxUserMembers) {
            WxUserIntegralLog query = new WxUserIntegralLog();
            query.setUserId(userMember.getId());
            // 2、根据用户id获取用户的历史积分记录
            // 增加: 时间为 当前时间上一年的最后一天的最后一刻
            LocalDateTime queryTime = LocalDateTime.now().minusYears(1).with(TemporalAdjusters.lastDayOfYear()).with(LocalTime.MAX);
            query.setCreateTime(Date.from(queryTime.atZone(ZoneId.systemDefault()).toInstant()));
            List<WxUserIntegralLog> increaseUserIntegralLogList = wxUserIntegralLogMapper.selectWxUserIntegralLogList(query);
            Long increaseIntegral = increaseUserIntegralLogList.stream().filter(wxUserIntegralLog ->
                    StringUtils.equals(wxUserIntegralLog.getSource(), "1")
            ).mapToLong(WxUserIntegralLog::getFloatScore).sum();

            // 扣减: 时间为当前
            query.setCreateTime(null);
            List<WxUserIntegralLog> reduceUserIntegralLogList = wxUserIntegralLogMapper.selectWxUserIntegralLogList(query);
            Long reduceIntegral = reduceUserIntegralLogList.stream().filter(wxUserIntegralLog ->
                    StringUtils.equals(wxUserIntegralLog.getSource(), "2")
            ).mapToLong(WxUserIntegralLog::getFloatScore).sum();

            // 3、计算该用户得过期积分，并保存到用户信息表得过期积分中
            // 当增加的大于扣除的就直接扣减
            WxUserMember updateEntity = new WxUserMember();
            if (increaseIntegral > reduceIntegral) {
                updateEntity.setExpireCredit(increaseIntegral.intValue() - reduceIntegral.intValue());
            } else {
                updateEntity.setExpireCredit(0);
            }
            updateEntity.setId(userMember.getId());
            updateEntity.setUpdateBy(SecurityUtils.getUsername());
            updateEntity.setUpdateTime(DateUtils.getNowDate());
            wxUserMemberMapper.updateWxUserMember(updateEntity);
        }
    }
}
