package thyyxxk.webserver.service.medicaladvice.patientinfo;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.constants.Message;
import thyyxxk.webserver.dao.his.medicaladvice.patientinfo.AdjustBedDao;
import thyyxxk.webserver.dao.his.medicaladvice.patientinfo.ZyBedPreMsgDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.inpatient.ZyActpatient;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.MzZyReq;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.ZyBedPreMsg;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.patientinfo.ZyBedMi;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.patientinfo.ZyBedMiParam;
import thyyxxk.webserver.entity.medicaladvice.medicamanage.weixin.WeiXinPreBedMsgParam;
import thyyxxk.webserver.http.websocket.SocketV2;
import thyyxxk.webserver.http.websocket.dto.WebSocketByListUserCode;
import thyyxxk.webserver.service.externalhttp.WxServer;
import thyyxxk.webserver.service.hutoolcache.DeptCache;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.AssertUtil;
import thyyxxk.webserver.utils.CommonUtil;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.SocketMsg;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author:lihong
 * @Date: 2023/5/31
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdjustBedService {
    private final AdjustBedDao dao;
    private final ZyBedPreMsgDao zyBedPreMsgDao;
    private final WxServer wxServer;
    private final SocketV2 intergrationPlatformSocket;
    private final UserCache userCache;
    private final DeptCache deptCache;

    public ResultVo<String> preAllocationBed(MzZyReq mzZyReq) {
        mzZyReq.setVisitDateStr(DateUtil.formatDateTime(mzZyReq.getVisitDate()));
        MzZyReq zyReq = dao.selectMzZyReq(mzZyReq);
        //发送消息
        sendMsg(zyReq.getReqWard(), zyReq.getName());
        return ResultVoUtil.success("已发送预分配床位消息,等待护士进行确认");
    }

    public void sendMsg(String ward, String name) {
        //获取该病室的护士
        List<String> admins = dao.getAdmins(ward);
        JSONObject obj = new JSONObject();
        obj.put("message", StrUtil.format("病人:【{}】进行了床位预分配申请,请前往整理床位页面进行预分配床位", name));
        String message = SocketMsg.socketVo(Message.SYSTEM_NOTIFICATION, obj);


        intergrationPlatformSocket.sendUserCodeListMessage(
                WebSocketByListUserCode.create(admins, message)
        );

    }

    @Transactional(rollbackFor = Exception.class)
    public ResultVo<String> confirmPreBed(ZyBedPreMsg zyBedPreMsg) {
        BeanUtil.trimStrFields(zyBedPreMsg);
        ZyBedPreMsg msg = zyBedPreMsgDao.selectById(zyBedPreMsg.getId());
        if ("1".equals(msg.getMsgStatus())) {
            throw new BizException(ExceptionEnum.LOGICAL_ERROR, "该条消息已办,不要重复确认");
        }
        if ("1".equals(zyBedPreMsg.getPreBedStatus())) {
            AssertUtil.isnotBlank(zyBedPreMsg.getBedNo(), "床位不能为空");
            //判断床位是否空闲
            Integer idleBedNo = dao.isIdleBedNo(zyBedPreMsg.getBedNo(), zyBedPreMsg.getWard());
            if (idleBedNo == null) {
                throw new BizException(ExceptionEnum.LOGICAL_ERROR, "该床位已有人,请重新分配");
            }
        }
        //消息改为已办
        UserInfo userInfo = userCache.getUserInfoByToken();
        Date now = new Date();
        zyBedPreMsg.setConfirmDate(now);
        zyBedPreMsg.setConfirmId(userInfo.getCode());
        zyBedPreMsg.setMsgStatus("1");
        zyBedPreMsgDao.updateById(zyBedPreMsg);

        //修改住院申请表
        MzZyReq req = new MzZyReq();
        req.setPatientId(zyBedPreMsg.getPatientId());
        req.setVisitDate(zyBedPreMsg.getVisitDate());
        req.setBedNo(zyBedPreMsg.getBedNo());
        req.setPreBedConfirmId(userInfo.getCode());
        req.setPreBedConfirmDate(now);
        req.setVisitDateStr(DateUtil.formatDateTime(zyBedPreMsg.getVisitDate()));
        req.setReqStatus(zyBedPreMsg.getPreBedStatus());
        req.setPreBedConfirmRemark(zyBedPreMsg.getPreBedConfirmRemark());
        String reqStatus = dao.selectReqStatus(req);
        if (!"3".equals(reqStatus.trim())) {
            dao.updateBedNo(req);
            MzZyReq zyReq = dao.selectMzZyReq(req);
            if ("1".equals(req.getReqStatus()) && isPushMessagePreBedNo(req.getPatientId(), zyReq.getName())) {
                WeiXinPreBedMsgParam weiXinPreBedMsgParam = new WeiXinPreBedMsgParam();
                weiXinPreBedMsgParam.setPatientId(req.getPatientId());
                weiXinPreBedMsgParam.setName(zyReq.getName());
                weiXinPreBedMsgParam.setBedInfo("1".equals(req.getReqStatus()) ?
                        deptCache.getDeptName(zyReq.getReqWard()) + req.getBedNo() + "床" : "");
                weiXinPreBedMsgParam.setFirst("1".equals(req.getReqStatus()) ? "您已成功预约床位，请及时办理住院!" : req.getPreBedConfirmRemark());
                try {
                    pushMessagePreBedNo(weiXinPreBedMsgParam);
                } catch (Exception e) {
                    log.error("调用微信床位预约报错", e);
                }
            }
        }
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE, "成功");
    }

    private boolean isPushMessagePreBedNo(String patientId, String name) {
        String mzName = dao.selectPatientMi(patientId);
        if (StrUtil.equals(name, mzName)) {
            return true;
        }
        return false;
    }


    public ResultVo<IPage<ZyBedPreMsg>> queryZyBedPreMsg(ZyBedPreMsg msg) {
        IPage<ZyBedPreMsg> page = new Page<>(msg.getCurrentPage(), msg.getPageSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like(StrUtil.isNotBlank(msg.getName()), "a.name", msg.getName());
        queryWrapper.like(StrUtil.isNotBlank(msg.getMsgStatus()), "a.msg_status", msg.getMsgStatus());
        UserInfo userInfo = userCache.getUserInfoByToken();
        if (!userInfo.getRoles().contains(1)) {
            queryWrapper.eq("a.ward", userInfo.getDeptCode());
        }
        zyBedPreMsgDao.queryZyBedPreMsgPage(page, queryWrapper);
        page.getRecords().forEach(item -> {
            item.setWardName(deptCache.getDeptName(item.getWard()));
        });
        page.setRecords(page.getRecords());
        page.setTotal(page.getTotal());
        return ResultVoUtil.success(page);
    }

    public List<ZyActpatient> queryPreAdmiss(String ward) {
        return dao.getPreAdmPatients(ward);
    }

    public void receivePatient(ZyActpatient actpatient) {
        dao.updateBedStatus(actpatient.getInpatientNo(), actpatient.getPhry());
    }

    public ResultVo<List<Map>> getIdleBedNoList(ZyBedPreMsg msg) {
        List<Map> list = new ArrayList<>();
        List<String> bedNos = dao.selectIdleBedNoList(msg.getWard());
        if (CollUtil.isNotEmpty(bedNos)) {
            bedNos.forEach(bedNo -> {
                Map map = new HashMap(2);
                map.put("code", bedNo);
                map.put("name", bedNo);
                list.add(map);
            });
        }
        return ResultVoUtil.success(list);
    }


    public Map<String, Object> queryZybedMi(ZyBedMi param) {
        if (StrUtil.isBlank(param.getWardCode())) {
            param.setWardCode(userCache.getUserInfoByToken().getDeptCode());
        }
        Map<String, Object> map = new HashMap<>(4);
        List<ZyBedMi> list = dao.selectZybedMi(param);
        CommonUtil.BeanTrim(list);
        map.put("data", list);
        map.put("bedTotal", list.size());
        long yzBedTotal = list.stream().filter(o -> StrUtil.isNotBlank(o.getInpatientNo())).count();
        long ybTotal = list.stream().filter(o -> StrUtil.isNotBlank(o.getInpatientNo()) && !"01".equals(o.getResponceType()) && !"011".equals(o.getResponceType())).count();
        map.put("yzBedTotal", yzBedTotal);
        map.put("ybTotal", ybTotal);
        return map;
    }

    public ResultVo<String> clearBed(ZyBedMi param) {
        AssertUtil.isnotBlank(param.getBedNo(), "床位号不能为空");
        if (StrUtil.isBlank(param.getWardCode())) {
            param.setWardCode(userCache.getUserInfoByToken().getDeptCode());
        }
        //
        Integer existPatient = dao.isExistPatient(param);
        if (existPatient != null) {
            throw new BizException(ExceptionEnum.INTERNAL_SERVER_ERROR, "此床位存在病人信息不能清除");
        }
        param.setInpatientNo(null);
        param.setAdmissTimes(null);
        param.setBedStatus("1");
        dao.updatePatientByBed(param);
        String message = StrUtil.format("清除{}床信息成功", param.getBedNo());
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE, message);
    }

    public ResultVo<String> addBed(ZyBedMi param) {
        AssertUtil.isnotBlank(param.getBedNo(), "床位号不能为空");
        if (StrUtil.isBlank(param.getWardCode())) {
            param.setWardCode(userCache.getUserInfoByToken().getDeptCode());
        }
        ZyBedMi zyBedMi = dao.selectActInpatientByBed(param);
        if (zyBedMi == null || StrUtil.isBlank(zyBedMi.getInpatientNo())) {
            throw new BizException(ExceptionEnum.INTERNAL_SERVER_ERROR, "此床位不存在病人信息,不能添加");
        }
        zyBedMi.setBedStatus("2");
        dao.updatePatientByBed(zyBedMi);
        String message = StrUtil.format("添加{}床信息成功", param.getBedNo());
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE, message);
    }

    public ResultVo<String> saveBed(ZyBedMiParam params) {
        ZyBedMi bedMi = new ZyBedMi();
        if (StrUtil.isBlank(params.getWardCode())) {
            bedMi.setWardCode(userCache.getUserInfoByToken().getDeptCode());
        } else {
            bedMi.setWardCode(params.getWardCode());
        }
        List<ZyBedMi> oldZyBedMi = dao.selectZybedMi(bedMi);
        List<ZyBedMi> newZyBedMi = params.getParam();
        CommonUtil.BeanTrim(oldZyBedMi);
        List<ZyBedMi> updateData = new ArrayList<>();
        newZyBedMi.forEach(newData -> {
            ZyBedMi oldComBedMi = oldZyBedMi.stream().filter(old -> newData.getBedNo().equals(old.getBedNo())).findFirst().get();
            if (!Convert.toStr(oldComBedMi.getInpatientNo(), "").equals(Convert.toStr(newData.getInpatientNo(), ""))) {
                if (StrUtil.isBlank(newData.getWardCode())) {
                    newData.setWardCode(bedMi.getWardCode());
                }
                updateData.add(newData);
            }
        });
        if (CollUtil.isNotEmpty(updateData)) {
            updateData.forEach(o -> {
                if (StrUtil.isNotBlank(o.getInpatientNo())) {
                    o.setBedStatus("2");
                    dao.updateActpatientBed(o);
                    dao.updateYpZyOrder(o);
                    dao.updateYzActOcc(o);
                } else {
                    o.setBedStatus("1");
                    o.setInpatientNo(null);
                    o.setAdmissTimes(null);
                }
                dao.updatePatientByBed(o);
            });
        }
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE, "保存成功");
    }

    public ResultVo<String> queryIsPreBed(ZyBedMi param) {
        if (StrUtil.isBlank(param.getWardCode())) {
            param.setWardCode(userCache.getUserInfoByToken().getDeptCode());
        } else {
            param.setWardCode(param.getWardCode());
        }
        //是否24小时内分配了床位
        Date now = new Date();
        param.setEndVisitDate(DateUtil.formatDateTime(now));
        param.setStartVisitDate(DateUtil.formatDateTime(DateUtil.offsetDay(now, -1)));
        Integer pre = dao.queryIsPreBed(param);
        if (pre == null) {
            return ResultVoUtil.success();
        } else {
            String str = StrUtil.format("{}床24小时内已经分配的病人,请确认是否继续分配该床", param.getBedNo());
            return ResultVoUtil.fail(ExceptionEnum.INTERNAL_SERVER_ERROR, str);
        }
    }


    public void pushMessagePreBedNo(WeiXinPreBedMsgParam param) {
        JSONObject jsonObject = new JSONObject();
        String msgContentJson = "{\"touser\":\"\",\"data\":" +
                                "{\"keyword3\":{\"color\":\"#173177\",\"value\":\"" + param.getBedInfo() + "\"}," +
                                "\"keyword4\":{\"color\":\"#FF0000\",\"value\":\"泰和医院\"}," +
                                "\"keyword1\":{\"color\":\"#173177\",\"value\":\"" + param.getName() + "\"}," +
                                "\"remark\":{\"color\":\"#FF0000\",\"value\":\"感谢您的使用，祝您健康!\"}," +
                                "\"first\":{\"color\":\"#FF0000\",\"value\":\"" + param.getFirst() + "\"}}," +
                                "\"template_id\":\"gQapOy99TXwDpublt7pWFehB2pzfI0Az5qlhCjaYxB0\"," +
                                "\"url\":\"\"}";
        jsonObject.put("cardNo", param.getPatientId());
        jsonObject.put("isCardNoPatientId", true);
        jsonObject.put("msgContext", JSON.parseObject(msgContentJson));
        log.info("调用微信接口参数入参{}", JSON.toJSONString(jsonObject));
        wxServer.pushWxMessage(jsonObject);
    }

}
