package com.xinelu.web.controller.applet;

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
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.messagepush.MessagePushService;
import com.xinelu.manage.vo.chatrecord.MessageVo;
import com.xinelu.common.core.controller.BaseController;
import com.xinelu.common.core.domain.R;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.familydoctor.applet.pojo.body.MessagePushBody;
import com.xinelu.familydoctor.applet.pojo.dto.FDMessageDto;
import com.xinelu.familydoctor.applet.pojo.vo.SignInfoDataVo;
import com.xinelu.framework.config.AsyncExecutorConfig;
import com.xinelu.manage.domain.chatRecord.ChatRecord;
import com.xinelu.manage.domain.hospitalpersoninfo.HospitalPersonInfo;
import com.xinelu.manage.service.hospitalpersoninfo.IHospitalPersonInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author mengkuiliang
 * @Description 家医消息推送控制器
 * @Date 2023-10-19 019 11:18
 * @Param
 * @return
 **/
@Api(tags = "家医消息推送控制器")
@RestController
@RequestMapping("/applet/message")
public class FdMessageController extends BaseController {
    @Resource
    private MessagePushService messagePushService;
    @Resource
    private AsyncExecutorConfig asyncExecutorConfig;
    @Resource
    private IChatRecordService chatRecordService;
    @Resource
    private IHospitalPersonInfoService hospitalPersonInfoService;

    @ApiOperation(value = "家医推送订阅消息", notes = "向接收方推送订阅消息")
    @PostMapping("/push")
    public R<String> pushMessage(@RequestBody FDMessageDto message) throws Exception {
        if (StringUtils.isBlank(message.getRecipientIdentity())) {
            return R.fail("接收方参数异常");
        }
        if (StringUtils.isBlank(message.getTemplateType())) {
            return R.fail("消息模版参数异常");
        }
        messagePushService.FdPushMessage(JSONObject.parseObject(JSONObject.toJSONString(message)));
        return R.ok();
    }

    @ApiOperation(value = "测试接口")
    @GetMapping("/test/")
    public R<SignInfoDataVo> test(MessagePushBody body, @RequestHeader("region") String region) {
//        JSONObject jsonObject = null;
//        try {
//            String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/resident/signinfo/detail/2334", null, String.class);
//            jsonObject = JSONObject.parseObject(result);
//            if ("0".equals(jsonObject.get("code"))) {
//                return R.fail(jsonObject.get("msg").toString());
//            }
//            if (!jsonObject.containsKey("data") || jsonObject.get("data") == null) {
//                return R.ok();
//            }
//            return R.ok(JSONObject.parseObject(jsonObject.getJSONObject("data").toJSONString(), SignInfoDataVo.class));
//        } catch (Exception e) {
//            System.out.println("注册完善信息-更新签约标识出错：" + e.getMessage());
//        }

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //设置子线程共享
        RequestContextHolder.setRequestAttributes(servletRequestAttributes, true);
        asyncExecutorConfig.asyncThreadServiceExecutor().execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("发送消息");
                messagePushService.fdApprovePush(JSONObject.parseObject(JSONObject.toJSONString(body)));
            }
        });
        System.out.println("执行成功");
        return R.ok();
    }


    @ApiOperation("查询通知推送列表-家医PC端")
    @PostMapping("/getNoticList")
    public R<PageInfo<MessageVo>> getNoticList(@RequestBody MessageSearchDto messageDto) {
        if (StringUtils.isBlank(messageDto.getSenderNo())) {
            return R.fail("发送人编号不能为空");
        }
        return R.ok(chatRecordService.getNoticList(messageDto));
    }

    @ApiOperation("查询通知详情-PC端")
    @GetMapping("/getNoticDetail/{messageNo}")
    public R<MessageVo> getNoticDetail(@PathVariable String messageNo) {
        return R.ok(chatRecordService.getNoticDetail(messageNo));
    }

    @ApiOperation(value = "保存通知-PC端", notes = "健康推送和通知公告消息通知")
    @PostMapping("/noticeSave")
    @Transactional
    public R<?> noticeSave(@RequestBody ChatRecordDTO message) {
        // 根据发送人编号查询家医用户信息
        HospitalPersonInfo hospitalPersonInfo = hospitalPersonInfoService.getByPersonCode(message.getSenderNo(), null);
        if(hospitalPersonInfo == null) {
            throw new ServiceException("未查询到医生信息");
        }
        if(StringUtils.isBlank(message.getMessageNo())) {
            message.setSendTime(new Date());
            message.setSenderId(hospitalPersonInfo.getId());
            message.setSenderName(hospitalPersonInfo.getPersonName());
            chatRecordService.insertChatRecord(message);
        } else {
            MessageVo messageVo = chatRecordService.getNoticDetail(message.getMessageNo());
            if(messageVo != null) {
                ChatRecord entity = new ChatRecord();
                BeanUtils.copyProperties(messageVo, entity);
                entity.setMessageType(message.getMessageType());
                entity.setContent(message.getContent());
                entity.setCrowds(message.getCrowds());
                entity.setCrowdsName(message.getCrowdsName());
                entity.setTitle(message.getTitle());
                entity.setUpdateTime(new Date());
                entity.setUpdateBy(message.getSenderNo());
                chatRecordService.updateChatRecordOfNo(entity);
            }
        }
        return R.ok();
    }

    @ApiOperation("删除通知-家医PC端")
    @GetMapping("/noticDel/{messageNo}")
    public R<String> noticDel(@PathVariable String messageNo) {
        chatRecordService.del(messageNo);
        return R.ok();
    }
}
