package jnpf.cultivate.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import jnpf.base.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.cultivate.mapper.CultivateUserViewMapper;
import jnpf.cultivate.mapper.TeachingApproveMapper;
import jnpf.cultivate.service.CultivateFileService;
import jnpf.cultivate.service.TeachingRecordService;
import jnpf.cultivate.service.V2TeachingService;
import jnpf.cultivate.utils.CultivateImUtil;
import jnpf.entity.cultivate.TeachingRecord;
import jnpf.exception.HandleException;
import jnpf.model.cultivate.dto.teaching.RecordQueryDto;
import jnpf.model.cultivate.dto.teaching.TeachingApproveDto;
import jnpf.model.cultivate.event.dto.file.FileEventDTO;
import jnpf.model.cultivate.po.teaching.CultivateFile;
import jnpf.model.cultivate.po.teaching.CultivateUserView;
import jnpf.model.cultivate.po.teaching.TeachingApprove;
import jnpf.model.cultivate.v2.teaching.vo.StoreTeachingVo;
import jnpf.model.cultivate.v2.teaching.vo.TeachingDetailVo;
import jnpf.model.cultivate.v2.teaching.vo.V2TeachingRecordVo;
import jnpf.permission.StoreApi;
import jnpf.permission.dto.store.QueryStoreListDTO;
import jnpf.permission.vo.store.StoreBaseListInfo;
import jnpf.util.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 带教/练习服务实现[v2]
 *
 * @author yanwenfu
 * @create 2026-03-02
 */
@Service
public class V2TeachingServiceImpl implements V2TeachingService {

    @Resource
    private TeachingRecordService teachingRecordService;
    @Resource
    private StoreApi storeApi;
    @Resource
    private TeachingApproveMapper teachingApproveMapper;
    @Resource
    private CultivateUserViewMapper cultivateUserViewMapper;
    @Resource
    private CultivateFileService cultivateFileService;
    @Resource
    private CultivateImUtil cultivateImUtil;

    @Override
    public List<StoreTeachingVo> getPage(RecordQueryDto queryDto) {

        // 根据storeIds查询每个门店下的带教数量
        List<StoreTeachingVo> list = teachingRecordService.getStoreRecordCount(queryDto);
        // 查询store信息
        ActionResult<List<StoreBaseListInfo>> storeResult = storeApi.listInfo(new QueryStoreListDTO(queryDto.getStoreIdList(), null));
        List<StoreBaseListInfo> storeList;
        if (null != storeResult && null != storeResult.getData()) {
            storeList = storeResult.getData();
        } else {
            storeList = new ArrayList<>();
        }
        if (StringUtil.isEmpty(queryDto.getStoreId())) {
            // 未传门店id, 默认展开第一个
            list.stream().max(Comparator.comparing(StoreTeachingVo::getRecordCount)).ifPresent(vo -> queryDto.setStoreId(vo.getStoreId()));
        }
        Map<String, StoreBaseListInfo> storeMap = storeList.stream().collect(Collectors.toMap(StoreBaseListInfo::getId, Function.identity()));
        list.forEach(v -> {
            StoreBaseListInfo store = storeMap.get(v.getStoreId());
            v.setStoreName(null == store ? "" : store.getStoreName());
        });
        // 根据storeId查询带教分页数据
        PageInfo<V2TeachingRecordVo> page = teachingRecordService.getStoreRecordPage(queryDto);
        if (page.getList() == null) {
            page.setList(new ArrayList<>());
        }
        List<String> collect = page.getList().stream().map(V2TeachingRecordVo::getId).collect(Collectors.toList());
        // 查询是否浏览
        Set<String> viewedSet = teachingRecordService.getViewedSet(collect, UserProvider.getLoginUserId());
        page.getList().forEach(v -> {
            if (viewedSet.contains(v.getId())) {
                v.setViewed(true);
            }
        });
        list.stream()
                .filter(v -> v.getStoreId().equals(queryDto.getStoreId()))
                .findFirst()
                .ifPresent(v -> {
                    PageListVO<V2TeachingRecordVo> vo = new PageListVO<>();
                    vo.setList(page.getList());
                    vo.setPagination(FtbUtil.getPagination(page));
                    v.setRecordPage(vo);
                });
        return list;
    }

    @Override
    public TeachingDetailVo getTeachingDetail(String bizId) {

        // 查询是否有已阅记录, 无则新增
        CultivateUserView cultivateUserView = cultivateUserViewMapper.selectOne(new LambdaQueryWrapper<CultivateUserView>()
                .eq(CultivateUserView::getBizId, bizId)
                .eq(CultivateUserView::getUserId, UserProvider.getLoginUserId()));
        if (null == cultivateUserView) {
            cultivateUserView = new CultivateUserView(FtbUtil.getId(), bizId, UserProvider.getLoginUserId());
            cultivateUserViewMapper.insert(cultivateUserView);
        }
        return teachingRecordService.getTeachingDetailById(bizId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approveTeachingRecord(TeachingApproveDto approveDto) throws HandleException {

        TeachingApprove teachingApprove = teachingApproveMapper.selectById(approveDto.getId());
        if (null == teachingApprove) {
            throw new HandleException("未找到审批记录");
        }
        teachingApprove.setApproveStatus(approveDto.getApproveStatus());
        teachingApprove.setRemark(approveDto.getRemark());
        teachingApprove.setNeedFeedback(approveDto.getNeedFeedback());
        teachingApprove.setLastModifyUserId(UserProvider.getLoginUserId());
        teachingApprove.setLastModifyTime(new Date());
        // 新增附件信息
        if (null != approveDto.getFileList() && !approveDto.getFileList().isEmpty()) {
            List<CultivateFile> fileList = teachingRecordService.changeToFileList(teachingApprove.getId(), approveDto.getFileList(), UserProvider.getLoginUserId(), FileEventDTO.FileType.TEACHING_APPROVE);
            cultivateFileService.saveBatch(fileList);
        }
        teachingApproveMapper.updateById(teachingApprove);
        if (teachingApprove.getApproveStatus().equals(ConstantUtil.PASS_FALSE) && null != approveDto.getNeedFeedback() && approveDto.getNeedFeedback().equals(ConstantUtil.NUM_TRUE)) {
            // 需要反馈带教员 发送IM
            TeachingRecord teachingRecord = teachingRecordService.getById(teachingApprove.getTeachId());
            cultivateImUtil.sendCultivateApproveMsg(List.of(teachingRecord.getUserId()), UserProvider.getUser().getTenantId(),
                    "带教审核结果提醒\n您有一条带教记录未通过，请点击查看详情进行查看！", teachingApprove.getTeachId());
        }
    }
}
