package thyyxxk.webserver.service.datamodify;

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.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.constants.Capacity;
import thyyxxk.webserver.constants.GetDateFormat;
import thyyxxk.webserver.constants.Message;
import thyyxxk.webserver.dao.his.datamodify.YzActOrderDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.datamodify.TYzActOrderModify;
import thyyxxk.webserver.entity.datamodify.YzActOrder;
import thyyxxk.webserver.http.websocket.SocketV2;
import thyyxxk.webserver.http.websocket.dto.WebSocketByListUserCode;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.SocketMsg;
import thyyxxk.webserver.utils.StringUtil;
import thyyxxk.webserver.utils.TokenUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 医嘱修改服务类
 * </p>
 *
 * @author 肖蟾
 * @since 2021-03-08
 */
@Service
@Slf4j
public class YzActOrderModifyService {
    private final YzActOrderDao dao;
    private final SocketV2 intergrationPlatformSocket;

    @Autowired
    public YzActOrderModifyService(YzActOrderDao dao, SocketV2 intergrationPlatformSocket) {
        this.dao = dao;
        this.intergrationPlatformSocket = intergrationPlatformSocket;
    }

    /**
     * 根据医嘱号 来查询 符合条件的数据
     *
     * @param param 医嘱号 和 住院号查询
     * @return 返回医嘱号和医嘱名称
     */
    public ResultVo<List<YzActOrder>> queryYz(YzActOrder param) {
        QueryWrapper<YzActOrder> qw = new QueryWrapper<>();
        if (param.getActOrderNo() != null) {
            qw.eq("a.act_order_no", param.getActOrderNo());
        }
        if (StringUtil.notBlank(param.getInpatientNo())) {
            qw.eq("a.inpatient_no", param.getInpatientNo());
        }
        List<YzActOrder> list = dao.listQueryYz(qw);
        if (list.size() > 0) {
            return ResultVoUtil.success(list);
        }
        return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST);
    }

    /**
     * 提交医嘱修改申请 这里是多个医嘱修改
     *
     * @param param 提交申请的信息
     * @return 返回提示
     */
    public ResultVo<Boolean> yzModifyApply(TYzActOrderModify param) {
        log.info("申请医嘱修改 --> 申请人：{}，数据：{}",
                TokenUtil.getInstance().getTokenUserId(), JSON.toJSONStringWithDateFormat(param, GetDateFormat.DATE_TIME));
        List<TYzActOrderModify> insertList = new ArrayList<>();
        List<TYzActOrderModify> updateList = new ArrayList<>();
        if (param.getList().size() > 100) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "一次性申请超过100条");
        }
        List<BigDecimal> actOrderNoList = new ArrayList<>();
        param.getList().forEach(item -> {
            actOrderNoList.add(item.getActOrderNo());
        });
        List<BigDecimal> yiJingCunZai = dao.chaKansfCunZai(actOrderNoList);
        param.getList().forEach(item -> {
            if (yiJingCunZai.contains(item.getActOrderNo())) {
                updateList.add(item);
            } else {
                insertList.add(item);
            }
        });
        //执行批量插入
        if (!insertList.isEmpty()) {
            dao.yzActOrderModifyInsert(param, insertList);
        }
        //执行批量更新
        if (!updateList.isEmpty()) {
            dao.yzActOrderModifyUpdate(param, updateList);
        }
        //这里是通知有权限的人
        sendMessage();
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE, "申请成功，已通知审核人员。<br />可以在上方查看审核状态 (•‾̑⌣‾̑•)✧˖°");
    }

    /**
     * 根据 人员的 code 来查看他申请的医嘱
     *
     * @param code 编码
     * @return 返回这个人 申请修改的医嘱
     */
    public ResultVo<Map<String, Object>> chaKanZhuangTai(String code, String actOrderNo, String inpatientNo, long currentPage, long pageSize) {
        log.info("根据人员的code查询医嘱修改申请：{}，住院号：{}，医嘱号：{}", code, inpatientNo, actOrderNo);
        IPage<TYzActOrderModify> page = new Page<>(currentPage, pageSize);
        List<TYzActOrderModify> list = dao.queryZhuangTai(page, code, actOrderNo, inpatientNo);
        if (page.getTotal() > 0 || list.size() > 0) {
            Map<String, Object> map = new HashMap<>(Capacity.TWO);
            map.put("total", page.getTotal());
            map.put("data", list);
            return ResultVoUtil.success(map);
        }
        return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST);
    }

    /**
     * 单个医嘱修改
     *
     * @param param 要修改的信息
     * @return 返回提示成功
     */
    public ResultVo<String> danGeShenQing(TYzActOrderModify param) {
        param.setProposer(TokenUtil.getInstance().getTokenUserId());
        log.info("申请医嘱修改 --> 申请人：{}，数据：{}", param.getProposer(), JSON.toJSONStringWithDateFormat(param, GetDateFormat.DATE_TIME));
        if (dao.chaKanDanGeShenQing(param.getActOrderNo()) == 0) {
            dao.danGeShenQingInsert(param);
        } else {
            dao.danGeShenQingUpdate(param);
        }
        sendMessage();
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE, "申请成功，已通知审核人员。<br />可以在上方查看审核状态 (•‾̑⌣‾̑•)✧˖°");
    }

    /**
     * 通知有医嘱修改审核权限的人
     */
    private void sendMessage() {
        List<String> admins = dao.selectAdmins();
        JSONObject obj = new JSONObject();
        obj.put("message", String.format("用户【%s】提交了医嘱修改申请，请前往审核页面查看。",
                dao.getUserName(TokenUtil.getInstance().getTokenUserId())));
        String message = SocketMsg.socketVo(Message.SYSTEM_NOTIFICATION, obj);


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

        );

    }
}
