package com.fs.his.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.doctor.domain.DoctorMsg;
import com.fs.doctor.mapper.DoctorMsgMapper;
import com.fs.enums.PostPayPrescStatusEnum;
import com.fs.his.config.FsSysConfig;
import com.fs.his.domain.*;
import com.fs.his.dto.FsPackagePatientDTO;
import com.fs.his.dto.FsPackagePruductDTO;
import com.fs.his.dto.FsPrescribeUsageDTO;
import com.fs.his.dto.PrescribeRejectDTO;
import com.fs.his.enums.PrescriptionTaskStepEnum;
import com.fs.his.mapper.*;
import com.fs.his.param.*;
import com.fs.his.service.*;
import com.fs.his.utils.ConfigUtil;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.utils.qrcode.QRCodeUtils;
import com.fs.his.vo.*;
import com.fs.hisStore.domain.FsUserInformationCollection;
import com.fs.hisStore.mapper.FsUserInformationCollectionMapper;
import com.fs.hisStore.service.IFsUserInformationCollectionService;
import com.fs.im.service.IImService;
import com.fs.qw.mapper.FsUserInformationCollectionScheduleMapper;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.WriterException;
import org.apache.http.util.Asserts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 处方Service业务层处理
 *
 * @author fs
 * @date 2023-06-13
 */
@Service
public class FsPrescribeServiceImpl implements IFsPrescribeService
{
    private static final Logger log = LoggerFactory.getLogger(FsPrescribeServiceImpl.class);
    @Autowired
    private FsPrescribeMapper fsPrescribeMapper;
    @Autowired
    private FsPrescribeDrugMapper fsPrescribeDrugMapper;
    @Autowired
    private FsInquiryOrderMapper fsInquiryOrderMapper;
    @Autowired
    private IFsDoctorService doctorService;
    @Autowired
    private FsDoctorMapper doctorMapper;
    @Lazy
    @Autowired
    private IFsStoreOrderService storeOrderService;
    @Autowired
    private IFsPrescribeDrugService prescribeDrugService;
    @Autowired
    private IImService imService;
    @Autowired
    private FsPackageMapper fsPackageMapper;
    @Autowired
    private ConfigUtil configUtil;
    @Autowired
    private FsExportTaskMapper fsExportTaskMapper;
    @Autowired
    private PrescriptionTaskRecordMapper prescriptionTaskRecordMapper;
    @Autowired
    private PrescriptionImageService prescriptionImageService;

    @Autowired
    private IFsExportTaskService fsExportTaskService;

    @Autowired
    RedisCache redisCache;

    @Autowired
    private FsUserInformationCollectionMapper collectionMapper;

    @Autowired
    private IFsPrescribeRecordService prescribeRecordService;

    @Autowired
    private DoctorMsgMapper doctorMsgMapper;

    @Autowired
    private FsStoreProductMapper fsStoreProductMapper;

    @Autowired
    private FsUserInformationCollectionScheduleMapper scheduleMapper;

    @Autowired
    private FsStoreOrderMapper storeOrderMapper;

    @Lazy
    @Autowired
    private IFsUserInformationCollectionService fsUserInformationCollectionService;

    @Autowired
    private IPollingAssignDoctorService pollingAssignDoctorService;

    @Autowired
    private ApplicationContext applicationContext;

    private IFsPrescribeService self() {
        return applicationContext.getBean(IFsPrescribeService.class);
    }

    /**
     * 查询处方
     *
     * @param prescribeId 处方主键
     * @return 处方
     */
    @Override
    public FsPrescribe selectFsPrescribeByPrescribeId(Long prescribeId)
    {
        return fsPrescribeMapper.selectFsPrescribeByPrescribeId(prescribeId);
    }

    /**
     * 查询处方列表
     *
     * @param fsPrescribe 处方
     * @return 处方
     */
    @Override
    public List<FsPrescribe> selectFsPrescribeList(FsPrescribe fsPrescribe)
    {
        return fsPrescribeMapper.selectFsPrescribeList(fsPrescribe);
    }

    /**
     * 新增处方
     *
     * @param fsPrescribe 处方
     * @return 结果
     */
    @Override
    public int insertFsPrescribe(FsPrescribe fsPrescribe)
    {
        fsPrescribe.setCreateTime(DateUtils.getNowDate());
        return fsPrescribeMapper.insertFsPrescribe(fsPrescribe);
    }

    /**
     * 修改处方
     *
     * @param fsPrescribe 处方
     * @return 结果
     */
    @Override
    public int updateFsPrescribe(FsPrescribe fsPrescribe)
    {
        return fsPrescribeMapper.updateFsPrescribe(fsPrescribe);
    }

    /**
     * 批量删除处方
     *
     * @param prescribeIds 需要删除的处方主键
     * @return 结果
     */
    @Override
    public int deleteFsPrescribeByPrescribeIds(Long[] prescribeIds)
    {
        return fsPrescribeMapper.deleteFsPrescribeByPrescribeIds(prescribeIds);
    }

    /**
     * 删除处方信息
     *
     * @param prescribeId 处方主键
     * @return 结果
     */
    @Override
    public int deleteFsPrescribeByPrescribeId(Long prescribeId)
    {
        return fsPrescribeMapper.deleteFsPrescribeByPrescribeId(prescribeId);
    }

    @Override
    public List<FsPrescribeListVO> selectFsPrescribeListVO(FsPrescribeParam fsPrescribe) {
        return  fsPrescribeMapper.selectFsPrescribeListVO(fsPrescribe);
    }

    @Override
    public List<FsPrescribeListVO> selectFsPrescribeListVOWithConfirm(FsPrescribeParam fsPrescribe) {
        List<FsPrescribeListVO> fsPrescribeListVOS = fsPrescribeMapper.selectFsPrescribeListVOWithConfirm(fsPrescribe);
        if (CollectionUtils.isEmpty(fsPrescribeListVOS)){
            return Collections.emptyList();
        }
        return  fsPrescribeListVOS;
    }

    @Override
    public List<FsPrescribeListDVO> selectFsPrescribeListDVO(FsPrescribeListDParam param) {
        List<FsPrescribeListDVO> list=fsPrescribeMapper.selectFsPrescribeListDVO(param);
        for(FsPrescribeListDVO vo:list){
            FsPrescribeDrug map=new FsPrescribeDrug();
            map.setPrescribeId(vo.getPrescribeId());
            vo.setDrugs(fsPrescribeDrugMapper.selectFsPrescribeDrugList(map));
        }
        return list;

    }

    @Override
    public String getFsPrescribeZyImg(PrescribeZyImgParam o) {
        File mb = new File("C:\\fs\\zycf.jpg");
        if (!mb.exists()) {
            // 创建目录
            throw  new CustomException("模板文件不存在");
        }
        BufferedImage image = null;
        try {
            image = ImageIO.read(mb);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建画笔(image为上一步的图片对象)
        Graphics2D pen = image.createGraphics();
        pen.setColor(Color.black);
        //处理字体 高清加边缘模糊
        pen.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        pen.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        pen.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        pen.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
        pen.setFont(new Font("黑体", Font.PLAIN, 21));
        // 将date对象格式化为字符串

        penDrawString(pen,new SimpleDateFormat("yyyy-MM-dd").format(o.getTime()), 730, 290);
        penDrawString(pen,o.getPrescribeId(),1030,290);
        penDrawString(pen,o.getPatientName(),136,372);
        penDrawString(pen,o.getPatientGender().equals("1")?"男":o.getPatientGender().equals("2")?"女":o.getPatientGender(),420,372);
        penDrawString(pen,o.getPatientAge(),690,372);
        penDrawString(pen,o.getPatientTel(),970,372);
        String address= o.getUserName()+"      "+o.getUserPhone()+"     "+o.getUserAddress();
        penDrawString(pen,address,180,445);
        penDrawString(pen,o.getDiagnose(),180,515);
        List<FsPrescribeDrug> Drug = o.getPrescribeDrug();
        int size=Drug.size();

        for (int i = 0; i < size/3.0; i++) {
            if (i*3<size){
                pen.drawString(Drug.get(i*3).getDrugName(),145,680+i*50);
            }
            if (i*3+1<size){
                pen.drawString(Drug.get(i*3+1).getDrugName(),510,680+i*50);
            }
            if (i*3+2<size){
                pen.drawString(Drug.get(i*3+2).getDrugName(),875,680+i*50);
            }
        }
        penDrawString(pen,o.getEat(),110,1195);
        penDrawString(pen,o.getUsageFrequencyUnit(),135,1240);
        penDrawString(pen,o.getRemark(),110,1288);

       // penDrawString(pen,o.getDoctorName(),152,1378);
        if (o.getUrl()!=null){
            try {
                URL   imageUrl = new URL(o.getUrl());
                BufferedImage img = ImageIO.read(imageUrl);
                pen.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                pen.drawImage(img, 130, 1420, 127, 60, null);
            } catch (Exception e) {
                throw new CustomException("获取医生签名图片失败");
            }

        }else {
            penDrawString(pen,o.getPrescribeDoctorName(),152,1450);
        }
        if (o.getDrugDoctorUrl()!=null){
            try {
                URL   imageUrl3 = new URL(o.getDrugDoctorUrl());
                BufferedImage img3 = ImageIO.read(imageUrl3);
                pen.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                pen.drawImage(img3, 370, 1345, 127, 60, null);
            } catch (Exception e) {
                throw new CustomException("获取药师签名图片失败");
            }
        }
//        penDrawString(pen,o.getCheck(),348,1378);
        penDrawString(pen,o.getSize(),620,1378);
        if (o.getTotalPrice()!=null){
            penDrawString(pen,o.getTotalPrice().toString(),370,1452);
            penDrawString(pen,o.getTotalPrice().toString(),620,1452);
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream inputStream = new ByteArrayInputStream(os.toByteArray());
        CloudStorageService storage = OSSFactory.build();
        String url = storage.uploadSuffix(inputStream, ".jpg");
        return url;
    }

    @Override
    public String getFsPrescribeXyImg(PrescribeXyImgParam o) {
       // File mb = new File(System.getProperty("user.dir")+"\\xycf.jpg");
        File mb = new File("C:\\fs\\xycf.jpg");
        if (!mb.exists()) {
            // 创建目录
            throw  new CustomException("模板文件不存在");
        }
        BufferedImage image = null;
        try {
            image = ImageIO.read(mb);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建画笔(image为上一步的图片对象)
        Graphics2D pen = image.createGraphics();
        pen.setColor(Color.black);
        //处理字体 高清加边缘模糊
        pen.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        pen.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        pen.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        pen.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
        pen.setFont(new Font("黑体", Font.PLAIN, 14));
        penDrawString(pen,o.getPrescribeId(),448,145);
        penDrawString(pen,o.getPatientName(),60,178);
        if (o.getPatientGender().equals("1")){
            penDrawString(pen,"√",255,178);
        }else if(o.getPatientGender().equals("2")){
            penDrawString(pen,"√",298,178);
        }
        penDrawString(pen,o.getPatientAge(),400,178);
        penDrawString(pen,o.getOutpatientId(),92,205);
        penDrawString(pen,o.getBedId(),400,205);
        penDrawString(pen,o.getHistoryAllergic(),95,230);
        penDrawString(pen,o.getDiagnose(),95,257);
        penDrawString(pen,new SimpleDateFormat("yyyy-MM-dd").format(o.getTime()),400,257);
        List<FsPrescribeDrug> Drug = o.getPrescribeDrug();
        int size=Drug.size();
//        BigDecimal price=BigDecimal.valueOf(0);
        for (int i = 0; i < size; i++) {
            FsPrescribeDrug d = Drug.get(i);
            String drugName = d.getDrugName();
            BigDecimal drugPrice = d.getDrugPrice().multiply(BigDecimal.valueOf(d.getDrugNum()));
//            price= price.add(drugPrice);
            if (drugName.length()>30){
                drugName = drugName.substring(0, 30)+"...";
            }

            String drugSpec = (d.getDrugSpec() != null) ? d.getDrugSpec() : "   ";

            penDrawString(pen,i+1+","+drugName+"    "+drugSpec+"    "+d.getDrugNum(),35,305+i*40);
            String usageMethod = (d.getUsageMethod() != null) ? d.getUsageMethod() : "   ";
            String usageFrequencyUnit = (d.getUsageFrequencyUnit() != null) ? d.getUsageFrequencyUnit() : "   ";
            String usagePerUseCount = (d.getUsagePerUseCount() != null) ? d.getUsagePerUseCount() : "   ";

            penDrawString(pen," Sig:          "+usageMethod+"     "+usageFrequencyUnit+"     "+usagePerUseCount,35,325+i*40);
        }
        penDrawString(pen,"本页完",277,325+size*40);

        penDrawString(pen,o.getRemark(),62,651);
        if (o.getUrl()!=null){
            try {
                URL   imageUrl = new URL(o.getUrl());
                pen.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                BufferedImage img = ImageIO.read(imageUrl);
                pen.drawImage(img, 65, 688, 88, 40, null);
            } catch (Exception e) {
                throw new CustomException("获取签名图片失败");
            }
        }else {
            penDrawString(pen,o.getDoctorName(),63,716);
        }

        penDrawString(pen,o.getTotalPrice().toString(),375,717);
        if (o.getDrugDoctorUrl()!=null){
            try {
                URL   imageUrl = new URL(o.getDrugDoctorUrl());
                BufferedImage img = ImageIO.read(imageUrl);
                pen.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                pen.drawImage(img, 90, 730, 88, 40, null);
            } catch (Exception e) {
                throw new CustomException("获取药师签名图片失败");
            }
        }
        penDrawString(pen,o.getDispatcher(),357,757);
        penDrawString(pen,o.getCheckDoctor(),135,796);


        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream inputStream = new ByteArrayInputStream(os.toByteArray());
        CloudStorageService storage = OSSFactory.build();
        String url = storage.uploadSuffix(inputStream, ".jpg");
        return url;
    }

    @Override
    public List<FsPrescribeListUVO> selectFsPrescribeListUVO(FsPrescribeListUParam param) {
        List<FsPrescribeListUVO> list=fsPrescribeMapper.selectFsPrescribeListUVO(param);
        for(FsPrescribeListUVO vo:list){
            FsPrescribeDrug map=new FsPrescribeDrug();
            map.setPrescribeId(vo.getPrescribeId());
            vo.setDrugs(fsPrescribeDrugMapper.selectFsPrescribeDrugList(map));
        }
        return list;
    }

//    @Async
    @Override
    public String PrescribeImg(Long PrescribeId){
        FsPrescribeVO f = fsPrescribeMapper.selectFsPrescribeByPrescribeIdVO(PrescribeId);
        if (f==null){
            return "";
        }
        FsStoreOrder fsStoreOrder = storeOrderService.selectFsStoreOrderByOrderId(f.getStoreOrderId());
        FsInquiryOrderVO order = fsInquiryOrderMapper.selectFsInquiryOrderVOByOrderId(f.getInquiryOrderId());
        if (f.getPrescribeImgUrl()==null||f.getPrescribeImgUrl().equals("")){
            FsPrescribeDrug d = new FsPrescribeDrug();
            d.setPrescribeId(f.getPrescribeId());
            List<FsPrescribeDrug> list = fsPrescribeDrugMapper.selectFsPrescribeDrugList(d);
            if (list.size()==0){
                return "";
            }
            if (f.getPrescribeType()==1){
                PrescribeXyImgParam o = new PrescribeXyImgParam();
                o.setTotalPrice(fsStoreOrder.getPayPrice());
                o.setTime(f.getCreateTime());
                o.setPrescribeId(f.getPrescribeCode());
                o.setPatientName(f.getPatientName());
                o.setPatientGender(f.getPatientGender());
                o.setPatientAge(f.getPatientAge());
                o.setOutpatientId(f.getPrescribeCode());
                o.setUrl(f.getPrescribeDoctorSignUrl());
                o.setDrugDoctorUrl(f.getDrugDoctorSignUrl());
                if (order!=null){
                    o.setBedId(order.getDeptName());
                }else {
                    o.setBedId("中医科");
                }
                String remark="";
                if (f.getUsageJson()!=null){
                    FsPrescribeUsageDTO usage = JSONUtil.toBean(f.getUsageJson(), FsPrescribeUsageDTO.class);
                    remark=usage.getRemark();
                }
                if (remark!=null&&remark!=""){
                    o.setRemark(remark);
                }else {
                    o.setRemark("请按照用药说明书服用药品，如有不适，请及时就医!");
                }
                o.setHistoryAllergic(f.getHistoryAllergic());
                o.setDiagnose(f.getDiagnose());
                o.setPrescribeDrug(list); // 在这里添加处方药品列表的值
                o.setDoctorName(f.getDoctorName());
                o.setAuditDoctor(f.getDoctorDrugName());
                o.setDispatcher("");
                o.setCheckDoctor("");
                o.setDoctorName(f.getDoctorName());
                String s = getFsPrescribeXyImg(o);
                FsPrescribe fsPrescribe = new FsPrescribe();
                fsPrescribe.setPrescribeImgUrl(s);
                fsPrescribe.setPrescribeId(f.getPrescribeId());
                fsPrescribeMapper.updateFsPrescribe(fsPrescribe);
                return s;
            }else if (f.getPrescribeType()==2){

                FsPrescribeUsageDTO usage = JSONUtil.toBean(f.getUsageJson(), FsPrescribeUsageDTO.class);

                // 设置字段值
                PrescribeZyImgParam o = new PrescribeZyImgParam();
                o.setTime(f.getCreateTime());

                o.setPrescribeId(f.getPrescribeCode());
                o.setPatientName(f.getPatientName());
                o.setPatientGender(f.getPatientGender());
                o.setPatientAge(f.getPatientAge());
                o.setPatientTel(f.getPatientTel());
                o.setPrescribeDoctorName(f.getPrescribeDoctorName());
                o.setUserName(fsStoreOrder.getUserName()); //发货地址
                o.setUserPhone(fsStoreOrder.getUserPhone()); //收货人手机
                o.setUserAddress(fsStoreOrder.getUserAddress()); //收货地址
                o.setDiagnose(f.getDiagnose());
                o.setPrescribeDrug(list); // 在这里添加处方药品列表的值
                o.setEat(usage.getUsageMethod());
                o.setUsageFrequencyUnit(usage.getUsageFrequencyUnit());
                o.setRemark(usage.getRemark());
                o.setDoctorName(f.getDoctorName());
                o.setCheck(f.getDoctorDrugName());
                if (usage.getCounts()!=null){
                    o.setSize(usage.getCounts().toString());
                }
                o.setUrl(f.getPrescribeDoctorSignUrl());
                o.setDrugDoctorUrl(f.getDrugDoctorSignUrl());
                o.setTotalPrice(fsStoreOrder.getPayPrice());
                String s = getFsPrescribeZyImg(o);
                FsPrescribe fsPrescribe = new FsPrescribe();
                fsPrescribe.setPrescribeImgUrl(s);
                fsPrescribe.setPrescribeId(f.getPrescribeId());
                fsPrescribeMapper.updateFsPrescribe(fsPrescribe);
                return s;
            }
        }
        return f.getPrescribeImgUrl();
    }

    @Override
    public String prescribeImgYsyTask(Long prescribeId,Integer signFlag) {
        FsPrescribeVO f = fsPrescribeMapper.selectFsPrescribeByPrescribeIdVO(prescribeId);
        Asserts.notNull(f,String.format("处方 %d 未找到！",prescribeId));

        FsStoreOrder fsStoreOrder = storeOrderService.selectFsStoreOrderByOrderId(f.getStoreOrderId());
        FsInquiryOrderVO order = fsInquiryOrderMapper.selectFsInquiryOrderVOByOrderId(f.getInquiryOrderId());
        if (StringUtils.isBlank(f.getPrescribeImgUrl())) {
            FsPrescribeDrug d = new FsPrescribeDrug();
            d.setPrescribeId(f.getPrescribeId());
            List<FsPrescribeDrug> list = fsPrescribeDrugMapper.selectFsPrescribeDrugList(d);

            if (CollectionUtils.isEmpty(list)) {
                throw new IllegalArgumentException(String.format("处方单 %d 对应药品为空！",prescribeId));
            }
            PrescribeXyImgParam o = new PrescribeXyImgParam();
            if (fsStoreOrder!=null){
                o.setStatus(fsStoreOrder.getStatus());
                o.setTotalPrice(fsStoreOrder.getPayPrice());
            }
            o.setTime(f.getCreateTime());
            o.setPrescribeId(f.getPrescribeCode());
            o.setPatientName(f.getPatientName());
            o.setPatientGender(f.getPatientGender());
            o.setPatientAge(f.getPatientAge());
            o.setOutpatientId(f.getPrescribeCode());
            if (order != null) {
                o.setBedId(order.getDeptName());
            } else {
                o.setBedId("中医科");
            }
            if (StringUtils.isNotBlank(f.getRemark())){
                o.setRemark(f.getRemark());
            } else {
                log.error("PrescribeImgYsyTask 处方id:{},缺失医嘱内容", f.getPrescribeId());
                o.setRemark("请按照用药说明书服用药品，如有不适，请及时就医!");
            }
            o.setHistoryAllergic(f.getHistoryAllergic());
            o.setDiagnose(f.getDiagnose());
            // 在这里添加处方药品列表的值
            List<FsPrescribeDrug> PrescribeDrugList=filterNonDrugPrescribe(list);
            o.setPrescribeDrug(PrescribeDrugList);
            if (signFlag!=null&&signFlag==1){
                //医生签名
                o.setUrl(f.getUrl());
            }else if (signFlag!=null&&signFlag==2){
                //医生签名+药师签名
                o.setUrl(f.getUrl());
                //药师签名
                o.setDrugDoctorUrl(f.getDrugDoctorSignUrl());
            } else if (signFlag==null){//保底策略 默认
                //医生签名
                o.setUrl(f.getUrl());
                //药师签名
                o.setDrugDoctorUrl(f.getDrugDoctorSignUrl());
            }
            //医生名称
            o.setDoctorName(f.getDoctorName());
            //审核药师
            o.setAuditDoctor(f.getDoctorDrugName());
            o.setDispatcher("");
            o.setCheckDoctor("");
            o.setTelPhone(f.getPatientTel());
            FsDoctor fsDoctor = doctorMapper.selectFsDoctorByDoctorId(f.getDoctorId());
            Asserts.notNull(fsDoctor,String.format("医生 %s 未找到！",f.getDoctorId()));
            //执业证号
            o.setJobLicenseNumber(fsDoctor.getPractiseCode());
            //医生证号
            o.setDoctorNo(fsDoctor.getCertificateCode());
            o.setDoctorTitle(fsDoctor.getPosition());

            String url = prescriptionImageService.generatePrescriptionImage(o);
            FsPrescribe fsPrescribe = new FsPrescribe();
            fsPrescribe.setPrescribeImgUrl(url);
            fsPrescribe.setPrescribeId(f.getPrescribeId());
            fsPrescribeMapper.updateFsPrescribe(fsPrescribe);
            f.setPrescribeImgUrl(url);

        } else {
            log.info("处方 {} 对应处方单已经被生成！",prescribeId);
        }
        return f.getPrescribeImgUrl();
    }

    @Override
    public String PrescribeImgYsy(Long prescribeId) {
        FsPrescribeVO f = fsPrescribeMapper.selectFsPrescribeByPrescribeIdVO(prescribeId);
        Asserts.notNull(f,String.format("处方 %d 未找到！",prescribeId));

        FsStoreOrder fsStoreOrder = storeOrderService.selectFsStoreOrderByOrderId(f.getStoreOrderId());
        FsInquiryOrderVO order = fsInquiryOrderMapper.selectFsInquiryOrderVOByOrderId(f.getInquiryOrderId());
        if (StringUtils.isBlank(f.getPrescribeImgUrl())) {
            FsPrescribeDrug d = new FsPrescribeDrug();
            d.setPrescribeId(f.getPrescribeId());
            List<FsPrescribeDrug> list = fsPrescribeDrugMapper.selectFsPrescribeDrugList(d);

            if (CollectionUtils.isEmpty(list)) {
                throw new CustomException(String.format("处方单 %d 对应药品为空！",prescribeId));
            }
            PrescribeXyImgParam o = new PrescribeXyImgParam();
            o.setStatus(fsStoreOrder.getStatus());
            o.setTotalPrice(fsStoreOrder.getPayPrice());
            o.setTime(f.getCreateTime());
            o.setPrescribeId(f.getPrescribeCode());
            o.setPatientName(f.getPatientName());
            o.setPatientGender(f.getPatientGender());
            o.setPatientAge(f.getPatientAge());
            o.setOutpatientId(f.getPrescribeCode());
            if (order != null) {
                o.setBedId(order.getDeptName());
            } else {
                o.setBedId("中医科");
            }
            if (StringUtils.isNotBlank(f.getRemark())){
                o.setRemark(f.getRemark());
            } else {
                o.setRemark("请按照用药说明书服用药品，如有不适，请及时就医!");
            }
            o.setHistoryAllergic(f.getHistoryAllergic());
            o.setDiagnose(f.getDiagnose());
            // 在这里添加处方药品列表的值
            List<FsPrescribeDrug> PrescribeDrugList=filterNonDrugPrescribe(list);
            o.setPrescribeDrug(PrescribeDrugList);
            //医生签名
            o.setUrl(f.getUrl());
            //药师签名
            o.setDrugDoctorUrl(f.getDrugDoctorSignUrl());
            //医生名称
            o.setDoctorName(f.getDoctorName());
            //审核药师
            o.setAuditDoctor(f.getDoctorDrugName());
            o.setDispatcher("");
            o.setCheckDoctor("");
            o.setTelPhone(f.getPatientTel());
            FsDoctor fsDoctor = doctorMapper.selectFsDoctorByDoctorId(f.getDoctorId());
            Asserts.notNull(fsDoctor,String.format("医生 %s 未找到！",f.getDoctorId()));
            //执业证号
            o.setJobLicenseNumber(fsDoctor.getPractiseCode());
            //医生证号
            o.setDoctorNo(fsDoctor.getCertificateCode());
            o.setDoctorTitle(fsDoctor.getPosition());

            String url = prescriptionImageService.generatePrescriptionImage(o);
            FsPrescribe fsPrescribe = new FsPrescribe();
            fsPrescribe.setPrescribeImgUrl(url);
            fsPrescribe.setPrescribeId(f.getPrescribeId());
            fsPrescribeMapper.updateFsPrescribe(fsPrescribe);
            f.setPrescribeImgUrl(url);

        } else {
            log.info("处方 {} 对应处方单已经被生成！",prescribeId);
        }
        return f.getPrescribeImgUrl();
    }

    /**
     * 根据产品最新状态过滤处方单药品列表。
     * <p>
     * 该方法的过滤规则如下:
     * - 对于 productId 非空的处方药，使用其对应产品表(FsStoreProduct)中的 isDrug 状态进行判断，只保留 isDrug=1 的项。
     * - 对于 productId 为空的处方药，直接使用其自身的 isDrug 状态进行判断，只保留 isDrug=1 的项。
     * </p>
     *
     * @param prescribeDrugs 待过滤的处方单药品列表。如果为 null 或空，则直接返回空列表。
     * @return 一个符合上述规则的新列表。
     */
    public List<FsPrescribeDrug> filterNonDrugPrescribe(List<FsPrescribeDrug> prescribeDrugs) {
        if (CollectionUtils.isEmpty(prescribeDrugs)) {
            return Collections.emptyList();
        }
        //提取处方单里面的产品id
        Set<Long> productIds = prescribeDrugs.stream().map(FsPrescribeDrug::getProductId).filter(Objects::nonNull).collect(Collectors.toSet());

        List<FsStoreProduct> storeProductIns = Collections.emptyList(); // 默认为空列表
        if (!productIds.isEmpty()) { // 只有当有 productIds 时才查询
            storeProductIns = fsStoreProductMapper.getStoreProductInProductIds(new ArrayList<>(productIds));
            if (storeProductIns.isEmpty()) {
                log.info("根据产品id列表:{}查询产品信息为空！", productIds);
            }
        }
        //构造一个Map(key为productId,value为FsStoreProduct)
        Map<Long, FsStoreProduct> storeProductMap = storeProductIns.stream().collect(Collectors.toMap(FsStoreProduct::getProductId, Function.identity()));
        // 创建新列表存放过滤后的结果
        List<FsPrescribeDrug> filteredDrugs = new ArrayList<>();

        for (FsPrescribeDrug drug : prescribeDrugs) {
            boolean shouldKeep = false; // 默认不保留

            if (drug.getProductId() != null) {
                // 情况 A: productId 非空，依赖产品表
                FsStoreProduct product = storeProductMap.get(drug.getProductId());
                if (product != null) {
                    // 找到了对应产品，检查 isDrug
                    if (Integer.valueOf(1).equals(product.getIsDrug())) {
                        shouldKeep = true;
                    } else {
                        log.debug("药品 '{}' (ID: {}) 在产品表中 isDrug={}，将被过滤。",
                                drug.getDrugName(), drug.getProductId(), product.getIsDrug());
                    }
                } else {
                    // 产品表中找不到该 productId，视为无效数据，不保留
                    log.warn("药品 '{}' (ID: {}) 在产品表中未找到对应记录，将被过滤。",
                            drug.getDrugName(), drug.getProductId());
                    // shouldKeep = false;
                }
            } else {
                // 情况 B: productId 为 null，依赖自身 isDrug 状态
                if (Integer.valueOf(1).equals(drug.getIsDrug())) {
                    shouldKeep = true;
                } else {
                    log.debug("药品 '{}' (ID: null) 自身 isDrug={}，将被过滤。",
                            drug.getDrugName(), drug.getIsDrug());
                }
            }

            if (shouldKeep) {
                filteredDrugs.add(drug);
            }
        }

        return filteredDrugs;
    }

    @Override
    public Long insertFsPrescribeByPackageOrder(FsPackageOrder packageOrder) {
        log.info("开始生成处方单");
        FsPackage fsPackage=fsPackageMapper.selectFsPackageByPackageId(packageOrder.getPackageId());
        log.info("packageOrder:{}",packageOrder);
        FsPrescribe fsPrescribe = new FsPrescribe();
        fsPrescribe.setPrescribeType(fsPackage.getProductType());
        fsPrescribe.setRecipeType(fsPackage.getRecipeType());
        fsPrescribe.setStoreId(fsPackage.getStoreId());
        fsPrescribe.setStatus(0);
        fsPrescribe.setIcdCode(fsPackage.getIcdCode());
        fsPrescribe.setAuditTime(DateUtils.getNowDate());
        fsPrescribe.setCreateTime(DateUtils.getNowDate());
        fsPrescribe.setUsageJson("{}");
        fsPrescribe.setDiagnose(fsPackage.getTags());
        FsPrescribeUsageDTO fsPrescribeUsageDTO = new FsPrescribeUsageDTO();
        if (fsPackage.getProductType()==2){
            fsPrescribeUsageDTO.setCounts(fsPackage.getCounts()+0L);
            fsPrescribeUsageDTO.setUsageFrequencyUnit(fsPackage.getUsageFrequencyUnit());
            fsPrescribeUsageDTO.setRemark(fsPackage.getDoctorRemark());
        }
        if (packageOrder.getRemark()!=null||packageOrder.getRemark()!=""){
            fsPrescribeUsageDTO.setRemark(packageOrder.getDoctorRemark());
        }else {
            fsPrescribeUsageDTO.setRemark("请按照用药说明书服用药品，如有不适，请及时就医!");
        }

        String jsonString = JSON.toJSONString(fsPrescribeUsageDTO);
        fsPrescribe.setUsageJson(jsonString);

        fsPrescribe.setUserId(packageOrder.getUserId());
        String prescribeCode=IdUtil.getSnowflake(0, 0).nextIdStr();
        fsPrescribe.setPrescribeCode(prescribeCode);
        FsPackagePatientDTO patJson = JSON.parseObject(packageOrder.getPatientJson(),FsPackagePatientDTO.class);
        if (patJson.getBirthday() == null) {
            patJson.setBirthday(-285753600000L);
        }
        long currentTimeMillis = System.currentTimeMillis();
        long ageInMillis = currentTimeMillis - patJson.getBirthday();
        long ageInSeconds = ageInMillis / 1000;
        long ageInYears = ageInSeconds / (365 * 24 * 3600);
        fsPrescribe.setPatientAge(ageInYears+"");
        fsPrescribe.setPatientId(patJson.getPatientId()+0L);
        fsPrescribe.setPatientName(patJson.getPatientName());
        fsPrescribe.setPatientTel(patJson.getMobile());
        fsPrescribe.setPatientGender(patJson.getSex().toString());
        fsPrescribe.setPatientBirthday(new SimpleDateFormat("yyyy-MM-dd").format(new Date(patJson.getBirthday())));
        fsPrescribe.setDoctorId(packageOrder.getDoctorId());
        FsDoctor fsDoctor = doctorMapper.selectFsDoctorByDoctorId(packageOrder.getDoctorId());
        if (fsDoctor==null){
            throw new CustomException("医生查询错误:"+packageOrder.getDoctorId());
        }

        fsPrescribe.setPrescribeDoctorId(fsDoctor.getDoctorId());
        fsPrescribe.setPrescribeDoctorSignUrl(fsDoctor.getSignUrl());

        //分配在线的随机药师
        FsDoctor fsDrugDoctor = null;
        try {
            // 使用新写的轮询服务分配药师，传入处方编号
            fsDrugDoctor = pollingAssignDoctorService.getNextPharmacist(prescribeCode);

            fsPrescribe.setDrugDoctorId(fsDrugDoctor.getDoctorId());
            fsPrescribe.setDrugDoctorSignUrl(fsDrugDoctor.getSignUrl());

            log.info("轮询分配药师成功 - 处方号:{}, 药师ID:{}, 药师姓名:{}",
                    prescribeCode, fsDrugDoctor.getDoctorId(), fsDrugDoctor.getDoctorName());
        } catch (Exception e) {
            log.error("分配药师失败 - 处方号:{}", prescribeCode, e);
            fsPrescribe.setDrugDoctorId(1L);//为了不影响主业务执行设置默认值
        }

        int i = fsPrescribeMapper.insertFsPrescribe(fsPrescribe);
        if(i>0){
            String productJson = packageOrder.getPackageJson();
            Map<String,Object> prod = (Map) JSON.parse(productJson);

            List<FsPackagePruductDTO> prodList = JSON.parseArray((String) prod.get("productJson"), FsPackagePruductDTO.class);
            for (FsPackagePruductDTO dto : prodList) {
                FsPrescribeDrug prescribeDrug = new FsPrescribeDrug();
                //写入药品
                prescribeDrug.setProductAttrValueId(dto.getId());
                prescribeDrug.setPrescribeId(fsPrescribe.getPrescribeId());
                prescribeDrug.setDrugName(dto.getProductName());
                prescribeDrug.setDrugSpec(dto.getPrescribeSpec());
                prescribeDrug.setIsDrug(dto.getIsDrug());
                prescribeDrug.setUsageMethod(dto.getUsageMethod());
                prescribeDrug.setUsagePerUseCount(dto.getUsagePerUseCount());
                prescribeDrug.setUsageFrequencyUnit("每日"+(dto.getUsageFrequencyUnit()!=null?dto.getUsageFrequencyUnit()+"":"1")+"次");
                prescribeDrug.setDrugPrice(dto.getPrice());
                prescribeDrug.setDrugNum(dto.getCount()+0L);
                prescribeDrug.setProductId(dto.getProductId());
                prescribeDrug.setDrugImgUrl(dto.getImage());
                prescribeDrug.setDrugType(fsPackage.getProductType());
                prescribeDrugService.insertFsPrescribeDrug(prescribeDrug);
            }

        }



        return fsPrescribe.getPrescribeId();
    }

    @Override
    public List<FsPrescribeExcelListVO> selectFsPrescribeExcelListVO(FsPrescribeParam fsPrescribe) {
        return fsPrescribeMapper.selectFsPrescribeExcelListVO(fsPrescribe);
    }

    @Override
    public List<FsMessageFeedbackExportListVO> selectFsMessageFeedbackExportListVO(FsPrescribeParam fsPrescribe) {
        return fsPrescribeMapper.selectFsMessageFeedbackExportListVO(fsPrescribe);
    }

    @Override
    public String getPrescribeCodeUrl(Long prescribeId) {
        FsSysConfig sysConfig = configUtil.getSysConfig();
        FsPrescribeVO fsPrescribeVO = fsPrescribeMapper.selectFsPrescribeByPrescribeIdVO(prescribeId);
        if (fsPrescribeVO.getPrescribeCodeUrl()!=null&&fsPrescribeVO.getPrescribeCodeUrl()!=""){
            return fsPrescribeVO.getPrescribeCodeUrl();
        }
        String doctorName = fsPrescribeVO.getDoctorName();
        if (doctorName==null||doctorName.equals("")){
            throw  new CustomException("医生不存在");
        }
        String patientName = fsPrescribeVO.getPatientName();
        String codeUrl=sysConfig.getCodeUrl()+"prescribe?prescribeId="+prescribeId;

        File mb = new File("C:\\fs\\pCode.jpg");
        if (!mb.exists()) {
            // 创建目录
            throw  new CustomException("模板文件不存在");
        }
        BufferedImage image = null;
        try {
            image = ImageIO.read(mb);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建画笔(image为上一步的图片对象)
        Graphics2D pen = image.createGraphics();
        //处理字体 高清加边缘模糊
        pen.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        pen.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        pen.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        pen.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
        pen.setFont(new Font("黑体", Font.BOLD  ,120));
        pen.setColor(Color.decode("#612f00"));

        if (doctorName.length()==2){
            pen.drawString(doctorName+"已为您",135,285);
        }else {
            pen.drawString(doctorName+"已为您",80,285);
        }

        pen.setFont(new Font("黑体", Font.BOLD  ,58));
        pen.setColor(Color.decode("#fdf3e7"));
        if (patientName.length()==2){
            pen.drawString(patientName+"的处方",300,1438);
        }else {
            pen.drawString(patientName+"的处方",270,1438);
        }


        try {
            ByteArrayOutputStream qr = QRCodeUtils.create(codeUrl);
            byte[] imageBytes = qr.toByteArray(); // 从 ByteArrayOutputStream 获取字节数组

            ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes); // 创建 ByteArrayInputStream
            BufferedImage qrImage = ImageIO.read(inputStream);
            pen.drawImage(qrImage, 260, 815, 380, 380, null);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream inputStream = new ByteArrayInputStream(os.toByteArray());
        CloudStorageService storage = OSSFactory.build();
        String url = storage.uploadSuffix(inputStream, ".jpg");
        FsPrescribe fsPrescribe = new FsPrescribe();
        fsPrescribe.setPrescribeCodeUrl(url);
        fsPrescribe.setPrescribeId(prescribeId);
        fsPrescribeMapper.updateFsPrescribe(fsPrescribe);
        return url;
    }

    @Override
    public Boolean isEntityNull(FsPrescribeParam param) {
        if (param == null) {
            return true; // 整个实体对象为null
        }

        Class<? extends FsPrescribeParam> entityClass = param.getClass();
        Field[] fields = entityClass.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(param);
                if (value != null) {
                    return false; // 实体对象中有字段不为null
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return true; // 实体对象内所有字段为null
    }

    @Override
    public Long selectFsPrescribeExcelListVOCount(FsPrescribeParam fsPrescribe) {

       return fsPrescribeMapper.selectFsPrescribeExcelListVOCount(fsPrescribe);
    }
    @Async
    @Override
    public void exportData(FsPrescribeParam param) {
        List<FsPrescribeExcelListVO> list = fsPrescribeMapper.selectFsPrescribeExcelListVO(param);

        for (FsPrescribeExcelListVO vo : list){
            if (vo.getPatientTel()!=null){
                vo.setPatientTel(vo.getPatientTel().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }
        }
        ExcelUtil<FsPrescribeExcelListVO> util = new ExcelUtil<FsPrescribeExcelListVO>(FsPrescribeExcelListVO.class);
        AjaxResult result = util.exportExcel(list, "处方数据");

        FsExportTask task=fsExportTaskMapper.selectFsExportTaskByTaskId(param.getTaskId());
        task.setFinishTime(new Date());
        task.setStatus(1);
        task.setFileUrl(result.get("msg").toString());
        fsExportTaskMapper.updateFsExportTask(task);
    }
    @Async
    @Override
    public void exportMessageFeedback(FsPrescribeParam param) {
        List<FsMessageFeedbackExportListVO> list = fsPrescribeMapper.selectFsMessageFeedbackExportListVO(param);

        for (FsMessageFeedbackExportListVO vo : list){
            vo.setFeedbackContent("复诊");
            if (vo.getPatientTel()!=null){
                vo.setPatientTel(vo.getPatientTel().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }
            vo.setFeedbackTime(vo.getAuditTime());
        }
        ExcelUtil<FsMessageFeedbackExportListVO> util = new ExcelUtil<FsMessageFeedbackExportListVO>(FsMessageFeedbackExportListVO.class);
        AjaxResult result = util.exportExcel(list, "医疗信息反馈单数据");

        FsExportTask task=fsExportTaskMapper.selectFsExportTaskByTaskId(param.getTaskId());
        task.setFinishTime(new Date());
        task.setStatus(1);
        task.setFileUrl(result.get("msg").toString());
        fsExportTaskMapper.updateFsExportTask(task);
    }

    @Override
    public List<Long> selectFsPrescribeByPrescribeIdByOrderType() {
        return fsPrescribeMapper.selectFsPrescribeByPrescribeIdByOrderType();
    }

    @Override
    public void PrescribeStoreImg(Long id) {
        FsPrescribeVO f = fsPrescribeMapper.selectFsPrescribeByPrescribeIdVO(id);
        if (f==null){
            return ;
        }
        FsStoreOrder fsStoreOrder = storeOrderService.selectFsStoreOrderByOrderId(f.getStoreOrderId());
        FsPrescribeDrug d = new FsPrescribeDrug();
        d.setPrescribeId(f.getPrescribeId());
        List<FsPrescribeDrug> list = fsPrescribeDrugMapper.selectFsPrescribeDrugList(d);
        if (list.isEmpty()){
                return ;
        }
            FsPrescribeUsageDTO usage = JSONUtil.toBean(f.getUsageJson(), FsPrescribeUsageDTO.class);
            // 设置字段值
            PrescribeZyImgParam o = new PrescribeZyImgParam();
            o.setTime(f.getCreateTime());
            o.setPrescribeId(f.getPrescribeCode());
            o.setPatientName(f.getPatientName());
            o.setPatientGender(f.getPatientGender());
            o.setPatientAge(f.getPatientAge());
            o.setPatientTel(f.getPatientTel());
            o.setPrescribeDoctorName(f.getPrescribeDoctorName());
            o.setUserName(fsStoreOrder.getUserName()); //发货地址
            o.setUserPhone(fsStoreOrder.getUserPhone()); //收货人手机
            o.setUserAddress(fsStoreOrder.getUserAddress()); //收货地址
            o.setDiagnose(f.getDiagnose());
            o.setPrescribeDrug(list); // 在这里添加处方药品列表的值
            o.setEat(usage.getUsageMethod());
            o.setUsageFrequencyUnit(usage.getUsageFrequencyUnit());
            o.setRemark(usage.getRemark());
            o.setDoctorName(f.getDoctorName());
            o.setCheck(f.getDoctorDrugName());
            if (usage.getCounts()!=null){
                o.setSize(usage.getCounts().toString());
            }
            o.setUrl(f.getPrescribeDoctorSignUrl());
            o.setDrugDoctorUrl(f.getDrugDoctorSignUrl());
            o.setTotalPrice(fsStoreOrder.getPayPrice());
            String s = getFsPrescribeStoreZyImg(o);

            FsPrescribe fsPrescribe = new FsPrescribe();
            fsPrescribe.setPrescribeImgStoreUrl(s);
            fsPrescribe.setPrescribeId(f.getPrescribeId());
            fsPrescribeMapper.updateFsPrescribe(fsPrescribe);

    }

    private String getFsPrescribeStoreZyImg(PrescribeZyImgParam o) {
        File mb = new File("C:\\fs\\zycf.jpg");
        if (!mb.exists()) {
            // 创建目录
            throw  new CustomException("模板文件不存在");
        }
        BufferedImage image = null;
        try {
            image = ImageIO.read(mb);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建画笔(image为上一步的图片对象)
        Graphics2D pen = image.createGraphics();
        pen.setColor(Color.black);
        //处理字体 高清加边缘模糊
        pen.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        pen.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        pen.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        pen.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
        pen.setFont(new Font("黑体", Font.PLAIN, 21));
        // 将date对象格式化为字符串

        penDrawString(pen,new SimpleDateFormat("yyyy-MM-dd").format(o.getTime()), 730, 290);
        penDrawString(pen,o.getPrescribeId(),1030,290);
        penDrawString(pen,o.getPatientName(),136,372);
        penDrawString(pen,o.getPatientGender().equals("1")?"男":o.getPatientGender().equals("2")?"女":o.getPatientGender(),420,372);
        penDrawString(pen,o.getPatientAge(),690,372);
        penDrawString(pen,o.getPatientTel(),970,372);
        String address= o.getUserName()+"      "+o.getUserPhone()+"     "+o.getUserAddress();
        penDrawString(pen,address,180,445);
        penDrawString(pen,o.getDiagnose(),180,515);
        List<FsPrescribeDrug> Drug = o.getPrescribeDrug();
        int size=Drug.size();

        for (int i = 0; i < size/3.0; i++) {
            if (i*3<size){
                pen.drawString(Drug.get(i*3).getDrugName()+"  "+Drug.get(i*3).getDrugNum()+"克",145,680+i*50);
            }
            if (i*3+1<size){
                pen.drawString(Drug.get(i*3+1).getDrugName()+"  "+Drug.get(i*3+1).getDrugNum()+"克",510,680+i*50);
            }
            if (i*3+2<size){
                pen.drawString(Drug.get(i*3+2).getDrugName()+"  "+Drug.get(i*3+2).getDrugNum()+"克",875,680+i*50);
            }
        }
        penDrawString(pen,o.getEat(),110,1195);
        penDrawString(pen,o.getUsageFrequencyUnit(),135,1240);
        penDrawString(pen,o.getRemark(),110,1288);

        // penDrawString(pen,o.getDoctorName(),152,1378);
        if (o.getUrl()!=null){
            try {
                URL   imageUrl = new URL(o.getUrl());
                BufferedImage img = ImageIO.read(imageUrl);
                pen.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                pen.drawImage(img, 130, 1420, 127, 60, null);
            } catch (Exception e) {
                throw new CustomException("获取医生签名图片失败");
            }

        }else {
            penDrawString(pen,o.getPrescribeDoctorName(),152,1450);
        }
        if (o.getDrugDoctorUrl()!=null){
            try {
                URL   imageUrl3 = new URL(o.getDrugDoctorUrl());
                BufferedImage img3 = ImageIO.read(imageUrl3);
                pen.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                pen.drawImage(img3, 370, 1345, 127, 60, null);
            } catch (Exception e) {
                throw new CustomException("获取药师签名图片失败");
            }
        }
//        penDrawString(pen,o.getCheck(),348,1378);
        penDrawString(pen,o.getSize(),620,1378);
        if (o.getTotalPrice()!=null){
            penDrawString(pen,o.getTotalPrice().toString(),370,1452);
            penDrawString(pen,o.getTotalPrice().toString(),620,1452);
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream inputStream = new ByteArrayInputStream(os.toByteArray());
        CloudStorageService storage = OSSFactory.build();
        String url = storage.uploadSuffix(inputStream, ".jpg");
        return url;
    }

    @Override
    public FsPrescribeVO selectFsPrescribeByPrescribeIdVO(Long prescribeId) {
        FsPrescribeVO f = fsPrescribeMapper.selectFsPrescribeByPrescribeIdVO(prescribeId);
        return f;
    }

    @Override
    public List<FsPrescribeDrug> selectFsPrescribeDrugByPrescribeIdVO(Long prescribeId) {
        FsPrescribeDrug drug = new FsPrescribeDrug();
        drug.setPrescribeId(prescribeId);
        return fsPrescribeDrugMapper.selectFsPrescribeDrugList(drug);
    }


    @Override
    public void auditPrescribe() {
        List<FsPrescribe> FsPrescribes=fsPrescribeDrugMapper.selectFsPrescribeNoAudit();
        for (FsPrescribe fsPrescribe : FsPrescribes) {
            Long id = doctorMapper.selectFsDoctorType2Ids(fsPrescribe.getPrescribeType());
            FsPrescribeAuditParam param=new FsPrescribeAuditParam();
            param.setDoctorId(id);
            param.setStatus(1);
            param.setPrescribeId(fsPrescribe.getPrescribeId());
            audit(param);
        }
    }

    @Override
    @Transactional
    public R audit(FsPrescribeAuditParam param){
        FsPrescribe prescribe=this.selectFsPrescribeByPrescribeId(param.getPrescribeId());
        if(prescribe.getStatus()!=0){
            return R.error("非法操作");
        }
        //无论审核是否通过，都删除之前只有医生签名的处方图片,为了后续药师审核通过重新生成图片
        delUrl(param.getPrescribeId());

        FsPrescribe map=new FsPrescribe();
        map.setPrescribeId(param.getPrescribeId());
        map.setDrugDoctorId(param.getDoctorId());
        map.setStatus(param.getStatus());
        map.setAuditReason(param.getAuditReason());
        map.setAuditTime(new Date());
        FsDoctor doctor=doctorService.selectFsDoctorByDoctorId(map.getDrugDoctorId());
        if(StringUtils.isNotEmpty(doctor.getSignUrl())){
            map.setDrugDoctorSignUrl(doctor.getSignUrl());
        }

        //获取医生和药师名称
        FsPrescribeListVO vo = fsPrescribeMapper.selectDoctorNameAndDoctorDrugNameByPrescribeId(prescribe.getPrescribeId());
        //生成审核记录
        FsPrescribeRecord prescribeRecord = new FsPrescribeRecord();
        prescribeRecord.setPrescribeId(prescribe.getPrescribeId());
        prescribeRecord.setDoctorId(prescribe.getDoctorId());
        prescribeRecord.setDrugDoctorId(prescribe.getDrugDoctorId());
        prescribeRecord.setPrescribeImgUrl(prescribe.getPrescribeImgUrl());
        prescribeRecord.setStatus(param.getStatus());
        if (prescribe.getStatus() == 2) {
            prescribeRecord.setAuditReason(param.getAuditReason());
        }
        prescribeRecord.setCreateTime(DateUtils.getNowDate());
        prescribeRecord.setDoctorName(vo.getDoctorName());
        prescribeRecord.setDrugDoctorName(vo.getDoctorDrugName());
        prescribeRecordService.insertFsPrescribeRecord(prescribeRecord);
        if (param.getStatus() == 1) {
            if (prescribe.getThirdPartyUserId()!=null){
                //对于第三方用户的处方,药师审核通过后设置状态为未推送数据给第三方
                map.setIsSendToThirdParty(0);
            }
            map.setAuditReason("");
            //fsExportTaskService.updateFsExportTaskByPrescribeId(param.getPrescribeId());
            //重置处方单定时任务(药师审核通过后生成拥有药师签名的标识)
            fsExportTaskService.resetFsExportTaskByPrescribeIdAndSignFlag(param.getPrescribeId(),2);

            //审核通过 同步用户信息采集进度
            FsStoreOrder order = storeOrderMapper.selectByPrescriptionId(prescribe.getPrescribeId());
            if (order != null){
                FsUserInformationCollectionSchedule schedule = scheduleMapper.selectFsUserInformationCollectionByOrderCode(order.getOrderCode());
                if (schedule != null){
                    //审核通过 "待用户二次确认"节点
                    schedule.setCurrentStep(PrescriptionTaskStepEnum.WAITING_SECOND_CONFIRM.getCode());
                    scheduleMapper.updateFsUserInformationCollectionSchedule(schedule);
                    log.info("同步用户信息采集进度节点为:{},信息采集表id:{}",PrescriptionTaskStepEnum.WAITING_SECOND_CONFIRM.getDesc(),schedule.getCollectionId());
                }
            }
        }
        if (param.getStatus() == 2) {
            //生成拒方开方消息
            DoctorMsg msg = new DoctorMsg();
            msg.setDoctorId(prescribe.getDoctorId());
            msg.setType(1);
            msg.setTitle("药师拒方，处方编号："+prescribe.getPrescribeCode());
            msg.setContent("拒方原因："+param.getAuditReason()+",请重新开方");
            msg.setCreateTime(DateUtils.getNowDate());
            doctorMsgMapper.insertDoctorMsg(msg);

            //审核不通过 同步用户信息采集进度
            FsStoreOrder order = storeOrderMapper.selectByPrescriptionId(prescribe.getPrescribeId());
            if (order != null){
                FsUserInformationCollectionSchedule schedule = scheduleMapper.selectFsUserInformationCollectionByOrderCode(order.getOrderCode());
                if (schedule != null){
                    //审核不通过 "待开方"节点
                    schedule.setCurrentStep(PrescriptionTaskStepEnum.WAITING_PRESCRIBE.getCode());
                    scheduleMapper.updateFsUserInformationCollectionSchedule(schedule);
                    log.info("同步用户信息采集进度节点为:{},信息采集表id:{}",PrescriptionTaskStepEnum.WAITING_PRESCRIBE.getDesc(),schedule.getCollectionId());
                }
            }
        }

        if (this.updateFsPrescribe(map) > 0){
            return R.ok("审核成功");
        }

//        if(param.getStatus().equals(1)){
//            this.updateFsPrescribe(map);
//            //写入订单
//            storeOrderService.createOrder(prescribe.getPrescribeId());
//            //发送信息
//            String orderId=prescribe.getInquiryOrderId().toString();
//            MsgDTO msgDTO=new MsgDTO();
//            MsgCustomDTO customDTO=new MsgCustomDTO();
//            FsInquiryOrder fsInquiryOrder = fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(prescribe.getInquiryOrderId());
//            customDTO.setType("inquiry");
//            customDTO.setOrderId(orderId);
//            customDTO.setImType(1);
//            customDTO.setOrderType(fsInquiryOrder.getOrderType());
//            msgDTO.setCloudCustomData(JSONUtil.toJsonStr(customDTO));
//            msgDTO.setFrom_Account("D-"+prescribe.getDoctorId());
//            msgDTO.setTo_Account("U-"+prescribe.getUserId());
//            List<MsgDataDTO> msgs=new ArrayList<>();
//            MsgDataDTO msg=new MsgDataDTO();
//            String ext= JSONUtil.toJsonStr(prescribe);
//
//            msg.setMsgContent(new MsgDataFormatDTO("prescribe",ext,orderId));
//            msg.setMsgType("TIMCustomElem");//TIMCustomElem
//            msgs.add(msg);
//            msgDTO.setMsgBody(msgs);
//            imService.sendMsg(msgDTO);
//            return R.ok();
//        }
        return R.error("审核失败");

    }

    @Override
    public R auditAfterPayment(FsPrescribeAuditParam param) {
        FsPrescribe prescribe=this.selectFsPrescribeByPrescribeId(param.getPrescribeId());
        if(prescribe.getStatus()!=0){
            return R.error("非法操作");
        }
        //无论审核是否通过，都删除之前只有医生签名的处方图片，为了后续创建新的处方图片
        delUrl(param.getPrescribeId());

        FsPrescribe map=new FsPrescribe();
        map.setPrescribeId(param.getPrescribeId());
        map.setDrugDoctorId(param.getDoctorId());
        map.setStatus(param.getStatus());
        map.setAuditReason(param.getAuditReason());
        map.setAuditTime(new Date());
        FsDoctor doctor=doctorService.selectFsDoctorByDoctorId(map.getDrugDoctorId());
        if(StringUtils.isNotEmpty(doctor.getSignUrl())){
            map.setDrugDoctorSignUrl(doctor.getSignUrl());
        }

        //获取医生和药师名称
        FsPrescribeListVO vo = fsPrescribeMapper.selectDoctorNameAndDoctorDrugNameByPrescribeId(prescribe.getPrescribeId());
        //生成审核记录
        FsPrescribeRecord prescribeRecord = new FsPrescribeRecord();
        prescribeRecord.setPrescribeId(prescribe.getPrescribeId());
        prescribeRecord.setDoctorId(prescribe.getDoctorId());
        prescribeRecord.setDrugDoctorId(prescribe.getDrugDoctorId());
        prescribeRecord.setPrescribeImgUrl(prescribe.getPrescribeImgUrl());
        prescribeRecord.setStatus(param.getStatus());
        if (prescribe.getStatus() == 2) {//药师审核不通过设置原因
            prescribeRecord.setAuditReason(param.getAuditReason());
        }
        prescribeRecord.setCreateTime(DateUtils.getNowDate());
        prescribeRecord.setDoctorName(vo.getDoctorName());
        prescribeRecord.setDrugDoctorName(vo.getDoctorDrugName());
        prescribeRecordService.insertFsPrescribeRecord(prescribeRecord);
        if (param.getStatus() == 1) {
            //审核通过
            map.setAuditReason("");
            //重置处方单定时任务(药师审核通过后需要生成拥有药师签名的标识)
            fsExportTaskService.resetFsExportTaskByPrescribeIdAndSignFlag(param.getPrescribeId(),2);
            //更新采集表个微状态 销售可以根据处方给客户分享套餐包进行下单了
            FsUserInformationCollection informationCollection = collectionMapper.selectFsUserInformationCollectionById(param.getCollectionId());
            informationCollection.setPersonalCollectStatus(PostPayPrescStatusEnum.PACKAGE_BIND.getCode());
            collectionMapper.updateFsUserInformationCollection(informationCollection);
        }
        if (param.getStatus() == 2) {
            //生成拒方消息
            DoctorMsg msg = new DoctorMsg();
            msg.setDoctorId(prescribe.getDoctorId());
            msg.setType(1);
            msg.setTitle("药师拒方，处方编号："+prescribe.getPrescribeCode());
            msg.setContent("拒方原因："+param.getAuditReason()+",请重新开方");
            msg.setCreateTime(DateUtils.getNowDate());
            doctorMsgMapper.insertDoctorMsg(msg);

            FsUserInformationCollection informationCollection = collectionMapper.selectFsUserInformationCollectionById(param.getCollectionId());
            informationCollection.setPersonalCollectStatus(PostPayPrescStatusEnum.PENDING_DOCTOR.getCode());
            collectionMapper.updateFsUserInformationCollection(informationCollection);
        }
        if (this.updateFsPrescribe(map) > 0){
            return R.ok("审核成功");
        }
        return R.error("审核失败");
    }

    public void penDrawString( Graphics2D pen,String value,int x,int y){
        if (value!=null){
            pen.drawString(value,x,y);
        }
    }

    @Override
    public List<FsPrescribeListDVO> selectFsPrescribeListDVOByCompanyUser(FsPrescribeListDCompanyParam param) {
        List<FsPrescribeListDVO> list=fsPrescribeMapper.selectFsPrescribeListUVOByCompanyUser(param);
        for(FsPrescribeListDVO vo:list){
            FsPrescribeDrug map=new FsPrescribeDrug();
            map.setPrescribeId(vo.getPrescribeId());
            vo.setDrugs(fsPrescribeDrugMapper.selectFsPrescribeDrugList(map));
        }
        return list;


    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void confirmPrescribe(FsPrescribeParam param) {
        FsPrescribe fsPrescribe = fsPrescribeMapper.selectFsPrescribeByPrescribeId(param.getPrescribeId());
        if (fsPrescribe != null&&fsPrescribe.getCollectionId()!=null) {
            FsUserInformationCollection collection = collectionMapper.selectFsUserInformationCollectionById(fsPrescribe.getCollectionId());
            if (collection.getQwTag()==1){
                log.error("开方流程异常,此接口不支持个微信息采集处方开方");
                throw new CustomException("开方流程异常,不支持个微信息采集处方开方");
            }
        }
        fsPrescribe.setDoctorConfirm(1);
        //医生操作结束时间（第一次确认处方）
        if (fsPrescribe.getEndOperateTime() == null) {
            if (param.getStartOperateTime() == null) {
                throw new CustomException("操作时间参数错误，开方失败");
            }
            fsPrescribe.setStartOperateTime(new Date(param.getStartOperateTime()));
            fsPrescribe.setEndOperateTime(DateUtils.getNowDate());
            Long seconds = DateUtil.between(fsPrescribe.getStartOperateTime(), fsPrescribe.getEndOperateTime(), DateUnit.SECOND);
            fsPrescribe.setOperateSecond(seconds);
//            if (fsPrescribe.getStartOperateTime() != null && fsPrescribe.getEndOperateTime() != null) {
//                Long seconds = DateUtil.between(fsPrescribe.getStartOperateTime(), fsPrescribe.getEndOperateTime(), DateUnit.SECOND);
//                fsPrescribe.setOperateSecond(seconds);
//            }
        }
        //处方诊断
        fsPrescribe.setDiagnose(param.getDiagnose());
        //处方医嘱
        fsPrescribe.setRemark(param.getRemark());
        //待审核
        fsPrescribe.setStatus(0);
        fsPrescribeMapper.updateFsPrescribe(fsPrescribe);


        //用户信息采集医生确认
        FsUserInformationCollection collection = redisCache.getCacheObject("collectionPrescribeId:" + fsPrescribe.getPrescribeId());
        log.info("处方id：{}，采集信息{}",fsPrescribe.getPrescribeId(),collection);
        if (collection != null) {
            FsUserInformationCollection map = new FsUserInformationCollection();
            map.setId(collection.getId());
            map.setDoctorConfirm(1);
            collectionMapper.updateFsUserInformationCollection(map);
            //确认完成后删除缓存
            redisCache.deleteObject("collectionPrescribeId:" + fsPrescribe.getPrescribeId());
        }
        //医生确认后生成处方单
        PrescriptionTaskRecord record = new PrescriptionTaskRecord();
        record.setPrescribeId(param.getPrescribeId());
        record.setCreateTime(LocalDateTime.now());
        record.setExecuteStatus(0);
        record.setRetryCount(0);
        //只生成医生签名图片标识
        record.setSignFlag(1);
        prescriptionTaskRecordMapper.insert(record);

        //生成药师审核消息
        DoctorMsg msg = new DoctorMsg();
        msg.setType(2);
        msg.setDoctorId(fsPrescribe.getDrugDoctorId());
        msg.setTitle("处方审核");
        msg.setContent("处方编号："+fsPrescribe.getPrescribeCode()+"待审核");
        msg.setCreateTime(DateUtils.getNowDate());
        doctorMsgMapper.insertDoctorMsg(msg);

        //根据处方id查询订单号，然后根据订单号查询用户采集信息
        FsStoreOrder fsStoreOrder=storeOrderMapper.selectByPrescriptionId(fsPrescribe.getPrescribeId());
        if(fsStoreOrder != null){
            FsUserInformationCollection collectionResult = collectionMapper.selectByOrderCode(fsStoreOrder.getOrderCode());
            if (collectionResult != null){
                //同步用户信息采集进度
                FsUserInformationCollectionSchedule schedule = scheduleMapper.selectCollectionScheduleByCollectionId(collectionResult.getId());
                if (schedule != null){
                    //"待药师审核“节点
                    schedule.setCurrentStep(PrescriptionTaskStepEnum.WAITING_PHARMACIST_REVIEW.getCode());
                    //写入处方订单号
                    schedule.setOrderCode(fsStoreOrder.getOrderCode());
                    scheduleMapper.updateFsUserInformationCollectionSchedule(schedule);
                    log.info("同步用户信息采集进度节点为:{},信息采集表id:{}",PrescriptionTaskStepEnum.WAITING_PHARMACIST_REVIEW.getDesc(),schedule.getCollectionId());
                }
            }
        }
        //医生确认处方后立即生成处方图片
        self().createDoctorSignImg(fsPrescribe);
    }

    //手动生成带医生签名的处方图片
    public void createDoctorSignImg(FsPrescribe fsPrescribe) {
        if(fsPrescribe != null&& fsPrescribe.getPrescribeId() != null) {
            String prescribeImgUrl = self().prescribeImgYsyTask(fsPrescribe.getPrescribeId(),1);//1:只生成有医生签名的处方
            fsPrescribe.setPrescribeImgUrl(prescribeImgUrl);
            fsPrescribeMapper.updateFsPrescribe(fsPrescribe);
        }
    }


    @Override
    public void collectionPrescribe(Long prescribeId) {
        FsPrescribe fsPrescribe = fsPrescribeMapper.selectFsPrescribeByPrescribeId(prescribeId);
        fsPrescribe.setDoctorConfirm(0);
        //待审核
        fsPrescribe.setStatus(0);
        //医生开始操作时间
        fsPrescribe.setStartOperateTime(DateUtils.getNowDate());
        fsPrescribeMapper.updateFsPrescribe(fsPrescribe);
    }

    @Override
    public void delUrl(Long prescribeId) {
        fsPrescribeMapper.delUrl(prescribeId);

    }

    @Override
    public Long selectDoctorAvgOperateTime(Long doctorId) {
        return fsPrescribeMapper.selectDoctorAvgOperateTime(doctorId);
    }

    @Override
    public PageInfo<DoctorOperateStatVO> getDurationList(PrescribeStatParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<DoctorOperateStatVO> operateStatVOList = fsPrescribeMapper.selectDoctorOperateStatList(param);
        return new PageInfo<>(operateStatVOList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleReject(PrescribeRejectDTO rejectDTO) {
        //根据处方id查询订单号，根据订单号查询信息采集表id,根据信息采集表id 查询 信息采集进度
        FsStoreOrder fsStoreOrder =new FsStoreOrder();
        fsStoreOrder.setPrescribeId(rejectDTO.getPrescribeId());
        List<FsStoreOrder> fsStoreOrders = storeOrderMapper.selectFsStoreOrderList(fsStoreOrder);
        if (CollectionUtils.isEmpty(fsStoreOrders)){
            log.error("处方订单不存在,处方id:{}",rejectDTO.getPrescribeId());
            throw new CustomException("订单不存在");
        }else {
            String orderCode = fsStoreOrders.get(0).getOrderCode();
            FsUserInformationCollection fsUserInformationCollection = new FsUserInformationCollection();
            fsUserInformationCollection.setPackageOrderCode(orderCode);
            List<FsUserInformationCollection> fsUserInformationCollections = fsUserInformationCollectionService.selectFsUserInformationCollectionList(fsUserInformationCollection);
            Long collectionId;
            if (CollectionUtils.isEmpty(fsUserInformationCollections)){
                //如果用户信息采集表根据订单号查询没有数据就查询采集进度表
                FsUserInformationCollectionSchedule fsUserInformationCollectionSchedule = new FsUserInformationCollectionSchedule();
                fsUserInformationCollectionSchedule.setOrderCode(orderCode);
                List<FsUserInformationCollectionSchedule> fsUserInformationCollectionSchedules = scheduleMapper.selectFsUserInformationCollectionScheduleList(fsUserInformationCollectionSchedule);
                if (CollectionUtils.isEmpty(fsUserInformationCollectionSchedules)){
                    log.error("用户信息采集进度不存在,处方id:{}",rejectDTO.getPrescribeId());
                    throw new CustomException("用户信息采集进度不存在");
                }else {
                    collectionId=fsUserInformationCollectionSchedules.get(0).getCollectionId();
                }
            }else {
                collectionId=fsUserInformationCollections.get(0).getId();
            }
            // 1. 停止采集（状态变更）
            FsUserInformationCollectionSchedule paramCondition=new FsUserInformationCollectionSchedule();
            paramCondition.setRemark("医生拒访："+rejectDTO.getRemark());
            paramCondition.setCollectionId(collectionId);
            paramCondition.setOrderCode(orderCode);
            fsUserInformationCollectionService.stopCollection(paramCondition,rejectDTO.getTerminatedBy(),2);//包含退款操作
        }

    }

    @Override
    public List<FsPrescribe> getPrescribeListByUserId(FsPrescribe queryCondition) {
        queryCondition.setStatus(1);//审核通过
        List<FsPrescribe> resultList=fsPrescribeMapper.selectFsPrescribeList(queryCondition);
        if (CollectionUtils.isEmpty(resultList)){
            return Collections.emptyList();
        }
        return resultList;
    }

    @Override
    public List<FsPrescribe> selectFsPrescribeListByUserIds(List<Long> userIds) {
        List<FsPrescribe> resultList=fsPrescribeMapper.selectFsPrescribeListByUserIds(userIds);
        if (CollectionUtils.isEmpty(resultList)){
            return Collections.emptyList();
        }
        return resultList;
    }

    @Override
    public List<FsPrescribeListVO> selectWaitPrescribeList(WaitPrescribeParam waitPrescribeParam) {
        List<FsPrescribeListVO> resultList=fsPrescribeMapper.selectWaitPrescribeList(waitPrescribeParam);
        if (CollectionUtils.isEmpty(resultList)){
            return Collections.emptyList();
        }
        return resultList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmPrescribeAfterPayment(FsPrescribeParam param) {
        FsPrescribe fsPrescribe = fsPrescribeMapper.selectFsPrescribeByPrescribeId(param.getPrescribeId());
        if (fsPrescribe == null) {
            log.error("个微处方信息不存在,处方id:{}", param.getPrescribeId());
            throw new CustomException("个微处方信息不存在");
        }
        //医生操作结束时间（第一次确认处方）
//        if (fsPrescribe.getEndOperateTime() == null) {
//            if (param.getStartOperateTime() == null) {
//                throw new CustomException("操作时间参数错误，开方失败");
//            }
//            fsPrescribe.setStartOperateTime(new Date(param.getStartOperateTime()));
//            fsPrescribe.setEndOperateTime(DateUtils.getNowDate());
//            Long seconds = DateUtil.between(fsPrescribe.getStartOperateTime(), fsPrescribe.getEndOperateTime(), DateUnit.SECOND);
//            fsPrescribe.setOperateSecond(seconds);
//        }
        //处方类型
        fsPrescribe.setPrescribeType(param.getPrescribeType());
        //处方诊断
        fsPrescribe.setDiagnose(param.getDiagnose());
        //处方医嘱
        fsPrescribe.setRemark(param.getRemark());
        //医生已确认
        fsPrescribe.setDoctorConfirm(1);
        //待药师审核
        fsPrescribe.setStatus(0);
        fsPrescribeMapper.updateFsPrescribe(fsPrescribe);
        //用户信息采集医生确认
        FsUserInformationCollection collection = collectionMapper.selectFsUserInformationCollectionById(fsPrescribe.getCollectionId());
        if (collection != null) {
            FsUserInformationCollection willUpdate = new FsUserInformationCollection();
            willUpdate.setId(collection.getId());
            willUpdate.setDoctorConfirm(1);//医生已确认
            willUpdate.setPersonalCollectStatus(PostPayPrescStatusEnum.PENDING_DRUG_DOCTOR.getCode());//待药师审核
            collectionMapper.updateFsUserInformationCollection(willUpdate);
            //确认完成后删除缓存(如果有缓存)
            redisCache.deleteObject("collectionPrescribeId:" + fsPrescribe.getPrescribeId());
        }
        //医生确认后生成处方单
        PrescriptionTaskRecord record = new PrescriptionTaskRecord();
        record.setPrescribeId(param.getPrescribeId());
        record.setCreateTime(LocalDateTime.now());
        record.setExecuteStatus(0);
        record.setRetryCount(0);
        //只生成医生签名图片标识
        record.setSignFlag(1);
        prescriptionTaskRecordMapper.insert(record);

        //生成药师审核消息
        DoctorMsg msg = new DoctorMsg();
        msg.setType(2);
        msg.setDoctorId(fsPrescribe.getDrugDoctorId());
        msg.setTitle("处方审核");
        msg.setContent("处方编号："+fsPrescribe.getPrescribeCode()+"待审核");
        msg.setCreateTime(DateUtils.getNowDate());
        doctorMsgMapper.insertDoctorMsg(msg);

        //医生确认处方后立即生成处方图片
        self().createDoctorSignImg(fsPrescribe);
    }

    @Override
    public FsPrescribe selectNewestAuditedPrescribeByUserId(Long userId) {
        return fsPrescribeMapper.selectNewestAuditedPrescribeByUserId(userId);
    }

    @Override
    public FsPrescribe selectNewestAuditedPrescribeByCollectionId(Long collectionId) {
        return fsPrescribeMapper.selectNewestAuditedPrescribeByCollectionId(collectionId);
    }

    @Override
    public List<FsPrescribe> selectPrescribeListByEncryptPhone(String phone) {
        if (StringUtils.isBlank(phone)) {
            throw new CustomException("手机号不能为空");
        }
        // 手机号长度为11位时进行加密，否则直接使用原值查询
        String searchPhone = (phone.length() == 11) ? PhoneUtil.encryptPhone(phone) : phone;
        List<FsPrescribe> prescribeList = fsPrescribeMapper.selectPrescribeListByEncryptPhone(searchPhone);
        if (CollectionUtils.isEmpty(prescribeList)){
            return Collections.emptyList();
        }
        return prescribeList;
    }

}
