package cn.newfeifan.mall.module.member.service.signin;

import cn.hutool.core.util.ObjUtil;
import cn.newfeifan.mall.module.member.controller.admin.signin.vo.config.OrderPercentageRedisVO;
import com.alibaba.fastjson.JSONObject;
import cn.newfeifan.mall.framework.common.enums.CommonStatusEnum;
import cn.newfeifan.mall.framework.common.pojo.PageParam;
import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.util.date.DateUtils;
import cn.newfeifan.mall.framework.common.util.object.ObjectUtils;
import cn.newfeifan.mall.module.member.controller.admin.signin.vo.record.MemberSignInRecordPageReqVO;
import cn.newfeifan.mall.module.member.controller.app.signin.vo.record.AppMemberSignInConfigMoonRespVO;
import cn.newfeifan.mall.module.member.controller.app.signin.vo.record.AppMemberSignInRecordSummaryRespVO;
import cn.newfeifan.mall.module.member.controller.app.signin.vo.record.Days;
import cn.newfeifan.mall.module.member.controller.app.signin.vo.record.Rules;
import cn.newfeifan.mall.module.member.convert.signin.MemberSignInRecordConvert;
import cn.newfeifan.mall.module.member.dal.dataobject.signin.MemberSignInConfigDO;
import cn.newfeifan.mall.module.member.dal.dataobject.signin.MemberSignInRecordDO;
import cn.newfeifan.mall.module.member.dal.mysql.signin.MemberSignInRecordMapper;
import cn.newfeifan.mall.module.member.enums.MemberExperienceBizTypeEnum;
import cn.newfeifan.mall.module.member.service.level.MemberLevelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.newfeifan.mall.module.member.enums.DictTypeConstants.DISTRI_ORDER_PERCENTAGE;
import static cn.newfeifan.mall.module.member.enums.ErrorCodeConstants.SIGN_IN_RECORD_TODAY_EXISTS;

/**
 * 签到记录 Service 实现类
 *
 * @author 非繁源码
 */
@Service
@Validated
public class MemberSignInRecordServiceImpl implements MemberSignInRecordService {

    @Resource
    private MemberSignInRecordMapper signInRecordMapper;
    @Resource
    private MemberSignInConfigService signInConfigService;
    @Resource
    private MemberLevelService memberLevelService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public AppMemberSignInRecordSummaryRespVO getSignInRecordSummary(Long userId) {
        // 1. 初始化默认返回信息
        AppMemberSignInRecordSummaryRespVO summary = new AppMemberSignInRecordSummaryRespVO();
        summary.setTotalDay(0);
        summary.setContinuousDay(0);
        summary.setTodaySignIn(false);

        // 2. 获取用户签到的记录数
        Long signCount = signInRecordMapper.selectCountByUserId(userId);
        if (ObjUtil.equal(signCount, 0L)) {
            return summary;
        }
        summary.setTotalDay(signCount.intValue()); // 设置总签到天数

        // 3. 校验当天是否有签到
        MemberSignInRecordDO lastRecord = signInRecordMapper.selectLastRecordByUserId(userId);
        if (lastRecord == null) {
            return summary;
        }
        summary.setTodaySignIn(DateUtils.isToday(lastRecord.getCreateTime()));

        // 4.1 校验今天是否签到，没有签到则直接返回
        if (!summary.getTodaySignIn()) {
            return summary;
        }
        // 4.2 连续签到天数
        summary.setContinuousDay(lastRecord.getContinueDay());
        return summary;
    }

    @Override
    public AppMemberSignInConfigMoonRespVO getOwnSignInMoon(Long loginUserId, String month) {

        // 获取当前月份, 天数 , 星期数
        List<Days> days = generateDaysForCurrentMonth(month);
        LocalDate today = LocalDate.now();
        LocalDate firstDayOfMonth = today.withDayOfMonth(1);
        LocalDate lastDayOfMonth = today.withDayOfMonth(today.lengthOfMonth());
        if (StringUtils.isNotBlank(month)){
            // 解析字符串为YearMonth对象
            YearMonth yearMonth = YearMonth.parse(month, DateTimeFormatter.ofPattern("yyyy-MM"));
             firstDayOfMonth = yearMonth.atDay(1);
             lastDayOfMonth = yearMonth.atEndOfMonth();
        }

        // 获取签到的天数
        // 查询用户当月的签到情况
        List<MemberSignInRecordDO> lastRecordInMoon = signInRecordMapper.selectListByUserIdInCurrentMoon(loginUserId,
                Date.from(firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant()),
                Date.from(lastDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant())
        );
        for (MemberSignInRecordDO memberSignInRecordDO : lastRecordInMoon) {
            updateDayByNumber(days,memberSignInRecordDO.getDay());
        }
        int continueDays = 0;

        MemberSignInRecordDO lastRecord = signInRecordMapper.selectLastRecordByUserId(loginUserId);
        if (lastRecord!=null){
            continueDays = lastRecord.getContinueDay();
        }

        String s = stringRedisTemplate.opsForValue().get(DISTRI_ORDER_PERCENTAGE);
        if (StringUtils.isEmpty(s)) {
            OrderPercentageRedisVO signSocial = signInRecordMapper.getSignSocial();
            stringRedisTemplate.opsForValue().set(DISTRI_ORDER_PERCENTAGE, JSONObject.toJSONString(signSocial));
            s = JSONObject.toJSONString(signSocial);
        }
        OrderPercentageRedisVO orderPercentageRedisVO = JSONObject.parseObject(s, OrderPercentageRedisVO.class);

        return AppMemberSignInConfigMoonRespVO.builder()
                .days(days)
                .signInSocialStatus(orderPercentageRedisVO.getSignInSocialStatus())
                .continueDays(continueDays)
                .rules(Rules.builder().build())
                .build();
    }

    @Override
    public Boolean isSignIn() {
        MemberSignInRecordDO lastRecord = signInRecordMapper.selectLastRecordByUserId(getLoginUserId());
        return lastRecord != null && DateUtils.isToday(lastRecord.getCreateTime());
    }


    public static void updateDayByNumber(List<Days> daysList, int day) {
        for (Days dayObj : daysList) {
            if (dayObj.getDay() == day) {
                dayObj.setIsSign(1);
                dayObj.setIsReplenish(0);
                break;
            }
        }
    }


    public static List<Days> generateDaysForCurrentMonth(String month) {
        List<Days> daysList = new ArrayList<>();
        YearMonth yearMonth = YearMonth.parse(month, DateTimeFormatter.ofPattern("yyyy-MM"));
        LocalDate firstDayOfMonth = yearMonth.atDay(1);
        LocalDate lastDayOfMonth = yearMonth.atEndOfMonth();
        LocalDate today = LocalDate.now();
        if (StringUtils.isBlank(month)){
             firstDayOfMonth = today.withDayOfMonth(1);
             lastDayOfMonth = today.withDayOfMonth(today.lengthOfMonth());
        }
        for (LocalDate date = firstDayOfMonth; date.isBefore(lastDayOfMonth.plusDays(1)); date = date.plusDays(1)) {
            Days day = new Days();
            day.setDate(Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant()));
            day.setTime(day.getDate().getTime());
            day.setDay(date.getDayOfMonth());
            day.setWeek(date.getDayOfWeek().toString());

            if (date.isBefore(today)) {
                day.setCurrent("before");
            } else if (date.equals(today)) {
                day.setCurrent("today");
            } else {
                day.setCurrent("after");
            }
            daysList.add(day);
        }
        return daysList;
    }

    @Override
    public PageResult<MemberSignInRecordDO> getSignInRecordPage(MemberSignInRecordPageReqVO pageReqVO) {
        // 根据用户昵称查询出用户ids
        Set<Long> userIds = null;
        // 分页查询
        return signInRecordMapper.selectPage(pageReqVO, userIds);
    }

    @Override
    public PageResult<MemberSignInRecordDO> getSignRecordPage(Long userId, PageParam pageParam) {
        return signInRecordMapper.selectPage(userId, pageParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MemberSignInRecordDO createSignRecord(Long userId) {
        // 1. 获取当前用户最近的签到
        MemberSignInRecordDO lastRecord = signInRecordMapper.selectLastRecordByUserId(userId);
        // 1.1. 判断是否重复签到
        validateSigned(lastRecord);

        // 2.1. 获取所有的签到规则
        List<MemberSignInConfigDO> signInConfigs = signInConfigService.getSignInConfigList(CommonStatusEnum.ENABLE.getStatus());
        // 2.2. 组合数据
        MemberSignInRecordDO record = MemberSignInRecordConvert.INSTANCE.convert(userId, lastRecord, signInConfigs);

        // 3. 插入签到记录
        signInRecordMapper.insert(record);

        // 5. 增加经验
        if (!ObjectUtils.equalsAny(record.getExperience(), null, 0)) {
            memberLevelService.addExperience(userId, record.getExperience(), MemberExperienceBizTypeEnum.SIGN_IN, String.valueOf(record.getId()));
        }
        return record;
    }

    private void validateSigned(MemberSignInRecordDO signInRecordDO) {
        if (signInRecordDO == null) {
            return;
        }
        if (DateUtils.isToday(signInRecordDO.getCreateTime())) {
            throw exception(SIGN_IN_RECORD_TODAY_EXISTS);
        }
    }

}
