package com.storlead.sales.service.impl.customer;

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.extension.plugins.pagination.Page;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.vo.StaffVo;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.sales.pojo.dto.customer.CommentQueryDTO;
import com.storlead.sales.pojo.entity.customer.BulletinEntity;
import com.storlead.sales.pojo.entity.customer.BulletinReadEntity;
import com.storlead.sales.pojo.entity.customer.RecordCommentEntity;
import com.storlead.sales.pojo.vo.customer.RecordCommentVO;
import com.storlead.sales.mapper.customer.RecordCommentMapper;
import com.storlead.sales.service.customer.RecordCommentService;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

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

/**
 * <p>
 * 通用评论表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-05-16
 */
@Service
public class RecordCommentServiceImpl extends MyBaseServiceImpl<RecordCommentMapper, RecordCommentEntity> implements RecordCommentService {

    @Resource
    private IUserService userService;

    @Resource
    private BulletinServiceImpl bulletinService;

    @Override
    public Result<IPage<RecordCommentVO>> fillTaskList(CommentQueryDTO dto) {
        IPage<RecordCommentVO> result = new Page<>(dto.getPageIndex(),dto.getPageSize());
        Long recordId = dto.getRecordId();
        Integer type = dto.getType();

        LambdaQueryWrapper<RecordCommentEntity> queryWrapper = new LambdaQueryWrapper();
        if (!ObjectUtils.isEmpty(dto.getRecordIds())) {
            List<Long> recordIdList = Arrays.stream(dto.getRecordIds().split(",")).map(s -> Long.parseLong(s.trim())).
                    collect(Collectors.toList());

            queryWrapper.in(RecordCommentEntity::getRecordId, recordIdList);
        }
        if (!ObjectUtils.isEmpty(dto.getRecordId())){
            queryWrapper.eq(RecordCommentEntity::getRecordId, recordId);
        }else {
            if (ObjectUtils.isEmpty(dto.getRecordIds())){
                return Result.result(result);
            }
        }


        queryWrapper.eq(RecordCommentEntity::getParentId,0);
        queryWrapper.eq(RecordCommentEntity::getIsDelete,0);
        queryWrapper.eq(RecordCommentEntity::getType,type);
//        queryWrapper.orderByDesc(RecordComment::getCreateTime);
        queryWrapper.orderByAsc(RecordCommentEntity::getCreateTime);

        IPage<RecordCommentEntity> page = new Page<>(dto.getPageIndex(),dto.getPageSize());

        IPage<RecordCommentEntity> pageData = this.page(page,queryWrapper);

        List<RecordCommentEntity> list = pageData.getRecords();
//        IPage<RecordCommentVO> result = new Page<>(dto.getPageIndex(),dto.getPageSize());
        if (CollectionUtils.isEmpty(list)){
            return Result.result(result);
        }

        List<RecordCommentVO> recordVoList = new ArrayList<>();
        if(list!=null && !list.isEmpty()) {
            List<String> staffIds = new ArrayList<>();
            list.stream().forEach(item-> {
                staffIds.addAll(getStaffList(item));
            });
            if(!staffIds.isEmpty()) {
                Map<String,List<StaffVo>> staffListMap = this.convertUserList(staffIds);
                list.stream().forEach(record -> {
                    recordVoList.add(entityToVo(record,staffListMap));
                });
            }

            //获取点赞数
            setLikeCount(recordVoList);
            //获取是否点赞
            setIsLikeCount(recordVoList);
        }
        LoginUser sysUser = LoginUserUtil.getLoginUser();
        // 判断删除权限
//        if (Integer.valueOf(120).equals(dto.getType())){
//
//            BulletinEntity bulletin = bulletinService.getById(dto.getRecordIds());
//
//            recordVoList.forEach(s->s.setCanDelete(canDelete(sysUser,s,Objects.isNull(bulletin) ? null : bulletin.getOwnerBy())));
//        }

        //添加子评论
//        List<Long> recordParentIds = Arrays.asList(recordId);
        List<RecordCommentVO> recordCommentVOList = new ArrayList<>();
        List<Long> recordParentIds = recordVoList.stream().map(RecordCommentVO::getId).collect(Collectors.toList());
        if(recordParentIds.size()>0){
            recordCommentVOList = baseMapper.getChildComment(recordParentIds);

//            for (RecordCommentVO recordCommentVO:recordCommentVOList){
//                recordCommentVO.setCanDelete(canDelete(sysUser,recordCommentVO));
//            }
//                recordCommentVOList.forEach(t->t.setCanDelete(canDelete(sysUser,t)));
            // 判断删除权限
//            if (dto.getType().equals(120)){
//                BulletinEntity bulletin = bulletinService.getById(dto.getRecordIds());
//                recordCommentVOList.forEach(s->s.setCanDelete(canDelete(sysUser,s,Objects.isNull(bulletin) ? null : bulletin.getOwnerBy())));
//            }


        }
//        List<RecordCommentVo> recordCommentVoList = baseMapper.getChildComment(recordParentIds);
//        recordCommentVoList.forEach(s->s.setCanDelete(canDelete(sysUser,s)));

        if(recordCommentVOList != null){
            for (RecordCommentVO recordCommentVo:recordVoList){
                List<RecordCommentVO> recordCommentChildVoList = recordCommentVOList.stream().filter(s->s.getTopId().equals(recordCommentVo.getId())).collect(Collectors.toList());
                if(recordCommentChildVoList != null){
//                    recordCommentChildVoList.forEach(p->p.setStaffParentName(recordCommentVo.getStaffName()));
                    recordCommentVo.setCommentList(recordCommentChildVoList);
                }
            }
            setLikeCount(recordCommentVOList);
            //获取是否点赞
            setIsLikeCount(recordCommentVOList);

        }
        result.setCurrent(pageData.getCurrent());
        result.setTotal(pageData.getTotal());
        result.setRecords(recordVoList);
        SysBaseField.orgFileds(recordVoList);

        return Result.result(result);
    }

    @Override
    public List<RecordCommentVO> listCommont(Integer type,List<Long> dataIds) {
        LambdaQueryWrapper<RecordCommentEntity> queryWrapper = new LambdaQueryWrapper();
        if (!ObjectUtils.isEmpty(dataIds)) {
            List<Long> recordIdList = dataIds;
            queryWrapper.in(RecordCommentEntity::getRecordId, recordIdList);
        }
        queryWrapper.eq(RecordCommentEntity::getParentId,0);
        queryWrapper.eq(RecordCommentEntity::getIsDelete,0);
        queryWrapper.eq(RecordCommentEntity::getType,type);
        queryWrapper.orderByAsc(RecordCommentEntity::getCreateTime);
        List<RecordCommentEntity> list = this.list(queryWrapper);

        List<RecordCommentVO> recordVoList = new ArrayList<>();
        if(list!=null && !list.isEmpty()) {
            List<String> staffIds = new ArrayList<>();
            list.stream().forEach(item-> {
                staffIds.addAll(getStaffList(item));
            });
            if(!staffIds.isEmpty()) {
                Map<String,List<StaffVo>> staffListMap = this.convertUserList(staffIds);
                list.stream().forEach(record -> {
                    recordVoList.add(entityToVo(record,staffListMap));
                });
            }
        }

        List<RecordCommentVO> recordCommentVOList = new ArrayList<>();
        List<Long> recordParentIds = recordVoList.stream().map(RecordCommentVO::getId).collect(Collectors.toList());
        if(recordParentIds.size()>0) {
            recordCommentVOList = baseMapper.getChildComment(recordParentIds);

            if(recordCommentVOList != null){
                for (RecordCommentVO recordCommentVo:recordVoList){
                    List<RecordCommentVO> recordCommentChildVoList = recordCommentVOList.stream().filter(s->s.getTopId().equals(recordCommentVo.getId())).collect(Collectors.toList());
                    if(recordCommentChildVoList != null){
                        recordCommentVo.setCommentList(recordCommentChildVoList);
                    }
                }
            }
        }
        return recordVoList;
    }

    /***
     * @Description: 根据父级id递归删除所有子评论
     * @Param: id
     * @return:
     * @Author: YPZ
     * @Date: 2023/4/4 17:51
     */
    @Override
    public void removeByParentid(Long id) {
        baseMapper.removeByParentid(id);
    }

    @Override
    public Map<Long, Integer> getRecordNumMap(String type, List<Long> customerFollowUpIdList) {

        QueryWrapper<RecordCommentEntity> wrapper = new QueryWrapper<>();
        wrapper.select("record_id, COUNT(1) AS count")
                .eq("type", type)
                .eq("is_delete", CommonConstant.DEL_FLAG_0)
                .groupBy("record_id");

        // 执行查询并返回 Map<Long, Integer>
        List<Map<String, Object>> result = listMaps(wrapper);
        if (CollectionUtils.isEmpty(result)){
            return new HashMap<>();
        }
        return result.stream()
                .collect(Collectors.toMap(
                        map -> Long.valueOf(map.get("record_id").toString()),
                        map -> Integer.valueOf(map.get("count").toString())
                ));
    }


    private List<String> getStaffList(RecordCommentEntity recordCommentEntity) {
        List<String> staffIds = new ArrayList<>();
        if(recordCommentEntity.getStaffId()!=null) {
            staffIds.add(String.valueOf(recordCommentEntity.getStaffId()));
        }
        return staffIds;
    }

    private Map<String,List<StaffVo>> convertUserList(List<String> staffIds) {
        List<Long> ids = new ArrayList<>();
        staffIds.stream().forEach(item-> {
            ids.addAll(Arrays.asList(item.split(",")).stream().map(s -> Long.valueOf(s)).collect(Collectors.toList()));
        });
        List<UserEntity> userList =  new ArrayList<>(userService.getUserListByStaffIds(ids));
        Map<Long, UserEntity> userName = userList.stream().collect(Collectors.toMap(UserEntity::getId, Function.identity(), (key1, key2) -> key2));
        Map<String,List<StaffVo>> staffList = new HashMap<>();
        staffIds.stream().forEach(item-> {
            List<StaffVo> recordVos = new ArrayList<>();
            List<Long> recordIdList = Arrays.asList(item.split(",")).stream().map(s -> Long.valueOf(s)).collect(Collectors.toList());
            for (int i=0;i<recordIdList.size();i++) {
                UserEntity user = userName.get(recordIdList.get(i));
                if(user!=null) {
                    StaffVo staffVo = new StaffVo();
                    staffVo.setStaffId(user.getId());
                    staffVo.setStaffName(user.getRealName());
                    staffVo.setStaffPhoto(user.getAvatar());
                    recordVos.add(staffVo);
                }
            }
            staffList.put(item, recordVos);
        });
        return staffList;
    }



    private RecordCommentVO entityToVo(RecordCommentEntity recordCommentEntity, Map<String,List<StaffVo>> staffListMap) {
        RecordCommentVO recordVo = new RecordCommentVO();
        BeanUtils.copyProperties(recordCommentEntity, recordVo);
        List<StaffVo> createStaffList = staffListMap.get(String.valueOf(recordCommentEntity.getStaffId()));
        if(createStaffList!=null&&createStaffList.size()>0) {
            recordVo.setStaffName(createStaffList.get(0).getStaffName());
            recordVo.setStaffPhoto(createStaffList.get(0).getStaffPhoto());
        }
        return recordVo;
    }

    /**
     * 设置是否点赞
     * @param recordComments
     */
    private void setIsLikeCount(List<RecordCommentVO> recordComments) {
        if(CollectionUtils.isEmpty(recordComments)){
            return;
        }

//        Long currentUserId = LoginUserUtil.getCurrentUserId();
//        Set<Long> commentIds = recordComments.stream().map(RecordCommentVO::getId).collect(Collectors.toSet());
//        Map<Long, Integer> likeMaps = recordCommentLikeService.isLike(commentIds, currentUserId);
//        recordComments.forEach(
//                (recordComment)->{
//                    recordComment.setIsLike(likeMaps.get(recordComment.getId()));
//                }
//        );

    }

    /**
     * 获取点赞数
     * @param recordComments
     */
    private void setLikeCount(List<RecordCommentVO> recordComments) {
        if(recordComments==null||recordComments.size()==0){
            return;
        }
        Set<Long> recordCommentIds = recordComments.stream().map(RecordCommentVO::getId).collect(Collectors.toSet());
//        Map<Long, List<RecordCommentLikeEntity>> listMap = recordCommentLikeService.countByRecordCommentIds(recordCommentIds);
//        recordComments.forEach(
//                (t)->{
//                    List<RecordCommentLikeEntity> recordCommentLikeEntities = listMap.get(t.getId());
//                    if(recordCommentLikeEntities==null){
//                        t.setLikeCount(0);
//                    }else {
//                        t.setLikeCount(recordCommentLikeEntities.size());
//                    }
//
//                }
//        );
    }



    public List<RecordCommentVO> fillCommontList(List<Long> recordIds,Integer type) {
        LambdaQueryWrapper<RecordCommentEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(RecordCommentEntity::getType,type);
        queryWrapper.in(RecordCommentEntity::getRecordId,recordIds);
        queryWrapper.eq(RecordCommentEntity::getParentId,0);
        queryWrapper.eq(RecordCommentEntity::getIsDelete,0);
//        queryWrapper.orderByDesc(TargetReviewComment::getCreateTime);
        queryWrapper.orderByAsc(RecordCommentEntity::getCreateTime);
        List<RecordCommentEntity> list = this.list(queryWrapper);
        List<RecordCommentVO> recordCommentVoList = new ArrayList<>();
        if(list!=null && !list.isEmpty()) {
            List<String> staffIds = new ArrayList<>();
            list.stream().forEach(item-> {
                staffIds.addAll(getStaffList(item));
            });
            if(!staffIds.isEmpty()) {
                Map<String,List<StaffVo>> staffListMap = this.convertUserList(staffIds);
                list.stream().forEach(record -> {
                    recordCommentVoList.add(entityToVo(record,staffListMap));
                });
            }
            //获取点赞数
            setLikeCount(recordCommentVoList);
            //获取是否点赞
            setIsLikeCount(recordCommentVoList);
        }
        LoginUser sysUser = LoginUserUtil.getLoginUser();
//        recordCommentVoList.forEach(s->s.setCanDelete(canDelete(sysUser,s)));
        //添加子评论
        List<Long> recordParentIds = recordCommentVoList.stream().map(recordId->recordId.getId()).collect(Collectors.toList());
        List<RecordCommentVO> recordCommentVOList = new ArrayList<>();
        if(recordParentIds.size()>0){
            recordCommentVOList = baseMapper.getChildComment(recordParentIds);
//            recordCommentVOList.forEach(s->s.setCanDelete(canDelete(sysUser,s)));
        }
//        List<TargetReviewCommentVo> recordCommentVoList = baseMapper.getChildComment(recordParentIds);
//        recordCommentVoList.forEach(s->s.setCanDelete(canDelete(sysUser,s)));
        if(recordCommentVOList != null){
            for (RecordCommentVO recordCommentVo:recordCommentVoList){
                List<RecordCommentVO> recordCommentChildVoList = recordCommentVOList.stream().filter(s->s.getTopId().equals(recordCommentVo.getId())).collect(Collectors.toList());
                if(recordCommentChildVoList != null){
//                    recordCommentChildVoList.forEach(p->p.setStaffParentName(recordCommentVo.getStaffName()));
                    recordCommentVo.setCommentList(recordCommentChildVoList);
                }
            }
            setLikeCount(recordCommentVOList);
            //获取是否点赞
            setIsLikeCount(recordCommentVOList);
        }
        return recordCommentVoList;
    }
    //判断评论是否可以删除
    private Boolean canDelete(LoginUser loginUser, RecordCommentVO recordCommentVo,Long bulletinCreateBy){
        if (loginUser.getId().equals(bulletinCreateBy)) {
            return true;
        }
        if (loginUser.getId().equals(recordCommentVo.getOwnerBy())) {
            return true;
        }
        return false;
    }

    //判断登录人是否是管理员或者自己
//    private Boolean isMeOrAdmin(LoginUser loginUser,Long userId){
//        if(loginUser.getRoleType().equals(UserRoleType.Admin) || userId.equals(loginUser.getId())){
//            return true;
//        }
//        return false;
//    }

}
