package org.dromara.zjk.learning_world.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.internal.trove.map.hash.TLongIntHashMap;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hpsf.Decimal;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.api.RemoteConfigService;
import org.dromara.zjk.domain.vo.ZjkExpertVo;
import org.dromara.zjk.learning_world.domain.bo.ZjkLearningRecordsBo;
import org.dromara.zjk.learning_world.domain.vo.ZjkLearningCourseVo;
import org.dromara.zjk.learning_world.domain.vo.ZjkLearningRecordsVo;
import org.dromara.zjk.learning_world.enums.course.LearningRecordStatusEnum;
import org.dromara.zjk.learning_world.mapper.ZjkLearningCourseMapper;
import org.dromara.zjk.learning_world.mapper.ZjkLearningRecordsMapper;
import org.dromara.zjk.learning_world.service.IZjkLearningCourseService;
import org.dromara.zjk.learning_world.service.IZjkLearningRecordsService;
import org.dromara.zjk.mapper.ZjkExpertMapper;
import org.springframework.stereotype.Service;
import org.dromara.zjk.learning_world.domain.entity.ZjkLearningRecords;

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

import static cn.hutool.core.date.DateTime.now;

/**
 * 学习记录Service业务层处理
 *
 * @author wt
 * @date 2024-11-26
 */
@RequiredArgsConstructor
@Service
public class ZjkLearningRecordsServiceImpl implements IZjkLearningRecordsService {

    private final ZjkLearningRecordsMapper baseMapper;

    private final ZjkExpertMapper zjkExpertMapper;

    private final ZjkLearningCourseMapper zjkLearningCourseMapper;

    @DubboReference
    private RemoteConfigService remoteConfigService;

    /**
     * 查询学习记录
     *
     * @param id 主键
     * @return 学习记录
     */
    @Override
    public ZjkLearningRecordsVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询学习记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 学习记录分页列表
     */
    @Override
    public TableDataInfo<ZjkLearningRecordsVo> queryPageList(ZjkLearningRecordsBo bo, PageQuery pageQuery) {
        Page<ZjkLearningRecordsVo> result = baseMapper.selectRecord(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的学习记录列表
     *
     * @param bo 查询条件
     * @return 学习记录列表
     */
    @Override
    public List<ZjkLearningRecordsVo> queryList(ZjkLearningRecordsBo bo) {
        LambdaQueryWrapper<ZjkLearningRecords> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZjkLearningRecords> buildQueryWrapper(ZjkLearningRecordsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZjkLearningRecords> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCourseId() != null, ZjkLearningRecords::getCourseId, bo.getCourseId());
        lqw.eq(bo.getUserId() != null, ZjkLearningRecords::getUserId, bo.getUserId());
        lqw.eq(bo.getExpertId() != null, ZjkLearningRecords::getExpertId, bo.getExpertId());
        lqw.eq(bo.getRate() != null, ZjkLearningRecords::getRate, bo.getRate());
        lqw.eq(bo.getViewDuration() != null, ZjkLearningRecords::getViewDuration, bo.getViewDuration());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ZjkLearningRecords::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增学习记录
     *
     * @param bo 学习记录
     * @return 是否新增成功
     */
    /*@Override
    public Boolean insertByBo(ZjkLearningRecordsBo bo) {
        ZjkLearningRecords add = MapstructUtils.convert(bo, ZjkLearningRecords.class);
        validEntityBeforeSave(add);
        ZjkExpertVo zjkExpertVo = zjkExpertMapper.selectByUserId(LoginHelper.getUserId());
        if (zjkExpertVo == null) {
            return false;
        }
        add.setExpertId(zjkExpertVo.getExpertId());
        add.setUserId(zjkExpertVo.getUserId());
        add.setDeptId(LoginHelper.getDeptId());
        Long courseId = add.getCourseId();
        ZjkLearningRecordsVo infoByCourseId = getInfoByCourseId(courseId);
        boolean recordEntity = infoByCourseId != null;
        if (recordEntity) {
            add.setId(infoByCourseId.getId());
        }
        //课程学习完毕 无需重复学习
        if (recordEntity && infoByCourseId.getStatus().equals(LearningRecordStatusEnum.DONE.getCode())) {
            return true;
        }
        boolean flag = baseMapper.insertOrUpdate(add);
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }*/
    @Override
    public Boolean insertByBo(ZjkLearningRecordsBo bo) {
        ZjkLearningRecords add = MapstructUtils.convert(bo, ZjkLearningRecords.class);
        validEntityBeforeSave(add);

        ZjkExpertVo zjkExpertVo = zjkExpertMapper.selectByUserId(LoginHelper.getUserId());
        if (zjkExpertVo == null) {
            return false;
        }

        add.setExpertId(zjkExpertVo.getExpertId());
        add.setUserId(zjkExpertVo.getUserId());
        add.setDeptId(LoginHelper.getDeptId());

        Long courseId = add.getCourseId();
        ZjkLearningRecordsVo infoByCourseId = getInfoByCourseId(courseId);
        boolean recordEntity = infoByCourseId != null;

        if (recordEntity) {
            // 学习完成，判断是否需要更新
            if (LearningRecordStatusEnum.DONE.getCode().equals(infoByCourseId.getStatus())) {
                if (add.getLearningSessionLength() <= infoByCourseId.getLearningSessionLength()) {
                    return true;
                }
            }

            // 幂等判断，内容一致不重复提交
            if (Objects.equals(add.getLearningSessionLength(), infoByCourseId.getLearningSessionLength()) &&
                Objects.equals(add.getStatus(), infoByCourseId.getStatus())) {
                return true;
            }

            // 更新逻辑（可根据实际改成累加 or max）
            long total = Math.max(
                Optional.ofNullable(add.getLearningSessionLength()).orElse(0L),
                Optional.ofNullable(infoByCourseId.getLearningSessionLength()).orElse(0L)
            );
            add.setLearningSessionLength(total);
            add.setId(infoByCourseId.getId());
        }

        add.setUpdateTime(now()); // 记录最后学习时间

        boolean flag = baseMapper.insertOrUpdate(add);
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }


    /**
     * 修改学习记录
     *
     * @param bo 学习记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ZjkLearningRecordsBo bo) {
        ZjkLearningRecords update = MapstructUtils.convert(bo, ZjkLearningRecords.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZjkLearningRecords entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除学习记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public ZjkLearningRecordsVo getInfoByCourseId(Long courseId) {
        LambdaQueryWrapper<ZjkLearningRecords> lqw = Wrappers.lambdaQuery();
        lqw.eq(courseId != null, ZjkLearningRecords::getCourseId, courseId);
        lqw.eq(ZjkLearningRecords::getUserId, LoginHelper.getUserId());
        lqw.last("limit 1");
        return baseMapper.selectVoOne(lqw);
    }

    @Override
    public ZjkLearningRecordsVo compliance() {
        ZjkLearningRecordsVo zjkLearningRecordsVo = new ZjkLearningRecordsVo();
        List<ZjkLearningRecords> zjkLearningRecords = baseMapper.selectList(
            new LambdaQueryWrapper<ZjkLearningRecords>()
                .eq(ZjkLearningRecords::getUserId, LoginHelper.getUserId())
        );
        if (CollectionUtil.isEmpty(zjkLearningRecords)) {
            return zjkLearningRecordsVo;
        }
        double sum = zjkLearningRecords.stream().mapToDouble(ZjkLearningRecords::getLearningSessionLength).sum();

        BigDecimal bd = BigDecimal.valueOf(sum);
        BigDecimal learningHours = bd.divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
        zjkLearningRecordsVo.setLearningHours(learningHours);

        String systemLearningHours = remoteConfigService.selectConfigByKey("system.learning.hours");
        BigDecimal systemLearningHoursLong;
        try {
            // 尝试将字符串转换为Long类型
            systemLearningHoursLong = new BigDecimal(systemLearningHours);
            systemLearningHoursLong = systemLearningHoursLong.multiply(BigDecimal.valueOf(1)).setScale(2, RoundingMode.HALF_UP);
        } catch (NumberFormatException e) {
            // 处理转换失败的情况
            systemLearningHoursLong = BigDecimal.ZERO;
        }

        zjkLearningRecordsVo.setSystemLearningHours(systemLearningHoursLong);
        // 比较学习时长和系统配置学习时长
        boolean isMoreThanSystemConfig = learningHours.compareTo(systemLearningHoursLong) > 0;

        zjkLearningRecordsVo.setCompliance(isMoreThanSystemConfig);
        return zjkLearningRecordsVo;
    }
}
