package com.bzd.system.service;

import com.bzd.common.config.dao.DaoBase;
import com.bzd.common.config.dao.DaoSupport;
import com.bzd.common.config.dao.PageData;
import com.bzd.common.core.domain.entity.DtpDeliveryPrint;
import com.bzd.common.utils.DateUtils;
import com.bzd.common.utils.StringUtils;
import com.bzd.common.utils.uuid.IdUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.bzd.common.utils.ShiroUtils.getSysUser;


@Service
public class DTPService {
    @Autowired
    private DaoBase dao;

    @Resource(name = "daoSupport")
    private DaoSupport daoSupport;

    /**
     * 处方列表
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> findForList(final PageData pd) throws Exception {

        return (List<PageData>) daoSupport.findForList("DTPCFDJMapper.selectPrescriptionRegistration", pd);
    }
    /**
     * 处方/药品列表
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData  getLastRecipe(final PageData pd) throws Exception {
        PageData pd3= new PageData();
        PageData pdObj= (PageData) daoSupport.findForObject("DTPCFDJMapper.selectOneByPatientId", pd);
        if(StringUtils.isNotNull(pdObj)){
            pd3.put("recipe",pdObj);
            PageData pd2=new PageData();
            pd2.put("drugsLinkId",pdObj.get("drugsLinkId"));
            List<PageData> pdObjList= (List<PageData>) daoSupport.findForList("DTPCFDJMapper.selectListRecordByPrescriptionNumber", pd2);
            if(pdObjList.size()>0){
                pd3.put("recipeList", pdObjList);
            }
        }
        return pd3;
    }

    public PageData  getLastRecipeInfo(final PageData pd) throws Exception {
        PageData pd3= new PageData();
        PageData pdObj= (PageData) daoSupport.findForObject("DTPCFDJMapper.selectOneById", pd);
        if(StringUtils.isNotNull(pdObj)){
            pd3.put("recipe",pdObj);
            PageData pd2=new PageData();
            pd2.put("drugsLinkId",pdObj.get("drugsLinkId"));
            List<PageData> pdObjList= (List<PageData>) daoSupport.findForList("DTPCFDJMapper.selectListRecordByPrescriptionNumber", pd2);
            if(pdObjList.size()>0){
                pd3.put("recipeList", pdObjList);
            }
        }
        return pd3;
    }
    public PageData  getLastRecipeInfoSales(final PageData pd) throws Exception {
        PageData pd3= new PageData();
        PageData pdObj= (PageData) daoSupport.findForObject("DTPCFDJMapper.selectOneById", pd);
        if(StringUtils.isNotNull(pdObj)){
            pd3.put("recipe",pdObj);
            PageData pd2=new PageData();
            pd2.put("drugsLinkId",pdObj.get("drugsLinkId"));
            List<PageData> pdObjList= (List<PageData>) daoSupport.findForList("DTPCFDJMapper.selectListRecordByPrescriptionNumber", pd2);
            if(pdObjList.size()>0){
                pd3.put("recipeList", pdObjList);
            }
        }
        return pd3;
    }

    /**
     * 处方信息
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public Object findOne(final PageData pd) throws Exception {
        return daoSupport.findForObject("DTPMapper.selectOne", pd);
    }
    @Transactional(rollbackFor = Exception.class)
    public Integer BandingRecipe(PageData pd)throws Exception {
        return daoSupport.update("DTPMapper.BangdingRecipe", pd);
    }
    /**
     * 先销售后登记的订单数据录入
     *
     * @param pd
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public PageData saveSales(final PageData pd) throws Exception {
        PageData returnPageData = new PageData();
        Object drugList = pd.get("drugData");//获取药品信息列表
        Integer salesOrderNumber = IdUtils.get10randomNumber();//订单号 模拟生成销售单号 实际会从销售系统带过来
       // Integer prescriptionNumber = IdUtils.get10randomNumber();//订单号 模拟生成销售单号 实际会从销售系统带过来
        Integer drugsLinkId = IdUtils.get10randomNumber();//处方关联药品唯一标识

        List<PageData> addList = new ArrayList<>();
        int resultDrug=0;
        int drugQuantity=0;

        try {
            if (StringUtils.isNotNull(drugList)) {
                // 将 JSON 字符串转换为 List<Map<String, Object>>
                ObjectMapper objectMapper = new ObjectMapper();
                List<Map<String, Object>> rowsdrugList = objectMapper.readValue(drugList.toString(), List.class);
                drugQuantity = rowsdrugList.size();//处方取药数量
                // 遍历列表并调用插入数据接口
                if (rowsdrugList.size() > 0) {
                    for (Map<String, Object> lxr : rowsdrugList) {
                        PageData pageData = new PageData();
                        // 设置固定或默认值
                        pageData.put("createdTime", DateUtils.getTime());
                        // 从 lxr 获取数据并映射到数据库字段
                        pageData.put("mdmCode", lxr.get("mdmCode"));
                        pageData.put("productName", lxr.get("productName"));
                        pageData.put("genericName", lxr.get("genericName"));
                        pageData.put("specification", lxr.get("specification"));
                        pageData.put("manufacturerShortName", lxr.get("manufacturerShortName"));
                        pageData.put("administrationMethod", lxr.get("administrationMethod"));
                        pageData.put("drug_batch_number", lxr.get("drug_batch_number"));//药品批号
                        pageData.put("pharmacyName", lxr.get("pharmacyName"));
                        // 添加其他可能需要的字段（如果有的话）
                        pageData.put("medicationRoute", lxr.get("medicationRoute"));
                        pageData.put("sales", lxr.get("sales"));
                       // pageData.put("prescriptionNumber", prescriptionNumber);
                        pageData.put("drugsLinkId", drugsLinkId);
                        pageData.put("salesOrderNumber", salesOrderNumber);
                        pageData.put("prescriptionDate", DateUtils.getTime());
                        pageData.put("hospital", lxr.get("hospital"));
                        pageData.put("prescribingDoctor", lxr.get("prescribingDoctor"));
                        pageData.put("department", lxr.get("department"));
                        pageData.put("attendingPhysician", lxr.get("attendingPhysician"));
                        pageData.put("clinicalDiagnosis", lxr.get("clinicalDiagnosis"));
                        addList.add(pageData);
                        resultDrug = dao.executeBatch("DTPCFDJMapper.batchAddDrugPurchaseRecordNew", pageData);
                    }
                }
            }


            // 从表单数据填充
          // pd.put("prescriptionNumber", prescriptionNumber); // 处方单表id主键，Id 应该是某个方式生成的唯一标识符
            pd.put("salesOrderNumber", salesOrderNumber); // 处方单表id主键，Id 应该是某个方式生成的唯一标识符
            pd.put("drugsLinkId", drugsLinkId);
            pd.put("status", 4);//先销售 处方状态就是 待处方登记4
            pd.put("createdBy", getSysUser().getUserId());
            pd.put("createTime", DateUtils.getTime());
            pd.put("drugQuantity", drugQuantity);
            String gender = (String) pd.get("gender");//获取性别
            if (StringUtils.isEmpty(gender)) {
                pd.put("gender", 2);//2等于未知性别
            }
            //String age = (String) pd.get("age");//
            int result = daoSupport.save("DTPCFDJMapper.insertPrescriptionRegistration", pd);
            if(resultDrug>0 && result>0){
                returnPageData.put("code", 200);
               // returnPageData.put("prescriptionNumber", prescriptionNumber);
                returnPageData.put("drugsLinkId", drugsLinkId);
                returnPageData.put("status", 4);//先销售 处方状态就是 待处方登记4
                returnPageData.put("salesOrderNumber", salesOrderNumber);
                return returnPageData;
            }else {
                returnPageData.put("msg", "添加失败");
                returnPageData.put("code", 300);
                return returnPageData;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 处方登记 添加此接口暂时废弃 不用
     *
     * @param pd
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public PageData save(final PageData pd) throws Exception {
        pd.put("createTime", DateUtils.getTime());//处方表 处方单号时间
        String prescriptionNumber = (String) pd.get("prescriptionNumber");
        String prescriptionImg = (String) pd.get("prescriptionImg");
        String prescriptionDate = (String) pd.get("prescriptionDate");
        if (StringUtils.isEmpty(prescriptionNumber.toString())) {
            pd.put("prescriptionNumber", IdUtils.get10randomNumber());//处方表 处方单号 如果没有就自动生成
            if( StringUtils.isEmpty(prescriptionImg.toString())){
                pd.put("status",4);//待上传处方
            }
            if( StringUtils.isNotEmpty(prescriptionImg)){
                pd.put("status",6);//待绑定患者6
            }
            if( StringUtils.isEmpty(prescriptionDate)){
                pd.put("prescriptionDate", DateUtils.getTime());
            }

        }
        String isFlipItemStr = "否"; // 初始化 isFlipItemStr
        boolean isFlipItemFound = false; // 标志变量
        int Id = IdUtils.get10randomNumber();
        List<PageData> addList = new ArrayList<>();
        Object drugList = pd.get("drugList");//获取药品信息列表

        if (StringUtils.isNotNull(drugList)) {
            try {
                // 将 JSON 字符串转换为 List<Map<String, Object>>
                ObjectMapper objectMapper = new ObjectMapper();
                List<Map<String, Object>> rowsdrugList = objectMapper.readValue(drugList.toString(), List.class);
                // 遍历列表并调用插入数据接口
                if (rowsdrugList.size() > 0) {
                    for (Map<String, Object> lxr : rowsdrugList) {
                        PageData pageData = new PageData();
                        pageData.put("creator", getSysUser().getLoginName());
                        pageData.put("createTime", DateUtils.getTime());
                        pageData.put("productName", lxr.get("productName"));
                        pageData.put("genericName", lxr.get("genericName"));
                        pageData.put("prescriptionNumber", Id);//处方药品信息表d的处方单号是处方表的主键id
                        pageData.put("patientId", pd.get("patientId"));
                        pageData.put("specification", lxr.get("specification"));
                        pageData.put("usageMethod", lxr.get("usageMethod"));
                        pageData.put("quantity", lxr.get("quantity"));
                        pageData.put("frequency", lxr.get("frequency"));
                        pageData.put("wordUsage", lxr.get("wordUsage"));
                        pageData.put("medicationCycle", lxr.get("medicationCycle"));
                        pageData.put("mdmCode", lxr.get("mdmCode"));
                        pageData.put("drugCode", lxr.get("productId"));
                        pageData.put("isFlipItem", lxr.get("isFlipItem"));
                        // 检查 isFlipItem 字段的值
                        if ("是".equals(lxr.get("isFlipItem")) && !isFlipItemFound) {
                            isFlipItemStr = "是";
                            isFlipItemFound = true; // 设置标志变量
                        }
                        addList.add(pageData);
                    }
                    final HashMap<String, Object> addMap = new HashMap<String, Object>();
                    addMap.put("dataList", addList);
                    int resultDrug= dao.executeBatch("DTPMapper.batchAddPrescriptionDrug", addMap);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        pd.put("id", Id);//处方单表id主键
        pd.put("isFlipItem", isFlipItemStr);//是否包含有上翻品
        pd.put("storeId", getSysUser().getDeptId());
       int result = daoSupport.save("DTPMapper.insertRecipe", pd);
        PageData resultpageData = new PageData();
       if(result>0){
           resultpageData.put("id", Id);//处方单表id主键
           Object prescription =  daoSupport.findForObject("DTPMapper.selectOne", resultpageData);
           resultpageData.put("result", "200");
           resultpageData.put("prescription", prescription);
           return resultpageData;
       }else{
           resultpageData.put("id", Id);//处方单表id主键
           resultpageData.put("result","300");
           return resultpageData;
       }
    }


    /**
     * 药师列表
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> findRevieForList(final PageData pd) throws Exception {
        return (List<PageData>) daoSupport.findForList("reviewPharmacistsMapper.selectAllReviewPharmacists", pd);
    }
    /**
     * 药师审核前输入密码
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData ReviewCheckInputPassword(final PageData pd) throws Exception {
        PageData ob= (PageData) daoSupport.findForObject("reviewPharmacistsMapper.ReviewCheckInputPassword", pd);
        return ob;
    }
    /**
     * 药师审核处方
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData Review(final PageData pd) throws Exception {
        PageData returnPageData= new PageData();
        String reviewStatus = (String) pd.get("reviewStatus");
        System.out.println("reviewStatus:"+reviewStatus);
        int resultDrug =daoSupport.update("DTPCFDJMapper.Review", pd);
        if(resultDrug>0){
            returnPageData.put("code", 200);
            returnPageData.put("msg", "审核成功");
            return returnPageData;
        }else {
            returnPageData.put("msg", "审核失败");
            returnPageData.put("code", 300);
            return returnPageData;
        }
    }



    /**
     * 处方删除
     *
     * @param ids
     * @return
     * @throws Exception
     */
    public Integer del(List<String> ids) throws Exception {
        daoSupport.delete("DTPMapper.deleteRecipe", ids);
        return daoSupport.delete("DTPMapper.deleteRecipeReg", ids);
    }
    /**
     * 一店一目删除
     * @param ids
     */
    public Integer deleteProductList(List<String> ids) throws Exception {
        return daoSupport.delete("DTPMapper.deleteProductList", ids);
    }

    /**
     * 处方修改
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public Integer update(PageData pd) throws Exception {
        return daoSupport.delete("DTPMapper.updateRecipe", pd);
    }

    /**
     * 校验患者姓名和电话
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public boolean checkPatientNameAndPhoneUnique(PageData pd) throws Exception {

        Object obj = daoSupport.findForObject("DTPMapper.checkPatientNameAndPhoneUnique", pd);
        return StringUtils.isNull(obj);
    }

    /**
     * 校验患者姓名和身份证号
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public boolean checkPatientNameAndIdCardUnique(PageData pd) throws Exception {

        Object obj = daoSupport.findForObject("DTPMapper.checkPatientNameAndIdCardUnique", pd);
        return StringUtils.isNull(obj);
    }

    /**
     * 冷链配送列表
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> findColdForList(final PageData pd) throws Exception {
        return (List<PageData>) daoSupport.findForList("DTPMapper.DistributionOrderList", pd);
    }

    /**
     * 冷链配送登记 添加
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public Integer saveCold(final PageData pd) throws Exception {

        pd.put("orderNumber", "1113333");//订单编号
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//2024-01-01 10:00:00
        String formattedOrderTime = now.format(formatter);
        pd.put("create_time", formattedOrderTime);//订单时间
        pd.put("creationTime", formattedOrderTime);//订单创建时间
        pd.put("createdBy", "admin");//订单创建时间
        return daoSupport.save("DTPMapper.insertDistributionOrder", pd);
    }

    /**
     * 配送订单修改
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public Integer editColdOrder(PageData pd) throws Exception {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//2024-01-01 10:00:00
        String formattedOrderTime = now.format(formatter);
        pd.put("updatedTime", formattedOrderTime);//订单时间
        return daoSupport.update("DTPMapper.updateDistributionOrder", pd);
    }

    /**
     * 配送订单软删除
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public Integer softDeleteColdOrder(PageData pd) throws Exception {
        return daoSupport.delete("DTPMapper.softDeleteColdOrder", pd);
    }

    /**
     * 配送单据打印列表
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> listPrint(final PageData pd) throws Exception {

        return (List<PageData>) daoSupport.findForList("DTPMapper.listPrintPd", pd);
    }

    /**
     * 配送单据打印导出
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<DtpDeliveryPrint> listPrintReport(final PageData pd) throws Exception {
        return (List<DtpDeliveryPrint>) daoSupport.findForList("DTPMapper.listPrintEntity", pd);
    }

    /**
     * 配送单据打印 添加
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public Integer savePrint(final PageData pd) throws Exception {

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//2024-01-01 10:00:00
        String formattedOrderTime = now.format(formatter);
        pd.put("create_time", formattedOrderTime);//订单时间
        pd.put("creationTime", formattedOrderTime);//订单创建时间
        pd.put("createdBy", "admin");//订单创建人
        pd.put("businessId", "10359");//业务ID
        pd.put("status", "待打印");//打印状态

        return daoSupport.save("DTPMapper.savePrint", pd);
    }

    /**
     * 配送单据打印修改
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public Integer editPrint(PageData pd) throws Exception {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//2024-01-01 10:00:00
        String formattedOrderTime = now.format(formatter);
        pd.put("updatedTime", formattedOrderTime);//订单时间
        return daoSupport.update("DTPMapper.editPrint", pd);
    }

    /**
     * 配送单据打印软删除
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public Integer DelPrint(PageData pd) throws Exception {
        return daoSupport.delete("DTPMapper.DelPrint", pd);
    }


    /**配置信息查询模块**/
    /**
     * 一店一目标签列表
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> findstoreTagList(final PageData pd) throws Exception {
        return (List<PageData>) daoSupport.findForList("DTPMapper.StoreProductList", pd);
    }

    /**
     * DTP医院列表
     *
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> findHospitalList(final PageData pd) throws Exception {
        pd.put("storeId", getSysUser().getDeptId());
        return (List<PageData>) daoSupport.findForList("DTPMapper.HospitalList", pd);
    }

    /**
     * 处方登记 添加
     * @param pd
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public PageData saveCFDJ(final PageData pd) throws Exception {
        PageData returnPageData = new PageData();
        Object drugList = pd.get("drugData");//获取药品信息列表
        String reviewStatus= (String) pd.get("reviewStatus");//审核状态
        String reviewingName= (String) pd.get("reviewingName");//审核人
        String registerPharmacistName= (String) pd.get("registerPharmacistName");//登记药师

        String remarks= (String) pd.get("remarks");//审核备注
        Integer drugsLinkId = IdUtils.get10randomNumber();//生成处方与药品关联的编号
        Integer prescriptionNumber = IdUtils.get10randomNumber();//生成处方单号
        String patientId=null;
        String patientIdif = (String) pd.get("patientId");
        if(StringUtils.isNotEmpty(patientIdif)){
            patientId = patientIdif;
        }
        List<PageData> addList = new ArrayList<>();
        int resultDrug=0;
        int drugQuantity=0;
        try {
            if (StringUtils.isNotNull(drugList)) {
                // 将 JSON 字符串转换为 List<Map<String, Object>>
                ObjectMapper objectMapper = new ObjectMapper();
                List<Map<String, Object>> rowsdrugList = objectMapper.readValue(drugList.toString(), List.class);
                drugQuantity = rowsdrugList.size();//处方取药数量
                // 遍历列表并调用插入数据接口
                if (rowsdrugList.size() > 0) {
                    for (Map<String, Object> lxr : rowsdrugList) {
                        PageData pageData = new PageData();

                        // 设置固定或默认值
                        pageData.put("createdBy", getSysUser().getLoginName());
                        pageData.put("createdTime", DateUtils.getTime());
                        pageData.put("storeId", getSysUser().getDeptId());
                        if (StringUtils.isNotEmpty(patientId)) {
                            pageData.put("patientId", patientId);
                        }

                        // 从 lxr 获取数据并映射到数据库字段
                        pageData.put("mdmCode", lxr.get("mdmCode"));
                        pageData.put("productName", lxr.get("productName"));
                        pageData.put("genericName", lxr.get("genericName"));
                        pageData.put("specification", lxr.get("specification"));
                        pageData.put("manufacturerShortName", lxr.get("manufacturerShortName"));
                        pageData.put("administrationMethod", lxr.get("administrationMethod"));
                        pageData.put("packageQuantity", lxr.get("packageQuantity"));//处方取药数量(包装数)输入框的值
                        pageData.put("singleDoseValue", lxr.get("singleDoseValue"));//处方单次剂量数值 输入框的值
                        pageData.put("singleDoseUnit", lxr.get("singleDoseUnit"));//处方单次剂量单位
                        pageData.put("dosageFrequency", lxr.get("dosageFrequency"));//规范用药频次
                        pageData.put("dosageFrequencyDays", lxr.get("dosageFrequencyDays"));//用药频次换算使用天数 下拉带出来的 要去字典的value
                        if(lxr.get("dvalueDays")!=null){
                            pageData.put("dvalueDays", lxr.get("dvalueDays"));
                        }else {
                            pageData.put("dvalueDays", 0);
                        }

                        // 添加其他可能需要的字段（如果有的话）
                        pageData.put("medicationRoute", lxr.get("medicationRoute"));
                        //pageData.put("sales", lxr.get("sales"));
                        pageData.put("prescriptionNumber", prescriptionNumber);
                        pageData.put("drugsLinkId", drugsLinkId);
                        pageData.put("prescriptionDate", DateUtils.getTime());
                        pageData.put("hospital", lxr.get("hospital"));

                        pageData.put("prescribingDoctor", lxr.get("prescribingDoctor"));
                        pageData.put("department", lxr.get("department"));
                        pageData.put("attendingPhysician", lxr.get("attendingPhysician"));
                        pageData.put("clinicalDiagnosis", lxr.get("clinicalDiagnosis"));
                        pageData.put("registrant", lxr.get("registrant"));
                        pageData.put("registrationDate", DateUtils.getTime());
//                        pageData.put("saleDate", lxr.get("saleDate"));
//                        pageData.put("pharmacyName", lxr.get("pharmacyName"));
//                        pageData.put("updatedBy", lxr.get("updatedBy"));
//                        pageData.put("updatedTime", lxr.get("updatedTime"));
//                        pageData.put("remarks", lxr.get("remarks"));
                        addList.add(pageData);
                        resultDrug = dao.executeBatch("DTPCFDJMapper.batchAddDrugPurchaseRecordNew", pageData);
                    }
//                        final HashMap<String, Object> addMap = new HashMap<String, Object>();
//                        addMap.put("dataList", addList);
//                        resultDrug = dao.executeBatch("DTPCFDJMapper.batchAddDrugPurchaseRecord", addMap);
                }
            }

            // 从表单数据填充
            pd.put("drugsLinkId", drugsLinkId); // 处方与药品关联的唯一编码
            pd.put("prescriptionNumber", prescriptionNumber);
            pd.put("storeId", getSysUser().getDeptId());
            pd.put("storeName", getSysUser().getDeptId()); // 假设 getDeptName() 可以获取部门名称
            pd.put("createdBy", getSysUser().getUserId());
            pd.put("createTime", DateUtils.getTime());
            pd.put("status", 5);//5待订单销售
            pd.put("registrationDate", DateUtils.getTime());
            pd.put("drugQuantity", drugQuantity);

            if (StringUtils.isNull(reviewingName) && StringUtils.isEmpty(reviewStatus)){
                pd.put("reviewingName", "系统默认");
                pd.put("reviewStatus", 1);//处方审核状态:0:审核不通过;1:审核通过;2: 待审核;默认 1: "审核通过";
            }
            if(StringUtils.isEmpty(remarks)){
                pd.put("remarks", "系统审核");
            }
            if(StringUtils.isEmpty(registerPharmacistName)){
                pd.put("registerPharmacistName", getSysUser().getLoginName());
            }

            String registrant = (String) pd.get("registrant");
            if(StringUtils.isEmpty(registrant)){
                pd.put("registrant", getSysUser().getLoginName());
            }
            int result = daoSupport.save("DTPCFDJMapper.insertPrescriptionRegistration", pd);
            if(resultDrug>0 && result>0){
                returnPageData.put("code", 200);
                returnPageData.put("prescriptionNumber", prescriptionNumber);
                returnPageData.put("drugsLinkId", drugsLinkId);
                return returnPageData;
            }else {
                returnPageData.put("msg", "天添加败");
                returnPageData.put("code", 300);
                return returnPageData;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 处方登记修改更新
     * @param pd
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateCFDJ(final PageData pd) throws Exception {
        PageData pd3=new PageData();
        try {
            String reviewStatus= (String) pd.get("reviewStatus");//审核状态
            String reviewingName= (String) pd.get("reviewingName");//审核人
            String remarks= (String) pd.get("remarks");//审核备注
            String registerPharmacistName= (String) pd.get("registerPharmacistName");//登记药师
            String patientId=null;
            String patientIdif = (String) pd.get("patientId");
            if(StringUtils.isNotEmpty(patientIdif)){
                patientId = patientIdif;
            }
            pd3.put("id",pd.get("id"));
            PageData pd1= (PageData) daoSupport.findForObject("DTPCFDJMapper.selectOneById", pd3);
        String status = (String) pd.get("status");
        boolean flag = false; // 标志变量
        Integer onlyId=null;
        String prescriptionImageUrl = (String) pd.get("prescriptionImageUrl");

        if (status.equals("4")) {//4待处方登记
             onlyId = IdUtils.get10randomNumber();//如果是先销售后登记来做的修改处方信息 生成处方单号
            flag=true;//为先销售后登记
            if (StringUtils.isEmpty(prescriptionImageUrl)) {//3待确认信息
                status="2";//待上传处方
            }else {
                status="3";//待确认信息
            }

        }else{
            if (StringUtils.isEmpty(prescriptionImageUrl)) {//3待确认信息
                status="2";//待上传处方
            }else {
                status="3";//待确认信息
            }
        }
        Object drugList = pd.get("drugData");//获取药品信息列表

        List<PageData> addList = new ArrayList<>();
        int resultDrug=0;
        int drugQuantity=0;

        if (StringUtils.isNotNull(drugList)) {

                // 将 JSON 字符串转换为 List<Map<String, Object>>
                ObjectMapper objectMapper = new ObjectMapper();
                List<Map<String, Object>> rowsdrugList = objectMapper.readValue(drugList.toString(), List.class);
                drugQuantity=rowsdrugList.size();//处方取药数量
                // 遍历列表并调用插入数据接口
                if (rowsdrugList.size() > 0) {
                    dao.executeBatch("DTPCFDJMapper.batchDeleteDrugPurchaseRecord", pd);  // 直接删除 所有的药品信息然后新增
                    for (Map<String, Object> lxr : rowsdrugList) {
                        PageData pageData = new PageData();

                        // 设置固定或默认值
                        pageData.put("createdBy", getSysUser().getLoginName());
                        pageData.put("createdTime", DateUtils.getTime());
                        pageData.put("storeId", getSysUser().getDeptId());
                        if (StringUtils.isNotEmpty(patientId)) {
                            pageData.put("patientId", patientId);
                        }
                        // 从 lxr 获取数据并映射到数据库字段
                        pageData.put("mdmCode", lxr.get("mdmCode"));
                        pageData.put("productName", lxr.get("productName"));
                        pageData.put("genericName", lxr.get("genericName"));
                        pageData.put("specification", lxr.get("specification"));
                        pageData.put("manufacturerShortName", lxr.get("manufacturerShortName"));
                        pageData.put("administrationMethod", lxr.get("administrationMethod"));
                        pageData.put("packageQuantity", lxr.get("packageQuantity"));
                        pageData.put("singleDoseValue", lxr.get("singleDoseValue"));
                        pageData.put("singleDoseUnit", lxr.get("singleDoseUnit"));
                        pageData.put("dosageFrequency", lxr.get("dosageFrequency"));
                        pageData.put("dosageFrequencyDays", lxr.get("dosageFrequencyDays"));
                        if(lxr.get("dvalueDays")!=null){
                            pageData.put("dvalueDays", lxr.get("dvalueDays"));
                        }else {
                            pageData.put("dvalueDays", 0);
                        }
                        pageData.put("medicationRoute", lxr.get("medicationRoute"));

                        if(flag){
                            pageData.put("salesOrderNumber", pd.get("salesOrderNumber"));
                            pageData.put("prescriptionNumber", onlyId);
                            if(StringUtils.isNotNull(pd1)){
                                pageData.put("sales", pd1.get("saleDate"));//销售日期
                                pageData.put("pharmacyName", pd1.get("ales_storeName"));//销售门店名称
                                pageData.put("drug_batch_number", pd1.get("drug_batch_number"));//药品批号
                            }
                        }else {
                            //pageData.put("salesOrderNumber", pd.get("salesOrderNumber"));
                            pageData.put("prescriptionNumber", pd.get("prescriptionNumber"));
                        }
                        pageData.put("drugsLinkId", pd.get("drugsLinkId"));
                        pageData.put("prescriptionDate", DateUtils.getTime());
                        pageData.put("hospital", lxr.get("hospital"));
                        pageData.put("prescribingDoctor", lxr.get("prescribingDoctor"));
                        pageData.put("department", lxr.get("department"));
                        pageData.put("attendingPhysician", lxr.get("attendingPhysician"));
                        pageData.put("clinicalDiagnosis", lxr.get("clinicalDiagnosis"));
                        pageData.put("registrant", lxr.get("registrant"));
                        pageData.put("registrationDate", DateUtils.getTime());
                        addList.add(pageData);
                        dao.executeBatch("DTPCFDJMapper.batchAddDrugPurchaseRecordNew", pageData);
                    }
                }
                pd.put("storeId", getSysUser().getDeptId());
                pd.put("storeName", getSysUser().getDeptId()); // 假设 getDeptName() 可以获取部门名称
                pd.put("createdBy", getSysUser().getUserId());
                pd.put("createTime", DateUtils.getTime());
                pd.put("status",Integer.parseInt(status));
                if(flag){
                    pd.put("prescriptionNumber", onlyId);
                    pd.put("registrationDate", DateUtils.getTime());
                    if(StringUtils.isNotNull(pd1)){

                        pd.put("saleDate", pd1.get("saleDate"));//销售日期
                        pd.put("ales_storeName", pd1.get("ales_storeName"));//销售门店名称
                        pd.put("sales_storeCode", pd1.get("sales_storeCode"));//销售门店编码
                        pd.put("drug_batch_number", pd1.get("drug_batch_number"));//药品批号
                    }
                }
                pd.put("drugQuantity", drugQuantity);

            if (StringUtils.isNull(reviewingName) && StringUtils.isEmpty(reviewStatus)){
                pd.put("reviewingName", "系统默认");
                pd.put("reviewStatus", 1);//处方审核状态:0:审核不通过;1:审核通过;2: 待审核;默认 1: "审核通过";
            }
            if(StringUtils.isEmpty(remarks)){
                pd.put("remarks", "系统审核");
            }
            if(StringUtils.isEmpty(registerPharmacistName)){
                pd.put("registerPharmacistName", getSysUser().getLoginName());
            }

            // 患者信息
                if (StringUtils.isNotNull(pd.get("gender"))){
                    String gender = pd.get("gender").toString();
                    if (gender.equals("男")){
                        pd.put("gender", "0");
                    }else if(gender.equals("女")){
                        pd.put("gender", "1");
                    }else {
                        pd.put("gender", "3");
                    }
                }
            if (StringUtils.isNull(pd.get("registrant"))){
                pd.put("registrant", getSysUser().getLoginName());
            }
                return daoSupport.save("DTPCFDJMapper.updatePrescriptionRegistration", pd);


        }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取ICD所有疾病信息
     * @param pd
     * @return
     * @throws Exception
     */
    public List<PageData> searchICD11(PageData pd) throws Exception{
        if (pd==null || pd.size()==0){
            pd.put("dict_key","ICD11");
        }
        return (List<PageData>) daoSupport.findForList("TypeDateMapper.getICD11_Date", pd);
    }
    /**
     * 获取ICD疾病信息根据id
     * @param pd
     * @return
     * @throws Exception
     */
    public PageData searchICD11Object(PageData pd) throws Exception{
        return (PageData) daoSupport.findForObject("TypeDateMapper.getICD11_Date", pd);
    }
}
