package com.cyksj.web.controller.manage.corp;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.model.entity.QyMsgContent;
import com.cyksj.model.manage.views.CorpFollowMsgView;
import com.cyksj.model.manage.views.CorpMsgAuditUserView;
import com.cyksj.service.corp.CorpQyMsgContentService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.operator.InList;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author chan
 * @date 2024/1/22 14:25
 */
@RequiredArgsConstructor
@Slf4j
@RestController
@RequestMapping("/manage/corp/msg/audit")
public class CorpMsgAuditController {

    private final BeanSearcher beanSearcher;

    private final HttpServletRequest request;

    private final CorpQyMsgContentService corpQyMsgContentService;



    /**
     * 会话存档用户列表
     * @param textKey 关键词搜索
     * @param tagId 标签筛选
     * @return
     */
    @GetMapping
    public Result<SearchResult<CorpMsgAuditUserView>> get(String textKey, String tagId, Integer intention) {
        Set<String> userIds = new HashSet<>();
        if(StringUtils.isNotBlank(textKey)){
            List<QyMsgContent> text = corpQyMsgContentService.list(Wrappers.lambdaQuery(QyMsgContent.class).select(QyMsgContent::getFrom, QyMsgContent::getExternalUserid,QyMsgContent::getTolist).like(QyMsgContent::getText, textKey).eq(QyMsgContent::getRoomid,"").eq(QyMsgContent::getMsgtype, "text"));
            userIds = text.stream().map(QyMsgContent::getExternalUserid).collect(Collectors.toSet());
        }
        MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
        if (userIds.size() > 0) {
            builder.field(CorpMsgAuditUserView::getExternalUserid,userIds).op(InList.class);
        }
        if(StringUtils.isNotBlank(tagId)){
            builder.put("tag", String.format( "and cr.id = t.relation_id and t.tag_id = '%s'", tagId));
            builder.put("tagTable", ",corp_user_tag t");
        }
        if (intention != null) {
            builder.put("intention", String.format("and exists (select 1 from corp_user_pay_intention cup where cup.union_id = c.unionid and intention = %s limit 1)", intention));
        }
        SearchResult<CorpMsgAuditUserView> search = beanSearcher.search(CorpMsgAuditUserView.class, builder.build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);

    }

    /**
     * 获取会话列表
     */
    @GetMapping("/msgList")
    public Result<SearchResult<CorpFollowMsgView>> msgList(String keyword){
        MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
        if(StringUtils.isNotBlank(keyword)){
            builder.put("keyword", String.format("where q.text like '%s%%')",keyword));
        }
        SearchResult<CorpFollowMsgView> search = beanSearcher.search(CorpFollowMsgView.class, builder.build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }


    /**
     * 获取聊天记录
     */
    @GetMapping("/getMsgByFollowIdAndUserId")
    public Result<SearchResult<QyMsgContent>> getMsgByFollowIdAndUserId(){
        Map<String, Object> build = MapUtils.flatBuilder(request.getParameterMap()).build();
        log.info("获取聊天记录 param:{}", JSONUtil.toJsonStr(build));
        if (!build.containsKey("followId") || !build.containsKey("externalUserid")){
            throw BusinessRuntimeException.getInstance("缺少必填参数.");
        }
        SearchResult<QyMsgContent> search = beanSearcher.search(QyMsgContent.class, build);
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }


}
