package thyyxxk.webserver.service.dashboardEditor;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.dashboardEditor.DashboardEditorDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.dashboardEditor.TDashboardTemplate;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.http.websocket.SocketV2;
import thyyxxk.webserver.service.PublicServer;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.ResultVoUtil;

@Service
@RequiredArgsConstructor
public class DashboardEditorService {
    private final DashboardEditorDao dao;
    private final PublicServer publicServer;
    private final UserCache userCache;
    private final SocketV2 socketV2;

    public ResultVo<TDashboardTemplate> getDashboardTemplateByWardCode(String wardCode, Integer templateType) {
        return ResultVoUtil.success(dao.selectOne(TDashboardTemplate.lambdaQueryWrapper()
                .eq(TDashboardTemplate::getWardCode, wardCode)
                .eq(TDashboardTemplate::getTemplateType, templateType)));
    }

    public void checkRole(String wardCode) {
        if (publicServer.needRule(84)) {
            return;
        }
        UserInfo info = userCache.getUserInfoByToken();
        if (!wardCode.equals(info.getDeptCode())) {
            throw new BizException(ExceptionEnum.ERROR_MESSAGE, "您只能操作自己科室的模板。");
        }
    }

    public ResultVo<TDashboardTemplate> saveTemplate(TDashboardTemplate param) {
        checkRole(param.getWardCode());
        if (param.getId() == null) {
            param.setId(IdUtil.simpleUUID());
            dao.insert(param);
        } else {
            dao.updateById(param);
        }
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_NOTIFICATION, "保存成功", dao.selectById(param.getId()));
    }

    public ResultVo<String> release(String id) {
        TDashboardTemplate tDashboardTemplate = dao.selectById(id);
        checkRole(tDashboardTemplate.getWardCode());
        TDashboardTemplate tmp = TDashboardTemplate.builder()
                .htmlData(tDashboardTemplate.getHtmlDataTemp())
                .id(tDashboardTemplate.getId())
                .build();
        JSONObject entries = new JSONObject();
        entries.putOnce("release", tDashboardTemplate.getWardCode());
        socketV2.getPostApi("/nursingRecordBoard")
                .body(entries.toJSONString(0))
                .executeAsync();
        dao.updateById(tmp);
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_NOTIFICATION);
    }

}
