package com.jeeplus.test.knowledge.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.core.domain.BaseEntity;
import com.jeeplus.core.service.dto.BaseDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.knowledge.domain.KnowledgeShareComment;
import com.jeeplus.test.knowledge.domain.KnowledgeShareDetail;
import com.jeeplus.test.knowledge.domain.KnowledgeShareVisit;
import com.jeeplus.test.knowledge.mapper.KnowledgeShareCommentMapper;
import com.jeeplus.test.knowledge.mapper.KnowledgeShareDetailMapper;
import com.jeeplus.test.knowledge.mapper.KnowledgeShareTypeMapper;
import com.jeeplus.test.knowledge.mapper.KnowledgeShareVisitMapper;
import com.jeeplus.test.knowledge.service.dto.KnowledgeShareInfoDto;
import com.jeeplus.test.knowledge.service.dto.KnowledgeShareListDto;
import com.jeeplus.test.oss.domain.WorkAttachment;
import com.jeeplus.test.oss.mapper.OssServiceMapper;
import com.jeeplus.test.workContract.mapper.WorkContractInfoMapper;
import com.jeeplus.test.workContract.service.WorkContractService;
import com.jeeplus.test.workContract.service.dto.WorkAttachmentDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class KnowledgeShareInfoService {

    @Resource
    private KnowledgeShareDetailMapper detailMapper;

    @Resource
    private KnowledgeShareVisitMapper visitMapper;

    @Resource
    private KnowledgeShareCommentMapper commentMapper;

    @Resource
    private KnowledgeShareTypeMapper typeMapper;

    @Resource
    private OssServiceMapper ossServiceMapper;

    @Resource
    private WorkContractInfoMapper workContractInfoMapper;

    @Resource
    private WorkContractService workContractService;

    public IPage<KnowledgeShareListDto> list(Page<KnowledgeShareListDto> page, KnowledgeShareDetail detail) {
        return detailMapper.findList(page, 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 = UserUtils.getCurrentUserDTO();
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 保存知识分享详情信息
        KnowledgeShareDetail detail = new KnowledgeShareDetail();
        BeanUtils.copyProperties(dto, detail);
        detail.setId(id);
        detail.setCreateBy(userDTO.getId());
        detail.setCreateDate(new Date());
        detail.setUpdateBy(userDTO.getId());
        detail.setUpdateDate(new Date());
        detail.setDelFlag(0);
        detailMapper.insert(detail);
        // 保存附件信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            workContractService.saveFilesNew(dto.getFiles(), userDTO, id, "knowledgeShare");
        }
        return "操作完成";
    }

    public String update(KnowledgeShareInfoDto dto) {
        // 获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        // 保存知识分享详情信息
        KnowledgeShareDetail detail = new KnowledgeShareDetail();
        BeanUtils.copyProperties(dto, detail);
        detail.setUpdateBy(userDTO.getId());
        detail.setUpdateDate(new Date());
        detailMapper.updateById(detail);
        // 保存附件信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            workContractService.updateFiles(dto.getFiles(), userDTO, dto.getId());
        }
        return "操作完成";
    }

    public KnowledgeShareInfoDto findById(String id, String method) {
        KnowledgeShareInfoDto dto = new KnowledgeShareInfoDto();
        // 获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        if ("view".equals(method)) {
            // 保存访问信息
            saveVisit(id, userDTO);
        }
        // 查询数据
        KnowledgeShareDetail detail = detailMapper.selectById(id);
        BeanUtils.copyProperties(detail, dto);
        dto.setTypeName(typeMapper.selectById(detail.getTypeId()).getKlgsType());
        // 查询访问记录
        LambdaQueryWrapper<KnowledgeShareVisit> visitWrapper = new LambdaQueryWrapper<>();
        visitWrapper.eq(KnowledgeShareVisit::getDetailId, id).eq(BaseEntity::getDelFlag, 0);
        List<KnowledgeShareVisit> visits = visitMapper.selectList(visitWrapper);
        if (CollectionUtils.isNotEmpty(visits)) {
            visits.stream().forEach(i -> {
                UserDTO visitUser = UserUtils.get(i.getUserId());
                i.setUserId(visitUser.getName());
            });
        }
        dto.setVisits(visits);
        // 查询回复记录
        LambdaQueryWrapper<KnowledgeShareComment> commentWrapper = new LambdaQueryWrapper<>();
        commentWrapper.eq(KnowledgeShareComment::getDetailId, id).eq(BaseEntity::getDelFlag, 0).orderByDesc(BaseEntity::getCreateDate);
        List<KnowledgeShareComment> comments = commentMapper.selectList(commentWrapper);
        if (CollectionUtils.isNotEmpty(comments)) {
            comments.stream().forEach(i -> {
                UserDTO commentUser = UserUtils.get(i.getUserId());
                i.setUserId(commentUser.getName());
                i.setDeff(timeDef(i.getCreateDate()));
            });
        }
        dto.setComments(comments);
        // 查询附件信息
        List<WorkAttachmentDto> dtos = workContractInfoMapper.findDtos(id);
        if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(dtos)) {
            for (WorkAttachmentDto i : dtos) {
                i.setCreateBy(UserUtils.get(i.getBy()));
            }
        }
        dto.setFiles(dtos);
        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);
        // 删除附件信息表
        LambdaQueryWrapper<WorkAttachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkAttachment::getAttachmentId, id).eq(BaseDTO::getDelFlag, 0);
        ossServiceMapper.delete(wrapper);
        return "操作完成";
    }

    public String addComment(KnowledgeShareComment comment) {
        // 获取当前登录人
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        comment.setId(id);
        comment.setCreateBy(userDTO.getId());
        comment.setCreateDate(new Date());
        comment.setUpdateBy(userDTO.getId());
        comment.setUpdateDate(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.setCreateBy(userDTO.getId());
            visit.setCreateDate(new Date());
            visit.setUpdateBy(userDTO.getId());
            visit.setUpdateDate(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 + "分钟前";
    }
}
