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.bzd.system.service.dtp.SDtpYypzFollowUpSopService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.math.NumberUtils;
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.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

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


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

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

    @Autowired
   private SDtpYypzFollowUpSopService SDtpYypzFollowUpSopService;
    /**
     * 处方列表
     *
     * @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 List<PageData> getFollowUpInformation(final PageData pd) throws Exception {
        pd.put("storeId", getSysUser().getDeptId());
        pd.put("status", 1);
        pd.put("position", "任务跟进人");
        return (List<PageData>) daoSupport.findForList("reviewPharmacistsMapper.getFollowUpInformation", 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;


        String registrant = (String) pd.get("registrant");
        if(StringUtils.isEmpty(registrant)){
            pd.put("registrant", getSysUser().getLoginName());
        }
        try {
            if (StringUtils.isNotNull(drugList)) {
                // 定义日期时间格式化器
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                // 将 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) {
                    PageData PS = new PageData();
                    PS.put("storeId", getSysUser().getDeptId());//门店id
                    PS.put("position", "任务跟进人");//角色
                    PS.put("status", 1);//在职状态
                    PS.put("default_follow_up", 1);//默认的跟进人

                    PageData SPD_EFAULT= (PageData) daoSupport.findForObject("SDtpYypzFollowUpSopMapper.selectDefaultFollowUpByPS", PS);//查询该门店的默认的任务跟进人
                    for (Map<String, Object> lxr : rowsdrugList) {
                        PageData pageData = new PageData();
                        PageData pdPlan = 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"));//处方取药数量(包装数)输入框的值
                        drugQuantity=drugQuantity+Integer.parseInt(lxr.get("packageQuantity").toString());
                        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"));//D值用药天数
                        }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("pharmacyName", lxr.get("pharmacyName"));
//                        pageData.put("updatedBy", lxr.get("updatedBy"));
//                        pageData.put("updatedTime", lxr.get("updatedTime"));
//                        pageData.put("remarks", lxr.get("remarks"));

                       //如果药品是随访管理品 生成随访计划和任务
                        String followUpItem   = (String) lxr.get("followUpItem");//是否是随访品 1是,0否
                      if( StringUtils.isNotEmpty(followUpItem) && "是".equals(followUpItem) ){

                            PageData d_value_code = (PageData) daoSupport.findForObject("drugConfigMapper.selectDvalueCode", pageData);//查询是否是关联的患者管理品 如果有数据就是管理品
                            if(StringUtils.isNotNull(d_value_code)){
                                Number oldvalueNumber = (Number) lxr.get("dvalueDays");
                                int oldvalue = (oldvalueNumber != null) ? oldvalueNumber.intValue() : 0;
                                pageData.put("dvalueDays", oldvalue);

                                LocalDate currentDate = LocalDate.now();

                                // 使用自定义格式化器解析日期时间字符串
                                LocalDateTime purchaseDateTime = LocalDateTime.parse((String) pageData.get("registrationDate"), formatter);
                                LocalDate purchaseDate = purchaseDateTime.toLocalDate();// 将购药日期转换为LocalDate类型
                               // 计算两个日期间的天数差
                                int daysDifference = (int) ChronoUnit.DAYS.between(purchaseDate, currentDate);
                                // 根据天数差更新实际用药天数
                                int actual_value = oldvalue - daysDifference;//actual_value 实际D值用药天数
                                pageData.put("dvalueDays", oldvalue);

                                // 查询是否存在关联记录
                                PageData D3Conditions = (PageData) daoSupport.findForObject("dvalueMapper.selectLinkDValuesBy3Conditions", pageData);
                                if(StringUtils.isNotNull(D3Conditions)){
                                    // 已有关联记录，进行更新操作
                                    Number existingSumTotalNumber = (Number) D3Conditions.get("sum_total");
                                    int existingSumTotal = (existingSumTotalNumber != null) ? existingSumTotalNumber.intValue() : 0;
                                    String existingMedicationStatus = (String) D3Conditions.get("medication_status");

                                    // 新购药的天数
                                    Number new_dvalueNumber = (Number) lxr.get("dvalueDays");
                                    int new_dvalue = (new_dvalueNumber != null) ? new_dvalueNumber.intValue() : 0;
                                    int sum_total;
                                    if(existingSumTotal<=0){
                                        // 累加新的D值到sum_total
                                        //如果是之前的D值天数是负数的时候 就重新计算D值
                                         sum_total = new_dvalue;
                                    }else{
                                        // 累加新的D值到sum_total
                                         sum_total = existingSumTotal + new_dvalue;
                                    }


                                    // 根据算法计算用药状态
                                    String medication_status;
                                    if (actual_value >= 0 && new_dvalue > 0) {
                                        medication_status = "持续购药";
                                    } else if (sum_total <= -35) {
                                        medication_status = "流失";
                                    } else if (sum_total < -7 && sum_total > -35) {
                                        medication_status = "脱落";
                                    } else if (sum_total <= -7 && sum_total < 0) {
                                        medication_status = "待复购";
                                    } else if (actual_value >= 0) {
                                        medication_status = "服药中";
                                    } else {
                                        medication_status = "未知状态";
                                    }
                                    // 更新pageData中的值
                                    pageData.put("sum_total", sum_total);
                                    pageData.put("medication_status", medication_status);
                                    // 执行更新操作
                                    int up_value = dao.executeBatch("dvalueMapper.updateLinkDValueByMdmCode", pageData);
                                    System.out.println("执行更新关联数据"+up_value);
                                }else{
                                    // 无关联记录，进行插入操作
                                    int sum_total = oldvalue; // 初次保存时，sum_total等于dvalueDays
                                    String medication_status = "服药中";

                                    // 更新pageData中的值
                                    pageData.put("sumTotal", sum_total);
                                    pageData.put("medicationStatus", medication_status);
                                    String dValueName =(String) d_value_code.get("dValueName");
                                    Long dValueCode =(Long) d_value_code.get("d_value_code");
                                    pageData.put("dValueName", dValueName);
                                    pageData.put("dValueCode", dValueCode);
                                    int add_value = dao.executeBatch("dvalueMapper.insertLinkDValue", pageData);//新增D值关关联数据
                                    System.out.println("插入关联数据"+add_value);
                                }
                            }

                            PageData   pdCPB=new PageData();
                            if (StringUtils.isNotEmpty(patientId)) {
                                pdCPB.put("patientId", patientId);
                            }else {
                                returnPageData.put("msg", "添加败!,未获取患者信息");
                                returnPageData.put("code", 300);
                                return returnPageData;
                            }
                            pdCPB.put("storeId", getSysUser().getDeptId());//门店id
                            pdCPB.put("mdmCode", lxr.get("mdmCode"));//'药品编码'
                            pdCPB.put("productCode", lxr.get("mdmCode"));//'药品编码' s_dtp_review_pharmacists


                            List<PageData> SOPList= (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectSOPTemplateByProductCode", pdCPB);//通过药品查询模版信息
                           if(SOPList.size()>0){
                            //说明是配置过的药品，需要生成计划和任务
                               List<PageData> PlanTemplateList = new ArrayList<>();
                               List<PageData> PlanList = new ArrayList<>();
                               List<PageData> TaskNodeList = new ArrayList<>();
                               List<PageData> TaskList = new ArrayList<>();
                             for (int j = 0; j < SOPList.size(); j++) {
                                  PageData template = new PageData();
                                  Integer planId = null;
                                  //生成计划
                                  pdCPB.put("productName", lxr.get("productName"));//'药品名称'
                                  pdCPB.put("specification", lxr.get("specification"));
                                  pdCPB.put("storeId", getSysUser().getDeptId().toString());
                                  pdCPB.put("drugsLinkId", drugsLinkId);
                                  pdCPB.put("storeName", getSysUser().getDept().getDeptName());
                                  pdCPB.put("templateId", SOPList.get(j).get("templateId"));//'模版ID'  实际是获取模板ID
                                  pdCPB.put("nodeId", SOPList.get(j).get("templateId"));//'模版ID'  实际是获取模板ID
                                  pdCPB.put("templeName", SOPList.get(j).get("templateName"));//templateName名称
                                  String templateId = (String)  SOPList.get(j).get("templateId");
                                  String productCode  = (String)  SOPList.get(j).get("productCode");
                                  pdCPB.put("planName", SOPList.get(j).get("templateName")+"计划");//'计划名称' 默认用药品作为名称
                                  pdCPB.put("businessBelonging", SOPList.get(j).get("businessBelonging"));//'业务归属
                                  if(StringUtils.isNotNull(SPD_EFAULT)){
                                      pdCPB.put("follow_up_person", SPD_EFAULT.get("pharmacistName"));//'随访跟进人'
                                      pdCPB.put("follow_up_person_id", SPD_EFAULT.get("id"));//'随访跟进人id'
                                  }

                                  pdCPB.put("createdBy", "系统创建");//'创建人'
                                  pdCPB.put("createdTime", DateUtils.getTime());//'创建时间'
                                  pdCPB.put("updatedBy", getSysUser().getLoginName());//'创建人'
                                  pdCPB.put("updatedTime", DateUtils.getTime());//'创建时间'

                                  //先查询该患者购买在这个药品是否已经有计划 mdmCode patientId businessBelonging
                                  PageData plan = (PageData) daoSupport.findForObject("followPlanMapper.selectPlanByCPB", pdCPB);
                                  if (StringUtils.isNotNull(plan)) {
                                      pdCPB.put("planId", plan.get("planId"));
                                      // 获取 planId 并进行类型转换
                                      Object planIdObj = plan.get("planId");
                                       if (planIdObj instanceof String) {
                                          // 使用 NumberUtils 进行安全转换
                                          planId = NumberUtils.toInt((String) planIdObj);
                                        } else if (planIdObj instanceof Integer) {
                                          planId = (Integer) planIdObj;
                                         } else if (planIdObj instanceof Long) {
                                          Long longPlanId = (Long) planIdObj;
                                          if (longPlanId <= Integer.MAX_VALUE && longPlanId >= Integer.MIN_VALUE) {
                                              planId = longPlanId.intValue();
                                          } else {
                                              throw new IllegalArgumentException("planId exceeds Integer range: " + longPlanId);
                                            }
                                         } else {
                                          throw new IllegalArgumentException("Unsupported type for planId: " + planIdObj.getClass());
                                         }
                                      pdCPB.put("businessBelonging", plan.get("businessBelonging"));//'业务归属:常规随访，脱落召回'
                                    } else {
                                      //生成计划ID
                                      planId = (Integer) IdUtils.get10randomNumber();
                                      //生成任务ID 一个药品 可能一次有两个任务 脱落召回 和常规随访
                                      pdCPB.put("planId", planId);
                                      //生成计划
                                      System.out.println("执行mapper方法:getTemplateNodeByMBS,return:" + template);
                                      pdCPB.put("status", 2);//'计划状态: 0关闭 1开启/进行中，2默认：2已创建待开启'
                                      int FollowPlan = dao.executeBatch("followPlanMapper.insertFollowPlan", pdCPB);

                                      System.out.println("FollowPlan.size()=" + FollowPlan);
                                      pdCPB.put("status", 2);//第二次赋值为 模版 状态: 0已创建 1启用，2禁用 默认为已创建0 这里的查询状态 取的反 不等于2的状态
                                      template = (PageData) daoSupport.findForObject("SDtpYypzFollowUpSopMapper.getTemplateNodeByMBS", pdCPB);//获取模版和药 查询条件mdmCode businessBelonging storeId
                                      //生成定时计划任务
                                      if (StringUtils.isNotNull(template)) {
                                          pdCPB.put("planId", planId);
                                          pdCPB.put("PlanProductCode", template.get("productCode"));
                                          pdCPB.put("PlanTemplateId", template.get("templateId"));
                                          PlanList.add(pdCPB);
                                      }

                                  }
                                  pdCPB.put("templateId", templateId);//'模版ID'
                                  List<PageData> SOPNodeList= (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectSOPNodeListByTemplateId", pdCPB);//通过模版id查询节点信息
                                 if(SOPNodeList.size()>0){

                                 for (PageData sopNode : SOPNodeList) {
                                 int i=0;
                                  //生成任务ID 一个药品 可能一次有两个任务 脱落召回 和常规随访
                                  Integer taskId = (Integer) IdUtils.get10randomNumber();
                                  //生成任务数据
                                  i++;
                                  pdCPB.put("mdmCode", lxr.get("mdmCode"));//'药品编码'
                                  pdCPB.put("taskName", lxr.get("productName") + "-第" + i + "次任务");//'任务名称'
                                  pdCPB.put("taskTheme", sopNode.get("businessBelonging"));//'任务主题'
                                  pdCPB.put("templateName", sopNode.get("templateName"));//模版名称
                                  pdCPB.put("planId", planId);//'计划ID'
                                  pdCPB.put("taskId", taskId);//'任务ID'
                                  pdCPB.put("patientId", patientId);//'患者id'
                                  pdCPB.put("patientName", pd.get("patientName"));//'患者姓名'
                                  pdCPB.put("gender", pd.get("gender"));//'性别:0男,1女,2未知'
                                  pdCPB.put("age", pd.get("age"));//'年龄'
                                  //pdCPB.put("followUpSummary", "无");//'随访小结'
                                  //pdCPB.put("followUpSummaryid", lxr.get("followUpSummaryid"));//'随访小结id'
                                  pdCPB.put("disease", pd.get("prescriptionDiagnosis"));//'疾病' 先用处方诊断字段代替
                                  pdCPB.put("storeName", getSysUser().getDeptId());//'门店'
                                  pdCPB.put("genericName", lxr.get("genericName"));//'药品通用名'
                                  pdCPB.put("productName", lxr.get("productName"));//'商品名'
                                  //pdCPB.put("taskFollower", "周敏");//'任务跟进人'
                                  if(StringUtils.isNotNull(SPD_EFAULT)){
                                      pdCPB.put("taskFollower", SPD_EFAULT.get("pharmacistName"));//'随访跟进人'
                                  }
                                  pdCPB.put("nutrition_evaluation_id", "11111111");//'营养测评id'
                                  pdCPB.put("medication_record_id", "22222222");//'用药记录id'
                                  pdCPB.put("taskStatus", "未下发");//任务状态：\r\n,0待执行,已下发，\r\n1已完成，\r\n2未完成，\r\n3已下发，\r\n4已取消
                                  pdCPB.put("operator", pd.get("registrant"));//'操作人'
                                  pdCPB.put("createdAt", DateUtils.getTime());
                                  pdCPB.put("updatedAt", DateUtils.getTime());
                                  pdCPB.put("storeId", getSysUser().getDeptId().toString());//返回的 Long类型 怎么转换成 Integer类型
                                  pdCPB.put("nodeId", sopNode.get("id"));
                                  pdCPB.put("sopNode", sopNode);

                                  sopNode.put("mdmCode", lxr.get("mdmCode"));//'药品编码'
                                  sopNode.put("taskName", lxr.get("productName") + "-第" + i + "次任务");//'任务名称'
                                  sopNode.put("taskTheme", sopNode.get("businessBelonging"));//'任务主题'
                                  sopNode.put("storeId", getSysUser().getDeptId().toString());
                                  sopNode.put("taskId", taskId);
                                  sopNode.put("planId", planId);
                                  sopNode.put("patientId", patientId);//'患者id' s_gxhpz_follow_task_node
                                  sopNode.put("productCode", productCode);
                                  sopNode.put("templateId", templateId);
                                  sopNode.put("createTime", DateUtils.getTime());

                                  //预存任务
                                  int FollowTask = dao.executeBatch("followTaskMapper.insertFollowTask", pdCPB);//预存数据任务
                                  System.out.println("insertFollowTask="+FollowTask);
                                  int TaskNod = dao.executeBatch("SDtpYypzFollowUpSopMapper.insertFollowTaskNode", sopNode);//把对应任务的节点与Task关联存起来
                                  System.out.println("insertFollowTaskNode="+TaskNod);
                                          //生成定时任务任务
                                          TaskList.add(sopNode);
                              }
                            }

                          }
                               SDtpYypzFollowUpSopService.createTrigger(PlanList,TaskList);//生成定时任务
                         }

                      }
                        addList.add(pageData);
                        resultDrug = dao.executeBatch("DTPCFDJMapper.batchAddDrugPurchaseRecordNew", pageData);
                        System.out.println("resultDrug.size()="+resultDrug);
                    }

                }
            }

            // 从表单数据填充
            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());
            }

            int result = daoSupport.save("DTPCFDJMapper.insertPrescriptionRegistration", pd);
            System.out.println("result.size()="+result);
            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 (StringUtils.isNull(pd.get("registrant"))){
            pd.put("registrant", getSysUser().getLoginName());
        }
        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;
            // 定义日期时间格式化器
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        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);  // 直接删除 所有的药品信息然后新增
                    PageData PS = new PageData();
                    PS.put("storeId", getSysUser().getDeptId());//门店id
                    PS.put("position", "任务跟进人");//角色
                    PS.put("status", 1);//在职状态
                    PS.put("default_follow_up", 1);//默认的跟进人

                    PageData SPD_EFAULT= (PageData) daoSupport.findForObject("SDtpYypzFollowUpSopMapper.selectDefaultFollowUpByPS", PS);//查询该门店的默认的任务跟进人
                    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"));
                        drugQuantity=drugQuantity+Integer.parseInt(lxr.get("packageQuantity").toString());
                        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", pd.get("registrant"));
                        pageData.put("registrationDate", DateUtils.getTime());
                        addList.add(pageData);

                        //如果药品是随访管理品 生成随访计划和任务
                       // String followUpItem   = (String) lxr.get("followUpItem");//是否是随访品 1是,0否
                        PageData MdmCode= (PageData) daoSupport.findForObject("DTPCFDJMapper.isfollowUpItemByMdmCode", pageData);
                        if(StringUtils.isNotNull(MdmCode)){
                            int follow_up_item = (int) MdmCode.get("follow_up_item");//随访品 //=1说明是随访品 0不是
                        if(follow_up_item==1){


                            PageData d_value_code = (PageData) daoSupport.findForObject("drugConfigMapper.selectDvalueCode", pageData);//查询是否是关联的患者管理品 如果有数据就是管理品
                            if(StringUtils.isNotNull(d_value_code)){
                                Number oldvalueNumber = (Number) lxr.get("dvalueDays");
                                int oldvalue = (oldvalueNumber != null) ? oldvalueNumber.intValue() : 0;
                                pageData.put("dvalueDays", oldvalue);
                                LocalDate currentDate = LocalDate.now();
                                // 使用自定义格式化器解析日期时间字符串
                                LocalDateTime purchaseDateTime = LocalDateTime.parse((String) pageData.get("registrationDate"), formatter);
                                LocalDate purchaseDate = purchaseDateTime.toLocalDate();

                                // 计算两个日期间的天数差
                                int daysDifference = (int) ChronoUnit.DAYS.between(purchaseDate, currentDate);
                                // 根据天数差更新实际用药天数
                                int actual_value = oldvalue - daysDifference;//actual_value 实际D值用药天数
                                pageData.put("dvalueDays", oldvalue);

                                // 查询是否存在关联记录
                                PageData D3Conditions = (PageData) daoSupport.findForObject("dvalueMapper.selectLinkDValuesBy3Conditions", pageData);
                                if(StringUtils.isNotNull(D3Conditions)){
                                    // 已有关联记录，进行更新操作
                                    Number existingSumTotalNumber = (Number) D3Conditions.get("sum_total");
                                    int existingSumTotal = (existingSumTotalNumber != null) ? existingSumTotalNumber.intValue() : 0;
                                    String existingMedicationStatus = (String) D3Conditions.get("medication_status");

                                    // 新购药的天数
                                    Number new_dvalueNumber = (Number) lxr.get("dvalueDays");
                                    int new_dvalue = (new_dvalueNumber != null) ? new_dvalueNumber.intValue() : 0;
                                    int sum_total;
                                    if(existingSumTotal<=0){
                                        // 累加新的D值到sum_total
                                        //如果是之前的D值天数是负数的时候 就重新计算D值
                                        sum_total = new_dvalue;
                                    }else{
                                        // 累加新的D值到sum_total
                                        sum_total = existingSumTotal + new_dvalue;
                                    }
                                    // 根据算法计算用药状态
                                    String medication_status;
                                    if (actual_value >= 0 && new_dvalue > 0) {
                                        medication_status = "持续购药";
                                    } else if (sum_total <= -35) {
                                        medication_status = "流失";
                                    } else if (sum_total < -7 && sum_total > -35) {
                                        medication_status = "脱落";
                                    } else if (sum_total <= -7 && sum_total < 0) {
                                        medication_status = "待复购";
                                    } else if (actual_value >= 0) {
                                        medication_status = "服药中";
                                    } else {
                                        medication_status = "未知状态";
                                    }
                                    // 更新pageData中的值
                                    pageData.put("sum_total", sum_total);
                                    pageData.put("medication_status", medication_status);
                                    // 执行更新操作
                                    int up_value = dao.executeBatch("dvalueMapper.updateLinkDValueByMdmCode", pageData);
                                    System.out.println("执行更新关联数据"+up_value);
                                }else{
                                    // 无关联记录，进行插入操作
                                    int sum_total = oldvalue; // 初次保存时，sum_total等于dvalueDays
                                    String medication_status = "服药中";

                                    // 更新pageData中的值
                                    pageData.put("sumTotal", sum_total);
                                    pageData.put("medicationStatus", medication_status);
                                    String dValueName =(String) d_value_code.get("dValueName");
                                    Long dValueCode =(Long) d_value_code.get("d_value_code");
                                    pageData.put("dValueName", dValueName);
                                    pageData.put("dValueCode", dValueCode);
                                    int add_value = dao.executeBatch("dvalueMapper.insertLinkDValue", pageData);//新增D值关关联数据
                                    System.out.println("插入关联数据"+add_value);
                                }
                            }


                            //生成计划ID
                            Integer planId =  IdUtils.get10randomNumber();
                            PageData   pdCPB=new PageData();
                            if (StringUtils.isNotEmpty(patientId)) {
                                pdCPB.put("patientId", patientId);
                            }else {
                                return -1;
                            }
                            pdCPB.put("storeId", getSysUser().getDeptId().toString());//门店id
                            pdCPB.put("mdmCode", lxr.get("mdmCode"));//'药品编码'
                            pdCPB.put("productCode", lxr.get("productCode"));//'药品编码'
                            List<PageData> SOPList= (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectSOPTemplateByProductCode", pdCPB);//通过药品查询模版信息

                                if(SOPList.size()>0){ //说明是配置过的药品，需要生成计划和任务
                                    List<PageData> PlanTemplateList = new ArrayList<>();
                                    List<PageData> PlanList = new ArrayList<>();
                                    List<PageData> TaskNodeList = new ArrayList<>();
                                    List<PageData> TaskList = new ArrayList<>();
                                    for (int j = 0; j < SOPList.size(); j++) {

                                        pdCPB.put("productName", lxr.get("productName"));//'药品名称'
                                        pdCPB.put("specification", lxr.get("specification"));
                                        pdCPB.put("storeId", getSysUser().getDeptId().toString());
                                        pdCPB.put("storeName", getSysUser().getDept().getDeptName());
                                        pdCPB.put("nodeId", SOPList.get(j).get("templateId"));//'模版ID'  实际是获取模板ID
                                        pdCPB.put("templeName", SOPList.get(j).get("templateName"));//templateName名称

                                        String drugsLinkId= (String) pd.get("drugsLinkId");
                                        String businessBelonging = (String) SOPList.get(j).get("businessBelonging");//业务归属
                                        String productCode = (String) SOPList.get(j).get("productCode");//药品编码
                                        String templateId = (String) SOPList.get(j).get("templateId");//模版id
                                       if(StringUtils.isNotEmpty(drugsLinkId)){
                                           pdCPB.put("drugsLinkId", drugsLinkId);
                                           PageData LinkPlanAndTask= (PageData) daoSupport.findForObject("followPlanMapper.selectPlanByDrugsLinkId", pdCPB);//查询当前 创建过计划和任务
                                           if(StringUtils.isNotNull(LinkPlanAndTask)){//如果有数据 说明创建过计划和任务 需要删除停掉自之前的然后重新生成计划和任务
                                               PageData   pddel=new PageData();
                                               pddel.put("drugsLinkId", drugsLinkId);
                                            int plan= daoSupport.delete("followPlanMapper.deletePlanByDrugsLinkId", pddel);
                                            int task=  daoSupport.delete("followTaskMapper.deleteTaskByDrugsLinkId", pddel);
                                               //还要删除job表的数据 根据 planId 和 taskId 删除
                                               pddel.put("planId", LinkPlanAndTask.get("planId"));
                                               pddel.put("taskId", LinkPlanAndTask.get("taskId"));
                                            int job=   daoSupport.delete("followTaskMapper.deleteSysJobByPlanId", pddel);

                                           }

                                       }

                                        PageData template=new PageData();
                                        //生成计划
                                        pdCPB.put("businessBelonging", businessBelonging);//'业务属性'
                                        //先查询该患者购买在这个药品是否已经有计划 mdmCode patientId businessBelonging
                                        PageData plan= (PageData) daoSupport.findForObject("followPlanMapper.selectPlanByCPB", pdCPB);
                                        if(StringUtils.isNotNull(plan)){
                                            pdCPB.put("planId", plan.get("planId"));
                                            // 获取 planId 并进行类型转换
                                            Object planIdObj = plan.get("planId");
                                            if (planIdObj instanceof String) {
                                                // 使用 NumberUtils 进行安全转换
                                                planId = NumberUtils.toInt((String) planIdObj);
                                            } else if (planIdObj instanceof Integer) {
                                                planId = (Integer) planIdObj;
                                            } else if (planIdObj instanceof Long) {
                                                Long longPlanId = (Long) planIdObj;
                                                if (longPlanId <= Integer.MAX_VALUE && longPlanId >= Integer.MIN_VALUE) {
                                                    planId = longPlanId.intValue();
                                                } else {
                                                    throw new IllegalArgumentException("planId exceeds Integer range: " + longPlanId);
                                                }
                                            } else {
                                                throw new IllegalArgumentException("Unsupported type for planId: " + planIdObj.getClass());
                                            }
                                            pdCPB.put("businessBelonging", plan.get("businessBelonging"));//'业务归属:常规随访，脱落召回'
                                        }else {
                                            //生成计划ID
                                            planId = (Integer) IdUtils.get10randomNumber();
                                            //生成任务ID 一个药品 可能一次有两个任务 脱落召回 和常规随访
                                            pdCPB.put("planId", planId);
                                            pdCPB.put("planName", SOPList.get(j).get("templateName")+"计划");//'计划名称' 默认用药品作为名称
                                            if(StringUtils.isNotNull(SPD_EFAULT)){
                                                pdCPB.put("follow_up_person", SPD_EFAULT.get("pharmacistName"));//'随访跟进人'
                                                pdCPB.put("follow_up_person_id", SPD_EFAULT.get("id"));//'随访跟进人id'
                                            }
                                            //生成计划
                                            System.out.println("执行mapper方法:getTemplateNodeByMBS,return:"+template);
                                            pdCPB.put("status", 2);//'计划状态: 0关闭 1开启/进行中，2默认：2已创建待开启'
                                            int FollowPlan = dao.executeBatch("followPlanMapper.insertFollowPlan", pdCPB);
                                            System.out.println("FollowPlan.size()="+FollowPlan);
                                            pdCPB.put("status", 2);//第二次赋值为 模版 状态: 0已创建 1启用，2禁用 默认为已创建0 这里的查询状态 取的反 不等于2的状态
                                            template= (PageData) daoSupport.findForObject("SDtpYypzFollowUpSopMapper.getTemplateNodeByMBS", pdCPB);//获取模版和药 查询条件mdmCode businessBelonging storeId
                                            //生成定时计划任务
                                            if(StringUtils.isNotNull(template)){
                                                pdCPB.put("createdTime", DateUtils.getTime());//计划生成时间
                                                pdCPB.put("planId", planId);//productCode templateId
                                                pdCPB.put("PlanProductCode", template.get("productCode"));
                                                pdCPB.put("PlanTemplateId", template.get("templateId"));
                                                PlanList.add(pdCPB);
                                            }
                                        }
                                        pdCPB.put("templateId", templateId);//'模版ID'
                                        pdCPB.put("createdTime", DateUtils.getTime());//计划生成时间
                                        List<PageData> SOPNodeList= (List<PageData>) daoSupport.findForList("SDtpYypzFollowUpSopMapper.selectSOPNodeListByTemplateId", pdCPB);//通过模版id查询节点信息
                                        if(SOPNodeList.size()>0){
                                            int i=0;
                                            for (PageData sopNode : SOPNodeList) {
                                                //生成任务数据
                                                //生成任务ID 一个药品 可能一次有两个任务 脱落召回 和常规随访
                                                Integer taskId =(Integer)  IdUtils.get10randomNumber();
                                                //生成任务数据+
                                                i++;
                                                pdCPB.put("mdmCode", lxr.get("mdmCode"));//'药品编码'
                                                pdCPB.put("taskName", lxr.get("productName")+"-第"+i+"次任务");//'任务名称'
                                                pdCPB.put("taskTheme", sopNode.get("businessBelonging"));//'任务主题'
                                                pdCPB.put("templeName", sopNode.get("templateName"));//'任务主题'
                                                pdCPB.put("taskId", taskId);//'任务ID'
                                                pdCPB.put("patientId", patientId);//'患者id'
                                                pdCPB.put("patientName", pd.get("patientName"));//'患者姓名'
                                                pdCPB.put("gender", pd.get("gender"));//'性别:0男,1女,2未知'
                                                pdCPB.put("age", pd.get("age"));//'年龄'
                                                //pdCPB.put("followUpSummary", "无");//'随访小结'
                                                //pdCPB.put("followUpSummaryid", lxr.get("followUpSummaryid"));//'随访小结id'
                                                pdCPB.put("disease", pd.get("prescriptionDiagnosis"));//'疾病' 先用处方诊断字段代替
                                                pdCPB.put("storeName", getSysUser().getDeptId());//'门店'
                                                pdCPB.put("genericName", lxr.get("genericName"));//'药品通用名'
                                                pdCPB.put("productName", lxr.get("productName"));//'商品名'
                                                //pdCPB.put("taskFollower", "周敏");//'任务跟进人'
                                                if(StringUtils.isNotNull(SPD_EFAULT)){
                                                    pdCPB.put("taskFollower", SPD_EFAULT.get("pharmacistName"));//'随访跟进人'
                                                }
                                                pdCPB.put("nutrition_evaluation_id", "11111111");//'营养测评id'
                                                pdCPB.put("medication_record_id", "22222222");//'用药记录id'
                                                pdCPB.put("taskStatus", "未下发");//任务状态：\r\n,0待执行,已下发，\r\n1已完成，\r\n2未完成，\r\n3已下发，\r\n4已取消
                                                pdCPB.put("operator", pd.get("registrant"));//'操作人'
                                                pdCPB.put("createdAt", DateUtils.getTime());
                                                pdCPB.put("updatedAt", DateUtils.getTime());
                                                pdCPB.put("storeId", getSysUser().getDeptId().toString());
                                                pdCPB.put("nodeId", sopNode.get("id"));
                                                pdCPB.put("sopNode", sopNode);
                                                sopNode.put("mdmCode", lxr.get("mdmCode"));//'药品编码'
                                                sopNode.put("taskName", lxr.get("productName") + "-第" + i + "次任务");//'任务名称'
                                                sopNode.put("taskTheme", sopNode.get("businessBelonging"));//'任务主题'
                                                sopNode.put("storeId", getSysUser().getDeptId().toString());
                                                sopNode.put("taskId", taskId);
                                                sopNode.put("planId", planId);
                                                sopNode.put("patientId", patientId);//'患者id' s_gxhpz_follow_task_node
                                                sopNode.put("productCode", productCode);
                                                sopNode.put("templateId", templateId);
                                                sopNode.put("createTime", DateUtils.getTime());
                                                //生成任务
                                                int FollowTask = dao.executeBatch("followTaskMapper.insertFollowTask", pdCPB);//预存数据任务
                                                System.out.println("insertFollowTask="+FollowTask);
                                                int TaskNod = dao.executeBatch("SDtpYypzFollowUpSopMapper.insertFollowTaskNode", sopNode);//把对应任务的节点与Task关联存起来
                                                System.out.println("insertFollowTaskNode="+TaskNod);
                                                //生成定时任务任务
                                               // SDtpYypzFollowUpSopService.triggerTask(pdCPB,sopNode);//生成定时任务
                                                TaskList.add(sopNode);
                                            }
                                        }

                                    }
                                     //生成定时任务任务
                                    SDtpYypzFollowUpSopService.createTrigger(PlanList,TaskList);//生成定时任务
                                }

                        }
                        }
                        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 {
                                if (gender.equals("0")){
                                    pd.put("gender", "0");
                                }else if(gender.equals("1")){
                                    pd.put("gender", "1");
                                }else {
                                    pd.put("gender", "3");
                                }
                            }

                        }

                        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);
    }
    public Integer updateFollowUp(PageData pd)throws Exception{
                pd.put("updateTime",DateUtils.getTime());
        return daoSupport.update("PharmaceuticalServiceMapper.updateArchiveRecord",pd);
    }

    public Integer updatePharmacistsByStoreId(PageData pd)throws Exception{
       String id= (String) pd.get("id");//新默认跟进人id 设置他为默认人
       String lzid= (String) pd.get("lzid");//旧默认跟进人id 取消他为默认人
        PageData pd1=new PageData();
        PageData pd2=new PageData();
        int a=0;
        int b=0;
       if(StringUtils.isNotEmpty(id)){
           pd1.put("id",id);
           pd1.put("storeId",getSysUser().getDeptId());
           pd1.put("default_follow_up",1);//是
           pd1.put("updateTime",DateUtils.getTime());
             a= daoSupport.update("reviewPharmacistsMapper.updatePharmacistsById",pd1);
       }
        if(StringUtils.isNotEmpty(lzid)){
            pd2.put("id",lzid);
            pd2.put("storeId",getSysUser().getDeptId());
            pd2.put("default_follow_up",0);//否
            pd2.put("updateTime",DateUtils.getTime());
             b= daoSupport.update("reviewPharmacistsMapper.updatePharmacistsById",pd1);

        }
        System.out.println("新默认跟人更新结果=====>a:"+a+"b:"+b);
        if(a >0 && b >0){
            return 1;
        }else{
            return 0;
        }

    }

}
