package com.fs.hisStore.controller;

import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.hisStore.facade.FsStore580FacadeService;
import com.fs.hospital580.param.PrescriptionPdfParam;
import com.fs.hospital580.vo.PrescriptionAdminQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 处方相关接口
 */
@Slf4j
@RestController
@RequestMapping("/store/prescription")
public class FsStoreHospital580PrescriptionScrmController extends BaseController {
    @Autowired
    private FsStore580FacadeService facadeService;


    /**
     * 处方订单列表
     */
    @PreAuthorize("@ss.hasPermi('store:storePrescription:list')")
    @GetMapping("/list")
    public TableDataInfo list(PrescriptionAdminQueryVo vo) {
        startPage();
        return getDataTable(facadeService.list(vo));
    }

    /**
     * 处方订单详情
     */
    @PreAuthorize("@ss.hasPermi('store:storePrescription:prescriptionDetail')")
    @GetMapping("/prescriptionDetail/{preId}")
    public R prescriptionDetail(@PathVariable("preId") Long preId) {
        return R.ok(facadeService.prescriptionDetail(preId));
    }

    /**
     * 获取聊天记录记录
     */
    @PreAuthorize("@ss.hasPermi('store:storePrescription:chatDetail')")
    @GetMapping("/chatDetail/{preId}")
    public R chatDetail(@PathVariable("preId") Long preId) {
        return R.ok(facadeService.chatDetail(preId));
    }


    /**
     * 批量导出PDF接口
     * @param param 包含需要导出的ID列表等参数
     * @return 二进制文件流响应
     */
    @PostMapping("/downloadMedicalPdf")
    public ResponseEntity<byte[]> downloadMedicalPdf(@RequestBody PrescriptionPdfParam param) {
        if (param == null || param.getIds() == null || param.getIds().isEmpty()) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        try {
            ByteArrayOutputStream pdfStream = facadeService.generatePdf(param);
            if (pdfStream == null) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }
            byte[] pdfBytes = pdfStream.toByteArray();
            if (pdfBytes.length < 1024) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }

            HttpHeaders headers = new HttpHeaders();
            String downloadFileName = "医疗记录_" + System.currentTimeMillis() + ".pdf";
            String encodedFileName = URLEncoder.encode(downloadFileName, StandardCharsets.UTF_8.name());

            headers.setContentDispositionFormData("attachment", encodedFileName);
            headers.setContentType(MediaType.APPLICATION_PDF);
            headers.setContentLength(pdfBytes.length);
            headers.setCacheControl("no-cache, no-store, must-revalidate");
            headers.setPragma("no-cache");
            headers.setExpires(0);

            return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            log.error("PDF下载IO异常", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            log.error("PDF下载异常", e);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
