package com.ruoyi.web.modules.diagnosis.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.web.modules.diagnosis.domain.AiConsultOpenBody;
import com.ruoyi.web.modules.diagnosis.domain.AiConsultSendResult;
import com.ruoyi.web.modules.diagnosis.domain.AiConsultSessionView;
import com.ruoyi.web.modules.diagnosis.domain.AiConsultTableDataInfo;
import com.ruoyi.web.modules.diagnosis.domain.BizConsultMessage;
import com.ruoyi.web.modules.diagnosis.domain.BizConsultSession;
import com.ruoyi.web.modules.diagnosis.domain.VetConsultSendBody;
import com.ruoyi.web.modules.diagnosis.service.IBizAiOnlineConsultService;
import com.ruoyi.web.modules.diagnosis.support.AiConsultConstants;
/**
 * AI 诊断（兽医、机构）— 管理端
 */
@RestController
@RequestMapping("/diseaseTreatment/onlineConsult/ai")
public class BizAiOnlineConsultController extends BaseController
{
    @Autowired
    private IBizAiOnlineConsultService bizAiOnlineConsultService;

    @PreAuthorize("@ss.hasPermi('diseaseTreatment:aiOnlineConsult:list')")
    @GetMapping("/session/list")
    public AiConsultTableDataInfo list(BizConsultSession query,
            @RequestParam(value = "searchMode", required = false) Boolean searchMode)
    {
        if (query == null)
        {
            query = new BizConsultSession();
        }
        query.setSearchMode(searchMode);
        Long userId = SecurityUtils.getUserId();
        startPage();
        List<BizConsultSession> list = bizAiOnlineConsultService.selectAiSessionList(query, userId);
        AiConsultTableDataInfo rsp = new AiConsultTableDataInfo();
        rsp.setDisclaimer(AiConsultConstants.DISCLAIMER);
        rsp.setCode(HttpStatus.SUCCESS);
        rsp.setMsg("查询成功");
        rsp.setRows(list);
        rsp.setTotal(new PageInfo<>(list).getTotal());
        return rsp;
    }

    @PreAuthorize("@ss.hasPermi('diseaseTreatment:aiOnlineConsult:add')")
    @Log(title = "AI诊断新建会话", businessType = BusinessType.INSERT)
    @PostMapping("/session")
    public AjaxResult createSession(@RequestBody(required = false) AiConsultOpenBody body)
    {
        SysUserNameHolder names = resolveUserNames();
        AiConsultSessionView session = bizAiOnlineConsultService.createAiSession(names.userId, names.displayName,
                body);
        return success(session);
    }

    @PreAuthorize("@ss.hasPermi('diseaseTreatment:aiOnlineConsult:query')")
    @GetMapping("/session/{sessionId}/messages")
    public AjaxResult messages(@PathVariable("sessionId") Long sessionId,
            @RequestParam(value = "beforeId", required = false) Long beforeId,
            @RequestParam(value = "pageSize", required = false) Integer pageSize)
    {
        List<BizConsultMessage> rows = bizAiOnlineConsultService.selectSessionMessages(sessionId, beforeId, pageSize,
                SecurityUtils.getUserId());
        return success(rows);
    }

    @PreAuthorize("@ss.hasPermi('diseaseTreatment:aiOnlineConsult:send')")
    @Log(title = "AI诊断提问", businessType = BusinessType.INSERT)
    @PostMapping("/session/{sessionId}/message")
    public AjaxResult send(@PathVariable("sessionId") Long sessionId, @RequestBody VetConsultSendBody body)
    {
        SysUserNameHolder names = resolveUserNames();
        AiConsultSendResult result = bizAiOnlineConsultService.sendAiMessage(sessionId, body, names.userId,
                names.displayName, IpUtils.getIpAddr());
        return success(result);
    }

    /**
     * 管理端隐藏 AI 诊断会话（提问人侧 {@code vet_visible=0}，列表不再展示，数据仍保留）。
     */
    @PreAuthorize("@ss.hasPermi('diseaseTreatment:aiOnlineConsult:remove')")
    @Log(title = "管理端隐藏AI诊断会话", businessType = BusinessType.UPDATE)
    @PostMapping("/session/{sessionId}/hide")
    public AjaxResult hide(@PathVariable("sessionId") Long sessionId)
    {
        return toAjax(bizAiOnlineConsultService.hideSession(sessionId, SecurityUtils.getUserId()));
    }

    private SysUserNameHolder resolveUserNames()
    {
        com.ruoyi.common.core.domain.entity.SysUser user = SecurityUtils.getLoginUser().getUser();
        String name = user.getNickName() != null ? user.getNickName() : user.getUserName();
        return new SysUserNameHolder(user.getUserId(), name);
    }

    private static final class SysUserNameHolder
    {
        private final Long userId;

        private final String displayName;

        private SysUserNameHolder(Long userId, String displayName)
        {
            this.userId = userId;
            this.displayName = displayName;
        }
    }
}
