package com.flossom.miniProgram.service.impl;

import com.flossom.common.core.domain.entity.*;
import com.flossom.common.core.domain.req.WxClockLogReq;
import com.flossom.common.core.domain.ret.WxClockLogRet;
import com.flossom.common.core.enums.Status;
import com.flossom.common.core.mapper.WxClockImgMapper;
import com.flossom.common.core.mapper.WxClockInstrumentLogMapper;
import com.flossom.common.core.mapper.WxClockLogMapper;
import com.flossom.common.core.mapper.WxInstrumentMapper;
import com.flossom.common.core.utils.DateUtils;
import com.flossom.common.security.utils.SecurityUtils;
import com.flossom.miniProgram.service.IWxClockLogService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class WxClockLogServiceImpl implements IWxClockLogService {

    @Autowired
    private WxClockLogMapper wxClockLogMapper;

    @Autowired
    private WxClockImgMapper wxClockImgMapper;

    @Autowired
    private WxClockInstrumentLogMapper wxClockInstrumentLogMapper;

    @Autowired
    private WxInstrumentMapper wxInstrumentMapper;


    @Override
    @Transactional
    public void insertWxClockLog(WxClockLogReq wxClockLogReq) {
        WxUserMember wxUserMember = SecurityUtils.getLoginUser().getWxUserMember();
        LocalDateTime now = LocalDateTime.now();

        // 首次打卡奖励
        WxClockLog queryClockLog = new WxClockLog();
        queryClockLog.setUserId(SecurityUtils.getLoginUser().getWxUserMember().getId());
        queryClockLog.getParams().put("beginTime", LocalDateTime.of(now.toLocalDate(), LocalTime.MIN));
        queryClockLog.getParams().put("endTime", LocalDateTime.of(now.toLocalDate(), LocalTime.MAX));
        Integer count = wxClockLogMapper.selectCountByUserId(queryClockLog);
        if (count == null || count == 0) {
            /**
             * TODO：当天首次打卡奖励积分
             */
        }

        // 打卡记录
        WxClockLog wxClockLog = new WxClockLog();
        BeanUtils.copyProperties(wxClockLogReq, wxClockLog);
        wxClockLog.setUserId(wxUserMember.getId());
        wxClockLog.setCreateBy(wxUserMember.getNickname());
        wxClockLog.setCreateTime(DateUtils.getNowDate());
        // 当天使用过的仪器
        WxClockInstrumentLog queryInstrumentLog = new WxClockInstrumentLog();
        queryInstrumentLog.setUserId(wxUserMember.getId());
        wxClockLog.getParams().put("beginTime", LocalDateTime.of(now.toLocalDate(), LocalTime.MIN));
        wxClockLog.getParams().put("endTime", LocalDateTime.of(now.toLocalDate(), LocalTime.MAX));
        queryInstrumentLog.setStatus(Status.OK.getCode().longValue());
        List<WxClockInstrumentLog> wxClockInstrumentLogList = wxClockInstrumentLogMapper.selectWxClockInstrumentLogList(queryInstrumentLog);
        if (wxClockInstrumentLogList != null && wxClockInstrumentLogList.size() > 0) {
            String instrumentIdList = wxClockInstrumentLogList.stream()
                    .map(WxClockInstrumentLog::getInstrumentId)
                    .distinct()
                    .map(Objects::toString)
                    .collect(Collectors.joining(","));
            wxClockLog.setInstrumentId(instrumentIdList);
            String instrumentNameList = wxClockInstrumentLogList.stream()
                    .map(WxClockInstrumentLog::getInstrumentName)
                    .distinct()
                    .map(Objects::toString)
                    .collect(Collectors.joining(","));
            wxClockLog.setInstrumentName(instrumentNameList);
        }
        wxClockLogMapper.insertWxClockLog(wxClockLog);

        // 打卡图片
        if (wxClockLogReq.getClockImageList() != null && wxClockLogReq.getClockImageList().size() > 0) {
            for (String image : wxClockLogReq.getClockImageList()) {
                WxClockImg wxClockImg = new WxClockImg();
                wxClockImg.setUserClockId(wxClockLog.getId());
                wxClockImg.setClockImg(image);
                wxClockImg.setCreateBy(wxUserMember.getNickname());
                wxClockImg.setCreateTime(DateUtils.getNowDate());
                wxClockImgMapper.insertWxClockImg(wxClockImg);
            }
        }
    }

    @Override
    @Transactional
    public void addClockInstrument(Long instrumentId) {
        // 添加仪器使用记录
        WxClockInstrumentLog wxClockInstrumentLog = new WxClockInstrumentLog();
        wxClockInstrumentLog.setUserId(SecurityUtils.getLoginUser().getWxUserMember().getId());
        wxClockInstrumentLog.setInstrumentId(instrumentId);
        WxInstrument wxInstrument = wxInstrumentMapper.selectWxInstrumentById(instrumentId);
        if (wxInstrument != null) {
            wxClockInstrumentLog.setInstrumentName(wxInstrument.getName());
        }
        wxClockInstrumentLog.setStatus(Status.OK.getCode().longValue());
        wxClockInstrumentLog.setCreateBy(SecurityUtils.getLoginUser().getWxUserMember().getNickname());
        wxClockInstrumentLog.setCreateTime(DateUtils.getNowDate());
        wxClockInstrumentLogMapper.insertWxClockInstrumentLog(wxClockInstrumentLog);

        // 查询今天是否有打卡，存在打卡，则将仪器添加到最近一条打卡记录上
        WxClockLog queryClockLog = new WxClockLog();
        queryClockLog.setUserId(SecurityUtils.getLoginUser().getWxUserMember().getId());
        LocalDateTime now = LocalDateTime.now();
        queryClockLog.getParams().put("beginTime", LocalDateTime.of(now.toLocalDate(), LocalTime.MIN));
        queryClockLog.getParams().put("endTime", LocalDateTime.of(now.toLocalDate(), LocalTime.MAX));
        List<WxClockLog> wxClockLogList = wxClockLogMapper.selectWxClockLogList(queryClockLog);
        if (wxClockLogList != null && wxClockLogList.size() > 0) {
            // 直接获取最新的打卡记录
            WxClockLog saveClockLog = new WxClockLog();
            WxClockLog newWxClockLog = wxClockLogList.get(0);
            // 获取打卡记录的使用过的仪器ID
            List<Long> usedList = Arrays.asList(newWxClockLog.getInstrumentId().split(",")).stream().map(Long::valueOf).collect(Collectors.toList());
            if (!usedList.contains(instrumentId)) {
                saveClockLog.setInstrumentId(newWxClockLog.getInstrumentId() + "," + instrumentId);
                WxInstrument instrument = wxInstrumentMapper.selectWxInstrumentById(instrumentId);
                if (instrument != null) {
                    saveClockLog.setInstrumentName(newWxClockLog.getInstrumentName() + "," + instrument.getName());
                }
                saveClockLog.setId(newWxClockLog.getId());
                wxClockLogMapper.updateWxClockLog(saveClockLog);
            }
        }
    }

    @Override
    public WxClockLogRet getClockByUserId() {
        // 查询今天是否有打卡，存在打卡，则将仪器添加到最近一条打卡记录上
        WxClockLog queryClockLog = new WxClockLog();
        queryClockLog.setUserId(SecurityUtils.getLoginUser().getWxUserMember().getId());
        LocalDateTime now = LocalDateTime.now();
        queryClockLog.getParams().put("beginTime", LocalDateTime.of(now.toLocalDate(), LocalTime.MIN));
        queryClockLog.getParams().put("endTime", LocalDateTime.of(now.toLocalDate(), LocalTime.MAX));
        List<WxClockLog> wxClockLogList = wxClockLogMapper.selectWxClockLogList(queryClockLog);
        if (wxClockLogList == null && wxClockLogList.size() == 0) {
            return null;
        }
        WxClockLogRet wxClockLogRet = new WxClockLogRet();
        BeanUtils.copyProperties(wxClockLogList.get(0), wxClockLogRet);

        WxClockImg queryClockImg = new WxClockImg();
        queryClockImg.setUserClockId(wxClockLogRet.getId());
        List<WxClockImg> wxClockImgList = wxClockImgMapper.selectWxClockImgList(queryClockImg);
        if (wxClockImgList != null && wxClockImgList.size() > 0) {
            wxClockImgList.forEach(wxClockImg -> {
                wxClockLogRet.getClockImg().add(wxClockImg.getClockImg());
            });
        }
        return wxClockLogRet;
    }
}
