/*
 * Copyright ©2023 CJB-CNIT Team. All rights reserved
 */
package com.openhis.web.ybmanage.controller;

import java.rmi.ServerException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import com.core.common.core.domain.R;
import com.openhis.web.ybmanage.dto.VeriPrescriptionParam;
import com.openhis.web.ybmanage.service.IYbEleBaseService;
import com.openhis.web.ybmanage.service.IYbEleHttpService;
import com.openhis.ybelep.domain.*;

/**
 * 医保电子处方业务接口
 *
 * @author yuxj
 * @date 2025-04-17
 */
@RestController
@RequestMapping("/ybelep-request")
public class YbElepController {

    @Autowired
    IYbEleBaseService ybEleBaseService;

    @Autowired
    IYbEleHttpService ybEleHttpService;

    /**
     * 医保电子处方查询
     *
     * @param veriPrescriptionParam 查询条件
     * @param searchKey 模糊查询关键字
     * @param pageNo 当前页
     * @param pageSize 每页多少条
     * @param request 请求数据
     * @return 处方信息
     */
    @GetMapping(value = "/get-PrescriptionInfo")
    public R<?> getVeriPrescriptionInfo(VeriPrescriptionParam veriPrescriptionParam,
        @RequestParam(value = "searchKey", defaultValue = "") String searchKey,
        @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) {
        return ybEleBaseService.getVeriPrescriptionInfo(veriPrescriptionParam, searchKey, pageNo, pageSize, request);
    }

    /**
     * 医保电子处方查看
     *
     * @param prescriptionNo 处方号
     * @return 处方详细信息
     */
    @GetMapping(value = "/get-PrescriptionDetailInfo")
    public R<?> getPrescriptionDetailInfo(String prescriptionNo) {
        return ybEleBaseService.getPrescriptionDetailInfo(prescriptionNo);
    }

    /**
     * 医保电子处方状态更新（上传）
     *
     * @param prescriptionNo 处方号
     * @return 处方信息
     */
    @PutMapping(value = "/uploadPrescriptionStatus")
    public R<?> uploadPrescriptionStatus(String prescriptionNo) {
        return ybEleBaseService.uploadPrescriptionStatus(prescriptionNo);
    }

    /**
     * 医保电子处方拒绝上传
     *
     * @param prescriptionNo 处方号
     * @return 处方信息
     */
    @PutMapping(value = "/refusePrescriptionStatus")
    public R<?> refusePrescriptionStatus(String prescriptionNo) {
        return ybEleBaseService.refusePrescriptionStatus(prescriptionNo);
    }

    /**
     * 医保电子处方状态更新（撤销）
     *
     * @param prescriptionNo 处方号
     * @param quashReason 撤销原因
     * @return 处方信息
     */
    @PutMapping(value = "/quashPrescriptionStatus")
    public R<?> quashPrescriptionStatus(String prescriptionNo, String quashReason) {
        return ybEleBaseService.quashPrescriptionStatus(prescriptionNo, quashReason);
    }

    /**
     * 电子处方上传预核验
     *
     * @param prescriptionNo 处方信息
     * @param authNo 电子凭证线上身份核验流水号
     * @param ecToken 电子凭证令牌
     * @param tenantId 租户Id
     * @return
     */
    @GetMapping("/pre-verification")
    public R<?> preVerification(String prescriptionNo, String ecToken, String authNo, Integer tenantId) throws ServerException {

        PreCheckPrescription pcp = ybEleBaseService.makePreCheckPrescription(prescriptionNo, tenantId);

        // 查类型和审核医生名称
        Map<String, String> map = ybEleBaseService.getMedTypeAndDoctorName(prescriptionNo, tenantId);

        R<?> result = ybEleHttpService.preCheck(pcp, map.get("medType"), map.get("doctorName"));
        // 入参和出参 保存
        if (pcp != null) {
            pcp.getMdtrtinfo().setPrescriptionNo(prescriptionNo);
            ybEleBaseService.savePreCheckPrescription(pcp);
        }
        // 成功时保存出参
        if (result.getCode() == 200) {
            ElepVeriPrescriptionOutput pcpResult = null;
            if (ElepVeriPrescriptionOutput.class.isAssignableFrom(result.getData().getClass())) {
                pcpResult = (ElepVeriPrescriptionOutput)result.getData();
                pcpResult.setPrescriptionNo(prescriptionNo);
                ybEleBaseService.saveEleVeriPrescriptionOutput(pcpResult);
                return R.ok(pcpResult);
            }
        }
        return R.fail(result.getMsg());
    }

    /**
     * 电子处方医保电子签名
     *
     * @param hiRxno 医保处方编号
     * @param practitionerId 审方药师Id
     * @param checkDate 审方时间
     * @param tenantId 租户Id
     * @return
     */
    @GetMapping("/pre-signature")
    public R<?> eleSignature(String hiRxno, Long practitionerId,
        @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date checkDate, Integer tenantId) {

        ElepSignatureInput eleSignature =
            ybEleBaseService.makeEleSignature(hiRxno, practitionerId, checkDate, tenantId);
        R<?> result = ybEleHttpService.eleSign(eleSignature);

        // 入参和出参都保存
        if (eleSignature != null) {
            eleSignature.setHiRxno(hiRxno);
            ybEleBaseService.saveEleSignature(eleSignature);
        }
        // 成功时保存出参
        if (result.getCode() == 200) {
            ElepSignatureOutput esResult = null;
            if (ElepSignatureOutput.class.isAssignableFrom(result.getData().getClass())) {
                esResult = (ElepSignatureOutput)result.getData();
                esResult.setHiRxno(hiRxno);
                ybEleBaseService.saveEleSignatureOutput(esResult);
                return R.ok(esResult);
            }
        }
        return R.fail(result.getMsg());
    }

    /**
     * 电子处方上传
     *
     * @param hiRxno 医保处方编号
     * @param practitionerId 审方药师Id
     * @param checkDate 审方时间
     * @param tenantId 租户Id
     * @return
     */
    @GetMapping("/pre-upload")
    public R<?> uploadElePrescription(String hiRxno, Long practitionerId,
        @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date checkDate, Integer tenantId) {
        ElepUploadInput eleUploadInput =
            ybEleBaseService.makeEleUploadInput(hiRxno, practitionerId, checkDate, tenantId);
        R<?> result = ybEleHttpService.uploadElePre(eleUploadInput);

        // 入参和出参都保存
        if (eleUploadInput != null) {
            ybEleBaseService.saveEleUploadInput(eleUploadInput);
        }
        // 成功时保存出参
        if (result.getCode() == 200) {
            ElepUploadOutput euResult = null;
            if (ElepUploadOutput.class.isAssignableFrom(result.getData().getClass())) {
                euResult = (ElepUploadOutput)result.getData();
                ybEleBaseService.saveEleUploadOutput(euResult);
                return R.ok(euResult);
            }
        }
        return R.fail(result.getMsg());
    }

    /**
     * 电子处方撤销
     *
     * @param hiRxno 医保处方编号
     * @param practitionerId 撤销医师Id
     * @param description 撤销原因
     * @param revokeDate 撤销时间
     * @param tenantId 租户Id
     * @return
     */
    @GetMapping("/pre-revoke")
    public R<?> revokePrescription(String hiRxno, Long practitionerId, String description,
        @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date revokeDate, Integer tenantId) {

        ElepRevokeInput eleRevokeInput =
            ybEleBaseService.makeEleRevokeInput(hiRxno, practitionerId, description, revokeDate, tenantId); // 入参和出参都保存
        R<?> result = ybEleHttpService.revokePre(eleRevokeInput);
        if (eleRevokeInput != null) {
            ybEleBaseService.saveEleRevokeInput(eleRevokeInput);
        }
        // 成功时保存出参
        if (result.getCode() == 200) {
            ElepRevokeOutput ereResult = null;
            if (ElepRevokeOutput.class.isAssignableFrom(result.getData().getClass())) {
                ereResult = (ElepRevokeOutput)result.getData();
                ybEleBaseService.saveEleRevokeOutput(ereResult);
                return R.ok(ereResult);
            }
        }
        return R.fail(result.getMsg());
    }

    /**
     * 电子处方信息查询
     *
     * @param hiRxno 医保处方编号
     * @return
     */
    @GetMapping("/pre-query")
    public R<?> queryPrescription(String hiRxno) {

        ElepQuerPrescriptionInput eleQueryPreResultInput = ybEleBaseService.makeEleQueryPrescriptionInput(hiRxno);
        R<?> result = ybEleHttpService.queryPre(eleQueryPreResultInput);
        // 入参和出参都保存
        if (eleQueryPreResultInput != null) {
            ybEleBaseService.saveEleQueryPrescriptionInput(eleQueryPreResultInput);
        }
        // 成功时保存出参
        if (result.getCode() == 200) {
            QueryPrescription emrResult = null;
            if (QueryPrescription.class.isAssignableFrom(result.getData().getClass())) {
                emrResult = (QueryPrescription)result.getData();
                ybEleBaseService.saveEleMedResultOut(emrResult);
                return R.ok(emrResult);
            }
        }
        return R.fail(result.getMsg());
    }

    /**
     * 电子处方取药结果查询
     *
     * @param hiRxno 医保处方编号
     * @return
     */
    @GetMapping("/med-query")
    public R<?> queryMedPrescription(String hiRxno) {

        ElepMedresultInput eleMedInput = ybEleBaseService.makeEleMedResultInput(hiRxno); // 入参和出参都保存
        R<?> result = ybEleHttpService.queryMedPre(eleMedInput);
        if (eleMedInput != null) {
            ybEleBaseService.saveEleMedResultInput(eleMedInput);
        }
        // 成功时保存出参
        if (result.getCode() == 200) {
            MedicationResultInquiry medResult = null;
            if (MedicationResultInquiry.class.isAssignableFrom(result.getData().getClass())) {
                medResult = (MedicationResultInquiry)result.getData();
                ybEleBaseService.saveMedicationResultInquiry(medResult);
                return R.ok(medResult);
            }
        }
        return R.fail(result.getMsg());
    }
}
