package thyyxxk.webserver.controller.ca;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import thyyxxk.webserver.config.auth.PassToken;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.ca.CaPatientSignDao;
import thyyxxk.webserver.dao.his.zhuyuanyisheng.emr.EmrPatientDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.ca.vo.move.PatientInfo;
import thyyxxk.webserver.entity.ca.vo.move.SaveCaMove;
import thyyxxk.webserver.entity.ca.vo.move.SignMedicalRecordsOnBehalfOfOthers;
import thyyxxk.webserver.enums.CaExceptionEnum;
import thyyxxk.webserver.service.ca.CaServer;
import thyyxxk.webserver.service.externalhttp.emr.EmrEditor;
import thyyxxk.webserver.service.zhuyuanyisheng.emr.EmrServer;
import thyyxxk.webserver.utils.ResultVoUtil;

import java.util.List;

@RestController
@RequestMapping("/caPatientSign")
@RequiredArgsConstructor
public class CaPatientSignController {

    private final CaPatientSignDao dao;
    private final EmrServer emrServer;
    private final CaServer caServer;
    private final EmrEditor emr;
    private final EmrPatientDao emrPatientDao;


    @GetMapping("/getPatientInfo")
    @PassToken
    public ResultVo<PatientInfo> getPatientInfo(@RequestParam("patNo") String patNo) {
        return ResultVoUtil.success(dao.selectPatientInfo(patNo));
    }

    @GetMapping("/getEmrToken")
    @PassToken
    public ResultVo<String> getEmrToken() {
        return ResultVoUtil.success(emrServer.getEmrToken());
    }

    @GetMapping("/getSignEmrInfoByPatient")
    @PassToken
    public ResultVo<List<SignMedicalRecordsOnBehalfOfOthers>> getSignEmrInfoByPatient(@RequestParam("patNo") String patNo,
                                                                                      @RequestParam("times") Integer times) {
        return ResultVoUtil.success(dao.selectEmr(patNo, times));
    }

    @PostMapping("/sendMoreEventSign")
    @PassToken
    public ResultVo<JSONObject> sendMoreEventSign(@RequestBody SaveCaMove moreEventSign) {
        if (StrUtil.isBlank(moreEventSign.getMoreEventSign().getDocumentId())) {
            return ResultVoUtil.fail(CaExceptionEnum.NOT_DOCUMENT_ID);
        }
        try {
            emr.saveDocument(moreEventSign.getDocumentData());
        } catch (Exception e) {
            return ResultVoUtil.fail(CaExceptionEnum.ERROR_AND_ALERT, "病历保存错误，请重试！" + e.getMessage());
        }
        ResultVo<JSONObject> rst = caServer.sendMoreEventSign(moreEventSign.getMoreEventSign());
        if (ExceptionEnum.SUCCESS_AND_EL_MESSAGE.getCode().equals(rst.getCode())) {
            return ResultVoUtil.success(CaExceptionEnum.SUCCESS_AND_MESSAGE, rst.getMessage());
        } else {
            return ResultVoUtil.fail(CaExceptionEnum.ERROR_AND_ALERT, rst.getMessage());
        }
    }

}
