package com.fs.task;

import com.fs.common.constant.FsConstants;
import com.fs.common.core.redis.RedisCache;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyMoneyLogs;
import com.fs.company.mapper.CompanyMoneyLogsMapper;
import com.fs.company.service.ICompanyService;
import com.fs.company.vo.RedPacketMoneyVO;
import com.fs.course.mapper.FsCourseRedPacketLogMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@AllArgsConstructor
@Component("companyTask")
@Slf4j
public class FsCompanyTask {

    private final RedisCache redisCache;
    private FsCourseRedPacketLogMapper fsCourseRedPacketLogMapper;
    private ICompanyService companyService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private CompanyMoneyLogsMapper moneyLogsMapper;

    public void refreshCompanyMoney() {
        LocalDateTime now = LocalDateTime.now();
        // 获取上一个小时的开始时间
        LocalDateTime startTime = now.minusHours(1)
                .withMinute(0)
                .withSecond(0);
        // 获取上一个小时的结束时间
        LocalDateTime endTime = startTime
                .withMinute(59)
                .withSecond(59);
        List<RedPacketMoneyVO> redPacketMoneyVOS = fsCourseRedPacketLogMapper.selectFsCourseRedPacketLogHourseByCompany(startTime, endTime);
        for (RedPacketMoneyVO redPacketMoneyVO : redPacketMoneyVOS) {
            companyService.subtractCompanyMoneyHourse(redPacketMoneyVO.getMoney(), redPacketMoneyVO.getCompanyId(), startTime.toLocalTime(), endTime.toLocalTime());
        }
    }

    /**
     * 同步公司缓存余额到公司数据表
     */
    public void syncRedisCompanyMoneyToDB(){
        // 获取所有的公司余额key
        String companyMoneyKeyAll = FsConstants.COMPANY_MONEY_KEY + "*";
        Collection<String> keys = redisCache.keys(companyMoneyKeyAll);

        if (keys != null && !keys.isEmpty()) {
            log.info("同步缓存余额到公司表，keys:{}", keys);
            List<Object> values = redisTemplate.opsForValue().multiGet(keys);
            Iterator<String> keyIterator = keys.iterator();
            if(values != null && !values.isEmpty()){
                Iterator<Object> valueIterator = values.iterator();
                List<Company> companies = companyService.selectCompanyList(new Company());

                Map<Long, BigDecimal> moneyMap = new HashMap<>();
                while (keyIterator.hasNext() && valueIterator.hasNext()) {
                    String next = keyIterator.next();
                    String[] keySplit = next.split(":");
                    Long companyId = Long.parseLong(keySplit[2]);
                    String value = valueIterator.next().toString();
                    moneyMap.put(companyId, new BigDecimal(value));
                }

                // 新增账户流水
                // 直接循环保存，由于是定时任务执行，暂时不优化
                for (Company company : companies) {
                    if(moneyMap.containsKey(company.getCompanyId()) && !(moneyMap.get(company.getCompanyId()).compareTo(company.getMoney()) == 0)){
                        CompanyMoneyLogs log = new CompanyMoneyLogs();
                        log.setCompanyId(company.getCompanyId());
                        log.setRemark("扣除红包金额-同步");
                        // 让减出来的金额为负数
                        if(moneyMap.get(company.getCompanyId()).compareTo(company.getMoney()) <= 0 ){
                            log.setMoney(moneyMap.get(company.getCompanyId()).subtract(company.getMoney()));
                        } else {
                            log.setMoney(company.getMoney().subtract(moneyMap.get(company.getCompanyId())));
                        }
                        log.setLogsType(15);
                        log.setBalance(moneyMap.get(company.getCompanyId()));
                        log.setCreateTime(new Date());
                        moneyLogsMapper.insertCompanyMoneyLogs(log);
                    }
                }

                // 使用Stream进行匹配赋值
                List<Company> collect = companies.stream()
                        .filter(company -> moneyMap.containsKey(company.getCompanyId()))
                        .peek(company -> company.setMoney(moneyMap.get(company.getCompanyId()))).collect(Collectors.toList());

                // 保存公司余额
                if(!collect.isEmpty()){
                    companyService.batchUpdateCompany(collect);
                }

            }
        }

    }
}
