package com.jeeplus.pubmodules.knowledge.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.domain.BaseEntity;
import com.jeeplus.pubmodules.editor.domain.EditorFiles;
import com.jeeplus.pubmodules.editor.service.EditorFilesService;
import com.jeeplus.pubmodules.editor.service.dto.EditorFilesDTO;
import com.jeeplus.pubmodules.knowledge.domain.KnowledgeShareComment;
import com.jeeplus.pubmodules.knowledge.domain.KnowledgeShareDetail;
import com.jeeplus.pubmodules.knowledge.domain.KnowledgeShareVisit;
import com.jeeplus.pubmodules.knowledge.mapper.KnowledgeShareCommentMapper;
import com.jeeplus.pubmodules.knowledge.mapper.KnowledgeShareDetailMapper;
import com.jeeplus.pubmodules.knowledge.mapper.KnowledgeShareTypeMapper;
import com.jeeplus.pubmodules.knowledge.mapper.KnowledgeShareVisitMapper;
import com.jeeplus.pubmodules.knowledge.service.dto.KnowledgeShareInfoDto;
import com.jeeplus.pubmodules.knowledge.service.dto.KnowledgeShareListDto;
import com.jeeplus.pubmodules.knowledge.service.dto.KnowledgeShareTypeDto;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.service.dto.WorkAttachmentInfoDTO;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class KnowledgeShareInfoService {

    @Resource
    private KnowledgeShareDetailMapper detailMapper;

    @Resource
    private KnowledgeShareVisitMapper visitMapper;

    @Resource
    private KnowledgeShareCommentMapper commentMapper;

    @Resource
    private KnowledgeShareTypeMapper typeMapper;

    @Resource
    private EditorFilesService editorFilesService;

    public IPage<KnowledgeShareListDto> list(Page<KnowledgeShareListDto> page, KnowledgeShareDetail detail) {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        QueryWrapper<KnowledgeShareTypeDto> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.company_id",userDTO.getCompanyDTO().getId());
        return detailMapper.findList(page,queryWrapper, detail);
    }

    public String save(KnowledgeShareInfoDto dto) {
        if (StringUtils.isNotEmpty(dto.getId())) {
            return update(dto);
        } else {
            return add(dto);
        }
    }

    public String add(KnowledgeShareInfoDto dto) {
        // 获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 保存知识分享详情信息
        KnowledgeShareDetail detail = new KnowledgeShareDetail();
        BeanUtils.copyProperties(dto, detail);
        detail.setId(id);
        detail.setCreateById(userDTO.getId());
        detail.setCreateTime(new Date());
        detail.setUpdateById(userDTO.getId());
        detail.setUpdateTime(new Date());
        detail.setDelFlag(0);
        detail.setOfficeId(userDTO.getOfficeDTO().getId());
        detail.setCompanyId(userDTO.getCompanyDTO().getId());
        detailMapper.insert(detail);
        // 保存富文本中的文件
        editorFilesService.remove(new QueryWrapper<EditorFiles>().lambda().eq(EditorFiles::getSourceId,id));
        if (CollectionUtil.isNotEmpty(dto.getEditorFilesDTOList())) {
            dto.getEditorFilesDTOList().stream().forEach(item->{
                editorFilesService.saveUrl(item.getTemporaryUrl(),item.getUrl(),id);
            });
        }
        // 保存附件信息
        if (ObjectUtil.isNotEmpty(dto.getFiles())) {
            AtomicInteger sort = new AtomicInteger(1);
            dto.getFiles().stream().forEach(item->{
                //保存附件信息
                WorkAttachmentInfo workAttachmentDto = new WorkAttachmentInfo();
                workAttachmentDto.setName(item.getName());
                workAttachmentDto.setSize(item.getSize());
                workAttachmentDto.setUrl(item.getUrl());
                Map<String,String> map = new HashMap<>();
                String workAttachmentDtoInfo = JSON.toJSONString(workAttachmentDto);
                String userDTOInfo = JSON.toJSONString(userDTO);
                String attachmentId = id;
                String attachmentFlag = "knowledgeShare";
                String sortInfo = Integer.toString(sort.get());
                map.put("workAttachmentDtoInfo",workAttachmentDtoInfo);
                map.put("userDTOInfo",userDTOInfo);
                map.put("attachmentId",attachmentId);
                map.put("attachmentFlag",attachmentFlag);
                map.put("sortInfo",sortInfo);
                String fileId = SpringUtil.getBean ( IWorkAttachmentApi.class ).saveFile(map);
                sort.getAndIncrement();
            });
        }
        return "操作完成";
    }

    public String update(KnowledgeShareInfoDto dto) {
        // 获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());

        // 保存知识分享详情信息
        KnowledgeShareDetail detail = new KnowledgeShareDetail();
        BeanUtils.copyProperties(dto, detail);
        detail.setUpdateById(userDTO.getId());
        detail.setUpdateTime(new Date());
        detailMapper.updateById(detail);
        // 保存富文本中的文件
        editorFilesService.remove(new QueryWrapper<EditorFiles>().lambda().eq(EditorFiles::getSourceId,dto.getId()));
        if (CollectionUtil.isNotEmpty(dto.getEditorFilesDTOList())) {
            dto.getEditorFilesDTOList().stream().forEach(item->{
                editorFilesService.saveUrl(item.getTemporaryUrl(),item.getUrl(),dto.getId());
            });
        }
        // 保存附件信息
        if (ObjectUtil.isNotEmpty(dto.getFiles())) {
            SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(dto.getId());
            AtomicInteger sort = new AtomicInteger(1);
            dto.getFiles().stream().forEach(item->{
                //保存附件信息
                WorkAttachmentInfo workAttachmentDto = new WorkAttachmentInfo();
                workAttachmentDto.setName(item.getName());
                workAttachmentDto.setSize(item.getSize());
                workAttachmentDto.setUrl(item.getUrl());
                Map<String,String> map = new HashMap<>();
                String workAttachmentDtoInfo = JSON.toJSONString(workAttachmentDto);
                String userDTOInfo = JSON.toJSONString(userDTO);
                String attachmentId = dto.getId();
                String attachmentFlag = "knowledgeShare";
                String sortInfo = Integer.toString(sort.get());
                map.put("workAttachmentDtoInfo",workAttachmentDtoInfo);
                map.put("userDTOInfo",userDTOInfo);
                map.put("attachmentId",attachmentId);
                map.put("attachmentFlag",attachmentFlag);
                map.put("sortInfo",sortInfo);
                String fileId = SpringUtil.getBean ( IWorkAttachmentApi.class ).saveFile(map);
                sort.getAndIncrement();
            });
        }
        return "操作完成";
    }

    public KnowledgeShareInfoDto findById(String id, String method, Integer size) {
        KnowledgeShareInfoDto dto = new KnowledgeShareInfoDto();
        // 获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if ("view".equals(method)) {
            // 保存访问信息
            saveVisit(id, userDTO);
        }
        // 查询数据
        KnowledgeShareDetail detail = detailMapper.selectById(id);

        // 富文本图片查询
        if (ObjectUtil.isNotEmpty(detail)) {
            BeanUtils.copyProperties(detail, dto);
            dto.setTypeName(typeMapper.selectById(detail.getTypeId()).getKlgsType());
            if(StringUtils.isNotBlank(detail.getDetail())){
                String newContent = editorFilesService.getNewContent(detail.getDetail(), id);
                dto.setDetail(newContent);
                KnowledgeShareDetail k = new KnowledgeShareDetail();
                k.setId(id);
                k.setDetail(newContent);
                detailMapper.update(k, new QueryWrapper<KnowledgeShareDetail>().lambda().eq(KnowledgeShareDetail::getId, id));
                List<EditorFiles> list = editorFilesService.list(new QueryWrapper<EditorFiles>().lambda().eq(EditorFiles::getSourceId, id));
                List<EditorFilesDTO> editorFilesDTOList = new ArrayList<>();
                list.stream().forEach(item->{
                    EditorFilesDTO editorFilesDTO = new EditorFilesDTO();
                    editorFilesDTO.setSourceId(item.getSourceId());
                    editorFilesDTO.setTemporaryUrl(item.getTemporaryUrl());
                    editorFilesDTO.setUrl(item.getUrl());
                    editorFilesDTOList.add(editorFilesDTO);
                });
                dto.setEditorFilesDTOList(editorFilesDTOList);
            }
        }

        // 查询访问记录
        LambdaQueryWrapper<KnowledgeShareVisit> visitWrapper = new LambdaQueryWrapper<>();
        visitWrapper.eq(KnowledgeShareVisit::getDetailId, id).eq(BaseEntity::getDelFlag, 0);
        List<KnowledgeShareVisit> visits = visitMapper.selectByDetailId(size,id);
        if (CollectionUtils.isNotEmpty(visits)) {
            visits.stream().forEach(i -> {
                UserDTO visitUser = SpringUtil.getBean(IUserApi.class).getById(i.getUserId());
                i.setUserId(visitUser.getName());
            });
        }
        dto.setVisits(visits);
        //查询访问人数
        Integer integer = visitMapper.selectCount(visitWrapper);
        dto.setVisitNum(integer);

        // 查询回复记录
        LambdaQueryWrapper<KnowledgeShareComment> commentWrapper = new LambdaQueryWrapper<>();
        commentWrapper.eq(KnowledgeShareComment::getDetailId, id).eq(BaseEntity::getDelFlag, 0).orderByDesc(BaseEntity::getCreateTime);
        List<KnowledgeShareComment> comments = commentMapper.selectList(commentWrapper);
        if (CollectionUtils.isNotEmpty(comments)) {
            comments.stream().forEach(i -> {
                UserDTO commentUser = SpringUtil.getBean(IUserApi.class).getById(i.getUserId());
                i.setUserId(commentUser.getName());
                i.setDeff(timeDef(i.getCreateTime()));
            });
        }
        dto.setComments(comments);
        // 查询附件信息
        List<WorkAttachmentInfoDTO> files = detailMapper.findDtos(id);
        if (CollectionUtils.isNotEmpty(files)) {
            for (WorkAttachmentInfoDTO i : files) {
                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
            }
            dto.setFiles(files);
        }
        return dto;
    }

    public String removeById(String id) {
        // 删除知识分享主表
        detailMapper.deleteById(id);
        // 删除知识分享浏览记录表
        LambdaQueryWrapper<KnowledgeShareVisit> visitWrapper = new LambdaQueryWrapper<>();
        visitWrapper.eq(KnowledgeShareVisit::getDetailId, id).eq(BaseEntity::getDelFlag, 0);
        visitMapper.delete(visitWrapper);
        // 删除知识分享评论表
        LambdaQueryWrapper<KnowledgeShareComment> commentWrapper = new LambdaQueryWrapper<>();
        commentWrapper.eq(KnowledgeShareComment::getDetailId, id).eq(BaseEntity::getDelFlag, 0);
        commentMapper.delete(commentWrapper);
        // 删除附件信息表
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(id);
        return "操作完成";
    }

    public String addComment(KnowledgeShareComment comment) {
        // 获取当前登录人
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        comment.setId(id);
        comment.setCreateById(userDTO.getId());
        comment.setCreateTime(new Date());
        comment.setUpdateById(userDTO.getId());
        comment.setUpdateTime(new Date());
        comment.setDelFlag(0);
        comment.setUserId(userDTO.getId());
        commentMapper.insert(comment);
        return "操作完成";
    }

    public String delComment(String id) {
        commentMapper.deleteById(id);
        return "操作完成";
    }

    /**
     * 保存访问记录
     */
    public Boolean saveVisit(String id, UserDTO userDTO) {
        LambdaQueryWrapper<KnowledgeShareVisit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseEntity::getDelFlag, 0).eq(KnowledgeShareVisit::getDetailId, id).eq(KnowledgeShareVisit::getUserId, userDTO.getId());
        KnowledgeShareVisit visit = visitMapper.selectOne(wrapper);
        if (visit != null) {
            // 访问记录存在，则增加访问次数和更改最近访问时间
            visit.setNum(visit.getNum() + 1);
            visit.setLastTime(new Date());
            visitMapper.updateById(visit);
        } else {
            // 访问记录不存在，则新增访问记录
            visit = new KnowledgeShareVisit();
            // 生成id
            String visitId = UUID.randomUUID().toString().replace("-", "");
            visit.setId(visitId);
            visit.setCreateById(userDTO.getId());
            visit.setCreateTime(new Date());
            visit.setUpdateById(userDTO.getId());
            visit.setUpdateTime(new Date());
            visit.setDelFlag(0);
            visit.setDetailId(id);
            visit.setUserId(userDTO.getId());
            visit.setFirstTime(new Date());
            visit.setLastTime(new Date());
            visit.setNum(1);
            visitMapper.insert(visit);
        }
        return true;
    }

    /**
     * 计算时间差
     */
    public String timeDef(Date time) {
        Long def = new Date().getTime() - time.getTime();
        // 计算天数
        long day = def / (1000 * 60 * 60 * 24);
        if (day != 0) {
            return day + "天前";
        }
        // 计算小时
        long house = def / (1000 * 60 * 60);
        if (house != 0) {
            return house + "小时前";
        }
        // 计算分钟
        long min = def / (1000 * 60);
        return min + "分钟前";
    }

    /**
     * 查询评论
     * @param id
     * @return
     */
    public KnowledgeShareInfoDto getComments(String id) {
        KnowledgeShareInfoDto knowledgeShareInfoDto = new KnowledgeShareInfoDto();
        // 查询回复记录
        LambdaQueryWrapper<KnowledgeShareComment> commentWrapper = new LambdaQueryWrapper<>();
        commentWrapper.eq(KnowledgeShareComment::getDetailId, id).eq(BaseEntity::getDelFlag, 0).orderByDesc(BaseEntity::getCreateTime);
        List<KnowledgeShareComment> comments = commentMapper.selectList(commentWrapper);
        if (CollectionUtils.isNotEmpty(comments)) {
            comments.stream().forEach(i -> {
                UserDTO commentUser = SpringUtil.getBean(IUserApi.class).getById(i.getUserId());
                i.setUserId(commentUser.getName());
                i.setDeff(timeDef(i.getCreateTime()));
            });
        }
        knowledgeShareInfoDto.setComments(comments);
        return knowledgeShareInfoDto;
    }
}
