package jnpf.cultivate.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.entity.SuperBaseEntity;
import jnpf.base.vo.PageListVO;
import jnpf.cultivate.mapper.FtbCultivateCaseBaseLikeMapper;
import jnpf.cultivate.mapper.FtbCultivateCaseBaseMapper;
import jnpf.cultivate.service.FtbCultivateCaseBaseService;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.dto.casebase.FtbCultivateCaseBaseAuditDTO;
import jnpf.model.cultivate.dto.casebase.FtbCultivateCaseBaseDTO;
import jnpf.model.cultivate.dto.casebase.app.FtbCultivateCaseBaseCreatDTO;
import jnpf.model.cultivate.event.JnpfApplicationEvent;
import jnpf.model.cultivate.event.dto.file.FileEventDTO;
import jnpf.model.cultivate.po.FtbCultivateFile;
import jnpf.model.cultivate.po.casebase.FtbCultivateCaseBase;
import jnpf.model.cultivate.po.casebase.FtbCultivateCaseBaseLike;
import jnpf.model.cultivate.vo.casebase.FtbCultivateCaseBaseVO;
import jnpf.model.cultivate.vo.common.InnerPowerUserVO;
import jnpf.model.cultivate.vo.offline.FtbCultivateOfflineFileVO;
import jnpf.model.enums.SelfrowingEnum;
import jnpf.model.personnels.po.FtbPersonnelsStaffRoster;
import jnpf.personnels.service.FtbPersonnelsStaffRosterService;
import jnpf.personnels.utils.PersonnelPerUtils;
import jnpf.util.SelfGrowthUtil;
import jnpf.util.UserProvider;
import jnpf.util.context.SpringContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Title:
 * @Author: peng.hao
 * @create: 2024/7/22:11:26
 */
@Service
public class FtbCultivateCaseBaseServiceImpl  extends ServiceImpl<FtbCultivateCaseBaseMapper, FtbCultivateCaseBase> implements FtbCultivateCaseBaseService {

    @Resource
    private FtbPersonnelsStaffRosterService staffRosterservice;

    @Resource
    private FtbCultivateFileService ftbCultivateFileService;

    @Resource
    private FtbCultivateCaseBaseLikeMapper caseBaseLikeMapper;

    @Override
    public PageListVO<FtbCultivateCaseBaseVO> listDisplay(FtbCultivateCaseBaseDTO dto) {
        Page<FtbCultivateCaseBaseVO> page = dto.coverCultivatePage();
        String userId = UserProvider.getUser().getUserId();
        dto.setUserId(userId);
        page = baseMapper.listDisplay(page, dto);
        return CultivatePage.coverPageList(page);
    }
    @Override
    public PageListVO<FtbCultivateCaseBaseVO> listDisplayForApp(FtbCultivateCaseBaseDTO dto) {
        Page<FtbCultivateCaseBaseVO> page = dto.coverCultivatePage();
        dto.setUserId(UserProvider.getUser().getUserId());
        page = baseMapper.listDisplayForApp(page, dto);
        return CultivatePage.coverPageList(page);
    }

    @Override
    public void reviewCase(FtbCultivateCaseBaseAuditDTO baseAuditDTO) {
        String flag = baseAuditDTO.getFlag();
        // 2 审核通过, 3 审核不通过
        int status = "0".equals(flag) ? 3 : 2;
        LambdaUpdateWrapper<FtbCultivateCaseBase> lambdaed = Wrappers.lambdaUpdate();
        lambdaed.eq(SuperBaseEntity.SuperIBaseEntity::getId,baseAuditDTO.getId());
        lambdaed.set(FtbCultivateCaseBase::getStatus,status);
        lambdaed.set(FtbCultivateCaseBase::getAuditOpinion,baseAuditDTO.getAuditOpinion());
        // 审核时间
        lambdaed.set(FtbCultivateCaseBase::getAuditTime,new Date());
        lambdaed.set(FtbCultivateCaseBase::getAuditUserId,UserProvider.getUser().getUserId());
        // 同步更新更新时间
        lambdaed.set(FtbCultivateCaseBase::getLastModifyTime,new Date());
        baseMapper.update(null,lambdaed);
    }

    @Override
    public FtbCultivateCaseBaseVO getDetail(String id) {
        FtbCultivateCaseBase caseBase = baseMapper.selectById(id);
        FtbCultivateCaseBaseVO convert = FtbCultivateCaseBaseVO.convert(caseBase);
        if(StringUtils.isNotEmpty(convert.getAuditUserId())){
            LambdaQueryWrapper<FtbPersonnelsStaffRoster> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(FtbPersonnelsStaffRoster::getUserId,convert.getAuditUserId());
            FtbPersonnelsStaffRoster rosterserviceOne = staffRosterservice.getOne(wrapper);
            if(ObjectUtil.isNotNull(rosterserviceOne)) convert.setAuditUserName(rosterserviceOne.getName());
        }
        LambdaQueryWrapper<FtbPersonnelsStaffRoster> wrapperN = Wrappers.lambdaQuery();
        wrapperN.eq(FtbPersonnelsStaffRoster::getUserId,convert.getCreatorUserId());
        FtbPersonnelsStaffRoster rosterserviceOne = staffRosterservice.getOne(wrapperN);
        if(ObjectUtil.isNotNull(rosterserviceOne)) convert.setCreatorUserName(rosterserviceOne.getName());
        // 点赞量
        LambdaQueryWrapper<FtbCultivateCaseBaseLike> lambdaed = Wrappers.lambdaQuery();
        lambdaed.eq(FtbCultivateCaseBaseLike::getGainedId,id);
        Long aLong = caseBaseLikeMapper.selectCount(lambdaed);
        convert.setNumberOfLikes(aLong.intValue());
        LambdaQueryWrapper<FtbCultivateCaseBaseLike> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(FtbCultivateCaseBaseLike::getLikeUserId, UserProvider.getUser().getUserId());
        lambdaQueryWrapper.eq(FtbCultivateCaseBaseLike::getGainedId,id);
        Long aLong1 = caseBaseLikeMapper.selectCount(lambdaQueryWrapper);
        // 是否已经点赞
        convert.setHaveYouLikedIt(aLong1.intValue() > 0 ? 1 : 0);
        LambdaQueryWrapper<FtbCultivateFile> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(FtbCultivateFile::getBusinessId, id);
        List<FtbCultivateFile> fileLists = ftbCultivateFileService.list(wrapper);
        List<FtbCultivateOfflineFileVO> fileVOS = fileLists.stream()
                .map(FtbCultivateOfflineFileVO::convertFtbCultivateOfflineFileVO).collect(Collectors.toList());
        convert.setFiles(fileVOS);
        return convert;
    }

    @Override
    public void caseBaseCreatDTO(FtbCultivateCaseBaseCreatDTO caseBaseCreatDTO) {
        FtbCultivateCaseBase covert = FtbCultivateCaseBaseCreatDTO.covert(caseBaseCreatDTO);
        // 获取展示id
        String systemCaseId = SelfGrowthUtil.provideACustomIDBasedOnTheModule(SelfrowingEnum.CASE_LIBRARY);
        covert.setSystemCaseId(systemCaseId);
        baseMapper.insert(covert);
        //通过文件事件监听信息
        SpringContext.getApplicationContext().publishEvent(new JnpfApplicationEvent<>(FileEventDTO.builder()
                .files(caseBaseCreatDTO.getFiles())
                .businessTypeID(covert.getId())
                .type(FileEventDTO.FileType.CASE_LIBRARY)
                .build()));
    }

    @Override
    public void updateCaseLibrary(FtbCultivateCaseBaseCreatDTO updateVO) {
        FtbCultivateCaseBase covert = FtbCultivateCaseBaseCreatDTO.covert(updateVO);
        if (updateVO.getFiles() != null) {
            LambdaUpdateWrapper<FtbCultivateFile> lambdaed = Wrappers.lambdaUpdate();
            lambdaed.eq(FtbCultivateFile::getBusinessId, updateVO.getId());
            ftbCultivateFileService.remove(lambdaed);
            //通过文件事件监听信息
            SpringContext.getApplicationContext().publishEvent(new JnpfApplicationEvent<>(FileEventDTO.builder()
                    .files(updateVO.getFiles())
                    .businessTypeID(updateVO.getId())
                    .type(FileEventDTO.FileType.CASE_LIBRARY)
                    .build()));
        }
        LambdaUpdateWrapper<FtbCultivateCaseBase> update = Wrappers.lambdaUpdate();
        update.eq(FtbCultivateCaseBase::getId, covert.getId());
        update.set(FtbCultivateCaseBase::getCaseDescription, covert.getCaseDescription());
        update.set(FtbCultivateCaseBase::getCaseName, covert.getCaseName());
        update.set(FtbCultivateCaseBase::getStatus, covert.getStatus());
        update.set(FtbCultivateCaseBase::getLastModifyTime, new Date());
        // 重新编辑清空审核人数据
        update.set(FtbCultivateCaseBase::getAuditOpinion,null);
        update.set(FtbCultivateCaseBase::getAuditTime,null);
        update.set(FtbCultivateCaseBase::getAuditUserId,null);
        baseMapper.update(null, update);
    }


}
