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

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.corp.CorpUserPayIntentionMapper;
import com.cyksj.model.entity.CorpUserPayIntention;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
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;

    private final CorpUserPayIntentionMapper corpUserPayIntentionMapper;



    /**
     * 会话存档用户列表
     * @param textKey 关键词搜索
     * @param tagIds 标签筛选
     * @return
     */
    @GetMapping
    public Result<SearchResult<CorpMsgAuditUserView>> get(String textKey, @RequestParam(value = "tagIds", required = false) List<String> tagIds, Integer intention, Long talkStartTime, Long talkEndTime) throws Exception {
        long adminId = StpUtil.getLoginIdAsLong();
        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(CollUtil.isNotEmpty(tagIds)){
            StringBuilder tagStr = new StringBuilder();
            if (tagIds.size() == 1) {
                tagStr.append("=").append("'").append(tagIds.get(0)).append("'");
            } else {
                tagStr.append("in").append(Jsons.toJson(tagIds).replaceAll("\\[", "(").replaceAll("]", ")"));
            }
            builder.put("tag", String.format( "and cr.id = t.relation_id and t.tag_id %s", tagStr));
            builder.put("tagTable", ",corp_user_tag t");
        }
        //管理员
        if (adminId == 75l) {
            builder.put("tagTable", ",corp_user_tag t");
            builder.put("tag", String.format("and cr.id = t.relation_id and t.tag_id =  'etvj2DPQAAxqh9QlGJG4N1EbdQBNYGAA'"));
        }
        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));
        }
        if (talkEndTime != null && talkStartTime != null) {
            builder.put("talkTime", String.format(" and exists (select 1 from qy_msg_content qmc where qmc.external_userid = cu.external_userid and qmc.msgtime between %s and %s)", talkStartTime, talkEndTime));
        }
        SearchResult<CorpMsgAuditUserView> search = beanSearcher.search(CorpMsgAuditUserView.class, builder.build());
        search.getDataList().forEach(e -> {
            Optional.ofNullable(corpUserPayIntentionMapper.selectOne(Wrappers.lambdaQuery(CorpUserPayIntention.class)
                    .eq(CorpUserPayIntention::getUnionId, e.getUnionId())
                    .last("limit 1"))).ifPresent(cu -> e.setIntention(cu.getIntention()));
        });
        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()).orderBy(QyMsgContent::getMsgtime).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);
    }
}
