package com.xinelu.applet.controller.chatrecord;

import com.xinelu.common.constant.Constants;
import com.xinelu.common.core.controller.BaseController;
import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.core.domain.R;
import com.xinelu.common.core.page.TableDataInfo;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.socket.WebSocketUtils;
import com.xinelu.manage.domain.chatRecord.ChatRecord;
import com.xinelu.manage.dto.chatrecord.ChatRecordDTO;
import com.xinelu.manage.dto.chatrecord.MessageSearchDto;
import com.xinelu.manage.service.chatrecord.IChatRecordService;
import com.xinelu.manage.service.patientinfo.IPatientInfoService;
import com.xinelu.manage.vo.chatrecord.MessageCenterVo;
import com.xinelu.manage.vo.patientinfo.PatientInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import java.util.Objects;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
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 org.springframework.web.multipart.MultipartFile;

/**
 * 图文咨询-聊天记录表
 *
 * @author wanghao
 * @create 2023/9/26 0026
 */
@Api(tags = "消息控制器")
@RestController
@RequestMapping("/nurseApplet/chatRecord")
public class ChatRecordController extends BaseController {


    @Autowired
    private IChatRecordService chatRecordService;

	@Resource
	private IPatientInfoService patientInfoService;

    /**
     * 查询聊天记录
     */
    @GetMapping("/getChatRecord")
    public AjaxResult getChatRecord(ChatRecord chatRecord) {
        return AjaxResult.success(chatRecordService.selectChatRecordList(chatRecord));
    }

    /**
     * 修改已读状态
     */
    @PutMapping(value = "updateReadStatus")
    public AjaxResult updateReadStatus(@RequestBody ChatRecord chatRecord) {
        return toAjax(chatRecordService.updateChatRecord(chatRecord));
    }

    @ApiOperation(value = "发送即时消息", notes = "向接收方发送即时消息")
    @PostMapping("/sendMessage")
    @Transactional
    public AjaxResult sendMessage(@RequestBody ChatRecordDTO chatRecordDTO) {
	    chatRecordDTO.setMessageCategory("3");
		if (chatRecordService.insertChatRecord(chatRecordDTO) > 0) {
            // 判断接收人是否在线
            if (WebSocketUtils.clients.get(chatRecordDTO.getRecipientId().toString()) == null) {
                return AjaxResult.success();
            } else {
                return chatRecordService.sendMessage(chatRecordDTO) ? AjaxResult.success() : AjaxResult.error();
            }
        } else {
            return AjaxResult.success();
        }
    }

    /**
     * 问诊聊天上传文件接口
     */
    @PostMapping("/uploadChatRecordFile")
    public AjaxResult uploadChatRecordFile(@RequestParam("file") MultipartFile multipartFile, @RequestParam(value = "consultationId") Long consultationId) throws Exception {
        if (Objects.isNull(multipartFile) || StringUtils.isBlank(multipartFile.getOriginalFilename())) {
            return AjaxResult.error("当前文件不存在，无法上传！");
        }
        if (multipartFile.getOriginalFilename().contains(Constants.EMPTY)) {
            return AjaxResult.error("当前文件名含有空格，请先去除空格在上传！");
        }
        return chatRecordService.uploadChatRecordFile(multipartFile, consultationId);
    }

	@ApiOperation("消息中心")
	@GetMapping("/getMegVoList")
	public R<List<MessageCenterVo>> getMegVoList(MessageSearchDto messageDto) {
		if (messageDto.getRecipientId() == null) {
			return R.fail("请先绑定账号！");
		}
		return R.ok(chatRecordService.getMegVoList(messageDto));
	}

    @ApiOperation(value = "获取指定类型的消息记录", notes = "1：通知公告 2：健康推送 4：消息通知")
    @GetMapping("/getMegList")
    public TableDataInfo getMegList(MessageSearchDto messageDto) {
        if (messageDto.getPatientId() == null) {
            throw new ServiceException("居民业务主键不能为空");
        }
        if (StringUtils.isBlank(messageDto.getMessageCategory())) {
            throw new ServiceException("消息类型不能为空");
        }
	    // 获取注册信息
	    PatientInfoVO patientInfo = patientInfoService.selectPatientInfoById(messageDto.getPatientId());
	    if (patientInfo == null) {
		    throw new ServiceException("未查询到注册信息");
	    }
        startPage();
        return getDataTable(chatRecordService.getMegList(messageDto, patientInfo));
    }

	@ApiOperation("删除消息")
	@GetMapping("/deleteMegs")
	public R<String> deleteMegs(@RequestBody List<Long> ids) {
		if (CollectionUtils.isEmpty(ids)) {
			return R.fail("请选择要删除的消息！");
		}
		return chatRecordService.deleteMegs(ids) > 0 ? R.ok("删除成功") : R.fail("删除失败");
	}


}
