package com.fs.his.service.impl;

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.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
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.mapper.*;
import com.fs.his.param.*;
import com.fs.his.service.IFsDoctorService;
import com.fs.his.service.IFsPrescribeDrugService;
import com.fs.his.service.IFsPrescribeService;
import com.fs.his.service.IFsStoreOrderService;
import com.fs.his.utils.ConfigUtil;
import com.fs.his.utils.qrcode.QRCodeUtils;
import com.fs.his.vo.*;
import com.fs.im.dto.MsgCustomDTO;
import com.fs.im.dto.MsgDTO;
import com.fs.im.dto.MsgDataDTO;
import com.fs.im.dto.MsgDataFormatDTO;
import com.fs.im.service.IImService;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import com.google.zxing.WriterException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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.util.*;
import java.util.List;

/**
 * 处方Service业务层处理
 *
 * @author fs
 * @date 2023-06-13
 */
@Service
public class FsPrescribeServiceImpl implements IFsPrescribeService
{
    @Autowired
    private FsPrescribeMapper fsPrescribeMapper;
    @Autowired
    private FsPrescribeDrugMapper fsPrescribeDrugMapper;
    @Autowired
    private FsInquiryOrderMapper fsInquiryOrderMapper;
    @Autowired
    IFsDoctorService doctorService;
    @Autowired
    FsDoctorMapper doctorMapper;
    @Lazy
    @Autowired
    IFsStoreOrderService storeOrderService;
    @Autowired
    private IFsPrescribeDrugService prescribeDrugService;
    @Autowired
    IImService imService;
    @Autowired
    FsPackageMapper fsPackageMapper;
    @Autowired
    ConfigUtil configUtil;
    @Autowired
    FsExportTaskMapper fsExportTaskMapper;
    /**
     * 查询处方
     *
     * @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<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);
//            List<FsPrescribeDrug> list =new ArrayList<>();
//            for (FsPrescribeDrug fsPrescribeDrug : FsPrescribeDruglist) {
//                if (fsPrescribeDrug.getIsDrug()!=null&&fsPrescribeDrug.getIsDrug()!=0){
//                    list.add(fsPrescribeDrug);
//                }else if (fsPrescribeDrug.getIsDrug()==null){
//                    list.add(fsPrescribeDrug);
//                }
//            }
            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 Long insertFsPrescribeByPackageOrder(FsPackageOrder packageOrder) {
        FsPackage fsPackage=fsPackageMapper.selectFsPackageByPackageId(packageOrder.getPackageId());
        FsPrescribe fsPrescribe = new FsPrescribe();
        fsPrescribe.setPrescribeType(fsPackage.getProductType());
        fsPrescribe.setRecipeType(fsPackage.getRecipeType());
        fsPrescribe.setStoreId(fsPackage.getStoreId());
        fsPrescribe.setStatus(1);
        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());
        fsPrescribe.setPrescribeCode(IdUtil.getSnowflake(0, 0).nextIdStr());
        FsPackagePatientDTO patJson = JSON.parseObject(packageOrder.getPatientJson(),FsPackagePatientDTO.class);
        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 drug =doctorMapper.selectPackageFsDoctorType2Ids(fsPackage.getProductType());

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

        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("非法操作");
        }
        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());
        }
        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.ok("操作成功");

    }

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