package com.gic.haoban.manage.web.controller.content;

import cn.hutool.core.util.ObjectUtil;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.PageHelperUtils;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.content.api.dto.comment.ListCommentDTO;
import com.gic.content.api.dto.comment.ListSonCommentDTO;
import com.gic.content.api.dto.comment.SonCommentInfoDTO;
import com.gic.content.api.enums.MaterialPurposeEnum;
import com.gic.content.api.enums.UserTypeEnum;
import com.gic.content.api.qdto.comment.ListMobileCommentQDTO;
import com.gic.content.api.qdto.comment.SaveCommentQDTO;
import com.gic.content.api.service.ContentMaterialCommentApiService;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.api.enums.HaobanClerkTypeEnum;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.service.StaffClerkRelationApiService;
import com.gic.haoban.manage.web.qo.content.comment.CommentCountQO;
import com.gic.haoban.manage.web.qo.content.comment.CommentInfoVO;
import com.gic.haoban.manage.web.qo.content.comment.SaveCommentQO;
import com.gic.haoban.manage.web.qo.content.comment.SonCommentInfoVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 好办-知识库-评论
 * @Author MUSI
 * @Date 2023/9/19 3:16 PM
 * @Description
 * @Version
 **/
@RestController
@RequestMapping(path = "/comment")
public class CommentController {

    @Autowired
    private ContentMaterialCommentApiService contentMaterialCommentApiService;

    @Autowired
    private StaffClerkRelationApiService staffClerkRelationApiService;
    @Autowired
    private StaffApiService staffApiService;

    /**
     * 评论总数（包含子评论）
     * @return
     */
    @RequestMapping(path = "/count-comment")
    public RestResponse<Integer> countContentComment(CommentCountQO commentCountQO) {

        ListMobileCommentQDTO mobileCommentQDTO = new ListMobileCommentQDTO();
        mobileCommentQDTO.setEnterpriseId(commentCountQO.getEnterpriseId());
        mobileCommentQDTO.setContentMaterialId(commentCountQO.getContentMaterialId());
        mobileCommentQDTO.setMemberId(commentCountQO.getClerkId());
        mobileCommentQDTO.setMaterialPurpose(3);
        ServiceResponse<Integer> serviceResponse = contentMaterialCommentApiService.countCommentForWechat(mobileCommentQDTO);
        return RestResponse.successResult(serviceResponse.getResult());
    }

    /**
     * 评论列表
     * @param commentCountQO
     * @return
     */
    @RequestMapping(path = "/list-comment")
    public RestResponse<Page<CommentInfoVO>> listCommentInfoVo(CommentCountQO commentCountQO) {
        ListMobileCommentQDTO mobileCommentQDTO = EntityUtil.changeEntityByJSON(ListMobileCommentQDTO.class, commentCountQO);
        mobileCommentQDTO.setEnterpriseId(commentCountQO.getEnterpriseId());
        mobileCommentQDTO.setContentMaterialId(commentCountQO.getContentMaterialId());
        mobileCommentQDTO.setMemberId(commentCountQO.getClerkId());
        mobileCommentQDTO.setMaterialPurpose(MaterialPurposeEnum.KNOWLEDGE.code);
        ServiceResponse<Page<ListCommentDTO>> serviceResponse = contentMaterialCommentApiService.listComment(mobileCommentQDTO);
        if (!serviceResponse.isSuccess()) {
            return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
        }
        if (CollectionUtils.isEmpty(serviceResponse.getResult().getResult())) {
            return RestResponse.successResult();
        }
        List<Long> contentMaterialCommentIds = serviceResponse.getResult().getResult().stream().map(ListCommentDTO::getContentMaterialCommentId).collect(Collectors.toList());
        //获取子评论信息
        ServiceResponse<Map<Long, SonCommentInfoDTO>> filterAuditStatusByContentMaterialCommentIds = contentMaterialCommentApiService.getFilterAuditStatusByContentMaterialCommentIds(mobileCommentQDTO, contentMaterialCommentIds);
        Map<Long, SonCommentInfoDTO> sonCommentInfoDTOMap = filterAuditStatusByContentMaterialCommentIds.getResult();
        serviceResponse.getResult().getResult().forEach(comment -> {
            if (sonCommentInfoDTOMap.containsKey(comment.getContentMaterialCommentId())) {
                SonCommentInfoDTO sonCommentInfoDTO = sonCommentInfoDTOMap.get(comment.getContentMaterialCommentId());

                comment.setSonComments(ObjectUtil.isNotNull(sonCommentInfoDTO.getListSonCommentDTO()) ? Collections.singletonList(sonCommentInfoDTO.getListSonCommentDTO()) : new ArrayList<>());
                comment.setSonCommentNum(sonCommentInfoDTO.getTotal());
            }
        });
        Page<CommentInfoVO> commentInfoVOPage = PageHelperUtils.changePageToCurrentPage(serviceResponse.getResult(), CommentInfoVO.class);
        return RestResponse.successResult(commentInfoVOPage);
    }

    /**
     * 子评论列表
     * @return
     */
    @RequestMapping(path = "/list-son-comment")
    public RestResponse<Page<SonCommentInfoVO>> listSonComment(CommentCountQO commentCountQO) {

        if (ObjectUtil.isEmpty(commentCountQO.getNextContentMaterialCommentId())){
            commentCountQO.setNextContentMaterialCommentId(0L);
        }
        ListMobileCommentQDTO listMobileCommentQDTO = EntityUtil.changeEntityByJSON(ListMobileCommentQDTO.class, commentCountQO);
        listMobileCommentQDTO.setMemberId(commentCountQO.getClerkId());
        listMobileCommentQDTO.setMaterialPurpose(MaterialPurposeEnum.KNOWLEDGE.code);
        ServiceResponse<Page<ListSonCommentDTO>> serviceResponse = contentMaterialCommentApiService.listSonCommentForWechat(listMobileCommentQDTO);
        if (!serviceResponse.isSuccess()) {
            return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
        }
        Page<SonCommentInfoVO> commentInfoVOPage = PageHelperUtils.changePageToCurrentPage(serviceResponse.getResult(), SonCommentInfoVO.class);
        return RestResponse.successResult(commentInfoVOPage);
    }

    /**
     * 添加评论
     * @param saveCommentQO
     * @return
     */
    @RequestMapping(path = "/save-comment")
    public RestResponse<SonCommentInfoVO> saveComment(@RequestBody SaveCommentQO saveCommentQO) {
        SaveCommentQDTO saveCommentQDTO = EntityUtil.changeEntityByJSON(SaveCommentQDTO.class, saveCommentQO);
        saveCommentQDTO.setMemberId(saveCommentQO.getClerkId());
        saveCommentQDTO.setReplyMemberId(saveCommentQO.getReplyClerkId());
        List<String> clerkIds = new ArrayList<>();
        clerkIds.add(saveCommentQO.getClerkId());
        if (StringUtils.isNotBlank(saveCommentQO.getReplyClerkId())) {
            clerkIds.add(saveCommentQO.getReplyClerkId());
        }
        Map<String, StaffClerkRelationDTO> clerkInfoMap = this.getClerkInfoMap(saveCommentQO.getWxEnterpriseId(), clerkIds);
        List<String> staffIds = new ArrayList<>();
        for (StaffClerkRelationDTO value : clerkInfoMap.values()) {
            staffIds.add(value.getStaffId());
        }
        Map<String, StaffDTO> staffDTOMap = this.queryStaffInfoMap(staffIds);
        StaffClerkRelationDTO staffClerkRelationDTO = clerkInfoMap.get(saveCommentQO.getClerkId());
        saveCommentQDTO.setUserType(UserTypeEnum.CLERK.value);
        if (staffClerkRelationDTO != null) {
            saveCommentQDTO.setUserCode(staffClerkRelationDTO.getClerkCode());
            StaffDTO staffDTO = staffDTOMap.get(staffClerkRelationDTO.getStaffId());
            if (staffDTO != null) {
                saveCommentQDTO.setUserHeadImage(staffDTO.getHeadImg());
            }
            if (HaobanClerkTypeEnum.AREA_MANAGER.getCode().equals(staffClerkRelationDTO.getClerkType())) {
                saveCommentQDTO.setUserType(UserTypeEnum.AREA_MANAGER.value);
            }else {
                saveCommentQDTO.setUserType(UserTypeEnum.CLERK.value);
            }
        }
        staffClerkRelationDTO = clerkInfoMap.get(saveCommentQO.getReplyClerkId());
        if (staffClerkRelationDTO != null) {
            saveCommentQDTO.setReplyUserCode(staffClerkRelationDTO.getClerkCode());
            StaffDTO staffDTO = staffDTOMap.get(staffClerkRelationDTO.getStaffId());
            if (staffDTO != null) {
                saveCommentQDTO.setReplyUserHeadImage(staffDTO.getHeadImg());
            }
            if (HaobanClerkTypeEnum.AREA_MANAGER.getCode().equals(staffClerkRelationDTO.getClerkType())) {
                saveCommentQDTO.setReplyUserType(UserTypeEnum.AREA_MANAGER.value);
            }else {
                saveCommentQDTO.setReplyUserType(UserTypeEnum.CLERK.value);
            }
        }
        saveCommentQDTO.setAuditStatus(2);
        saveCommentQDTO.setMaterialPurpose(MaterialPurposeEnum.KNOWLEDGE.code);
        saveCommentQDTO.setShowFlag(1);
        ServiceResponse<ListSonCommentDTO> serviceResponse = contentMaterialCommentApiService.saveComment(saveCommentQDTO);
        SonCommentInfoVO sonCommentInfoVO = EntityUtil.changeEntityByJSON(SonCommentInfoVO.class, serviceResponse.getResult());
        return RestResponse.successResult(sonCommentInfoVO);
    }

    public Map<String, StaffClerkRelationDTO> getClerkInfoMap(String wxEnterpriseId, List<String> clerkIds) {
        List<StaffClerkRelationDTO> staffClerkRelations = staffClerkRelationApiService.listByClerkIdsWxEnterpriseId(clerkIds, wxEnterpriseId);

        if (CollectionUtils.isEmpty(staffClerkRelations)) {
            return Collections.emptyMap();
        }
        return staffClerkRelations
                .stream()
                .collect(Collectors.toMap(StaffClerkRelationDTO::getClerkId, Function.identity(), (v1, v2) -> v1));
    }

    public Map<String, StaffDTO> queryStaffInfoMap(List<String> staffIds) {
        List<StaffDTO> staffDTOS = staffApiService.listByIds(staffIds);
        return staffDTOS
                .stream()
                .collect(Collectors.toMap(StaffDTO::getStaffId, Function.identity(), (v1, v2) -> v1));
    }

}
