package com.fs.his.service.impl;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fs.common.BeanCopyUtils;
import com.fs.common.annotation.Log;
import com.fs.common.utils.DateUtils;
import com.fs.his.config.FsSysConfig;
import com.fs.his.domain.*;
import com.fs.his.dto.FsPrescribeUsageDTO;
import com.fs.his.dto.FsStoreOrderItemDTO;
import com.fs.his.mapper.*;
import com.fs.his.param.FsStoreOrderParam;
import com.fs.his.param.FsSubOrderDrugListParam;
import com.fs.his.param.FsSubOrderParam;
import com.fs.his.utils.ConfigUtil;
import com.fs.his.vo.FsStoreProductAttrVO;
import com.fs.his.vo.FsStoreSubOrderListVO;
import com.fs.his.vo.FsStoreSubOrderVO;
import com.fs.his.vo.FsSubOrderResultVO;
import com.qcloud.cos.transfer.Copy;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.his.service.IFsStoreSubOrderService;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/**
 * 订单Service业务层处理
 *
 * @author fs
 * @date 2024-05-09
 */
@Service
public class FsStoreSubOrderServiceImpl implements IFsStoreSubOrderService
{
    @Autowired
    private FsStoreSubOrderMapper fsStoreSubOrderMapper;
    @Autowired
    private FsStoreOrderMapper fsStoreOrderMapper;
    @Autowired
    private FsPrescribeMapper fsPrescribeMapper;
    @Autowired
    private FsPrescribeDrugMapper fsPrescribeDrugMapper;
    @Autowired
    private FsDoctorMapper fsDoctorMapper;
    @Autowired
    FsPatientMapper fsPatientMapper;
    @Autowired
    FsPackageOrderMapper fsPackageOrderMapper;
    @Autowired
    FsStoreMapper fsStoreMapper;
    @Autowired
    FsStoreProductMapper fsStoreProductMapper;
    @Autowired
    ConfigUtil configUtil;
    org.slf4j.Logger logger= LoggerFactory.getLogger(getClass());
    /**
     * 查询订单
     *
     * @param subOrderId 订单主键
     * @return 订单
     */
    @Override
    public FsStoreSubOrder selectFsStoreSubOrderBySubOrderId(Long subOrderId)
    {
        return fsStoreSubOrderMapper.selectFsStoreSubOrderBySubOrderId(subOrderId);
    }


    public FsStoreSubOrderVO selectFsStoreSubOrderVOBySubOrderId(Long subOrderId)
    {
        return fsStoreSubOrderMapper.selectFsStoreSubOrderVOBySubOrderId(subOrderId);
    }
    /**
     * 查询订单列表
     *
     * @param fsStoreSubOrder 订单
     * @return 订单
     */
    @Override
    public List<FsStoreSubOrderListVO> selectFsStoreSubOrderList(FsStoreOrderParam fsStoreSubOrder)
    {
        return fsStoreSubOrderMapper.selectFsStoreOrderListVO(fsStoreSubOrder);
    }

    /**
     * 新增订单
     *
     * @param fsStoreSubOrder 订单
     * @return 结果
     */
    @Override
    public int insertFsStoreSubOrder(FsStoreSubOrder fsStoreSubOrder)
    {
        fsStoreSubOrder.setCreateTime(DateUtils.getNowDate());
        return fsStoreSubOrderMapper.insertFsStoreSubOrder(fsStoreSubOrder);
    }

    /**
     * 修改订单
     *
     * @param fsStoreSubOrder 订单
     * @return 结果
     */
    @Override
    public int updateFsStoreSubOrder(FsStoreSubOrder fsStoreSubOrder)
    {
        fsStoreSubOrder.setUpdateTime(DateUtils.getNowDate());
        return fsStoreSubOrderMapper.updateFsStoreSubOrder(fsStoreSubOrder);
    }

    /**
     * 批量删除订单
     *
     * @param subOrderIds 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteFsStoreSubOrderBySubOrderIds(String[] subOrderIds)
    {
        return fsStoreSubOrderMapper.deleteFsStoreSubOrderBySubOrderIds(subOrderIds);
    }

    /**
     * 删除订单信息
     *
     * @param subOrderId 订单主键
     * @return 结果
     */
    @Override
    public int deleteFsStoreSubOrderBySubOrderId(String subOrderId)
    {
        return fsStoreSubOrderMapper.deleteFsStoreSubOrderBySubOrderId(subOrderId);
    }

    @Override
    public void insertFsStoreSubOrderByStoreOrder(Long orderId) {
        FsStoreOrder fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderByOrderId(orderId);
        if (fsStoreOrder!=null&&fsStoreOrder.getPrescribeId()!=null){
            FsPrescribe  fsPrescribe = fsPrescribeMapper.selectFsPrescribeByPrescribeId(fsStoreOrder.getPrescribeId());
            logger.info("拆分处方："+fsPrescribe);
            if (fsPrescribe!=null){
                FsPrescribeDrug q = new FsPrescribeDrug();
                q.setPrescribeId(fsStoreOrder.getPrescribeId());
                List<FsPrescribeDrug> drugs = fsPrescribeDrugMapper.selectFsPrescribeDrugList(q);
                FsPatient fsPatient=null;
                if (fsPrescribe.getPatientId()!=null){
                    fsPatient = fsPatientMapper.selectFsPatientByPatientId(fsPrescribe.getPatientId());
                }else {
                    FsPackageOrder fsPackageOrder = fsPackageOrderMapper.selectFsPackageOrderByOrderId(fsStoreOrder.getPackageOrderId());
                    if (fsPackageOrder!=null&&fsPackageOrder.getPatientJson()!=null){
                        fsPatient = JSON.parseObject(fsPackageOrder.getPatientJson(), FsPatient.class);
                    }
                }
                //不生成条件判断
                if (fsPatient==null){
                    //没有病人信息不生成
                    return;
                }
                if (!fsPatient.getPatientName().matches("[\\u4E00-\\u9FA5]+")){
                    return;
                }

                if (fsStoreOrder.getPackageName()!=null&&fsStoreOrder.getPackageName()!=""){
                    int i= fsStoreSubOrderMapper.selectFsStoreSubOrderByPackageNameAndId(fsStoreOrder.getPackageName(),fsPatient.getIdCard(),fsStoreOrder.getCreateTime());
                    if (i!=0){
                        return;
                    }
                }
                System.out.println("病人信息"+fsPatient);

                Integer cycle = fsStoreOrder.getCycle();
                if (cycle==null||cycle<=90){
                    //不用拆分
                    System.out.println("不用拆分");
                    FsStoreSubOrder sub = BeanCopyUtils.copy(fsStoreOrder, FsStoreSubOrder.class);
                    System.out.println(fsStoreOrder);
                    System.out.println(sub);
                    boolean gl=true;
                    BigDecimal inquiryCostPrice = new BigDecimal("0");
                    BigDecimal totalCostPrice = new BigDecimal("0");
                    List<FsPrescribeDrug> d = new ArrayList<>();
                    if (fsPatient!=null){
                        sub.setPatientName(fsPatient.getPatientName());
                        sub.setPatientIdcard(fsPatient.getIdCard());
                    }
                    sub.setPatientId(fsPatient.getPatientId());
                    sub.setDiagnosis(fsPrescribe.getDiagnose());
                    sub.setIsPush(0);

                    if (fsPrescribe.getPrescribeType()==2){
                        sub.setDetailsUsage("口服");
                        if (fsPrescribe.getRecipeType()!=null&&fsPrescribe.getRecipeType()==1){
                            sub.setDetailsUsage("外敷");
                        }

                        FsPrescribeUsageDTO fsPrescribeUsageDTO = JSON.parseObject(fsPrescribe.getUsageJson(), FsPrescribeUsageDTO.class);
                        sub.setPrescriptionNum(fsPrescribeUsageDTO.getCounts());
                        sub.setPrescriptionTaking(fsPrescribeUsageDTO.getUsageMethod());
                        sub.setPrescriptionRequirements(fsPrescribeUsageDTO.getUsageFrequencyUnit());

                    }
                    String prescribeJson = JSON.toJSONString(fsPrescribe);
                    sub.setPrescribeJson(prescribeJson);
                    String drugsJson = JSON.toJSONString(drugs);
                    sub.setPrescribeDrugJson(drugsJson);
                    //计算成本价

                    if (cycle!=null){
                        inquiryCostPrice=new BigDecimal(cycle).multiply(new BigDecimal("300"));
                    }

                        BigDecimal prodCostPrice = new BigDecimal("0");
                        for(FsPrescribeDrug drug:drugs){

                            if (drug.getProductId()!=null){
                                FsStoreProductAttrVO value = fsStoreProductMapper.selectFsStoreProductAttrVOByProdId(drug.getProductId());
                                if (value!=null&&!value.getBarCode().equals("106013")&&!value.getBarCode().equals("SPZ00004288")&&!value.getBarCode().equals("109066")){
                                    gl=false;
                                }else {
                                    continue;
                                }
                                FsPrescribeDrug copy = BeanCopyUtils.copy(drug, FsPrescribeDrug.class);

                                if (value!=null){
                                    copy.setBarCode(value.getBarCode());
                                    copy.setDrugUnit(value.getUnitName());
                                    copy.setPrescribeCode(value.getPrescribeCode());
                                }

                                if (value!=null&&value.getCostPrice()!=null){
                                    if (drug.getDrugNum()!=null){
                                        prodCostPrice=prodCostPrice.add(value.getCostPrice().multiply(BigDecimal.valueOf(drug.getDrugNum())));
                                    }
                                }
                                d.add(copy);
                            }

                            if(fsPrescribe.getPrescribeType().equals(2)){
                                FsPrescribeUsageDTO dto= JSONUtil.toBean(fsPrescribe.getUsageJson(),FsPrescribeUsageDTO.class);
                                prodCostPrice=prodCostPrice.multiply(BigDecimal.valueOf(dto.getCounts()));
                            }

                        }
                    if (gl){
                        return;
                    }
                    totalCostPrice = totalCostPrice.add(prodCostPrice.add(prodCostPrice));
                    sub.setCostPrice(prodCostPrice);
                    sub.setPrescribeJson(prescribeJson);
                    sub.setInquiryCostPrice(inquiryCostPrice);
                    sub.setPrescribeDrugJson(JSON.toJSONString(d));
                    sub.setTotalCostPrice(totalCostPrice);
                    sub.setIcdCode(fsPrescribe.getIcdCode());
                    sub.setSubOrderCode(IdUtil.getSnowflake(0, 0).nextIdStr());
                    sub.setDrugDoctorId(fsPrescribe.getDrugDoctorId());
                    fsStoreSubOrderMapper.insertFsStoreSubOrder(sub);
                }else {
                    //拆分
                    int c = cycle / 90;
                    int ys = cycle % 90;
                    if (ys > 0) {
                        c++;
                    }else {
                        ys=90;
                    }
                    System.out.println("拆分系数:"+c);
                    BigDecimal payMoneyD = fsStoreOrder.getPayMoney();
                    BigDecimal payPriceD = fsStoreOrder.getPayPrice();
                    BigDecimal payRemainD = fsStoreOrder.getPayRemain();
                    BigDecimal discountMoneyD = fsStoreOrder.getDiscountMoney();
                    BigDecimal payDeliveryD = fsStoreOrder.getPayDelivery();
                    BigDecimal prescribePriceD = fsStoreOrder.getPrescribePrice();
                    BigDecimal payMoneyC = payMoneyD;
                    BigDecimal payPriceC = payPriceD;
                    BigDecimal payRemainC = payRemainD;
                    BigDecimal discountMoneyC = discountMoneyD;
                    BigDecimal payDeliveryC = payDeliveryD;
                    BigDecimal prescribePriceC = prescribePriceD;
                    boolean gl=true;
                    for (int i=1;i<c;i++){
                        FsStoreSubOrder sub = BeanCopyUtils.copy(fsStoreOrder, FsStoreSubOrder.class);
                        BigDecimal prodCostPrice = new BigDecimal("0");
                        long num=0L;
                        List<FsPrescribeDrug> d = new ArrayList<>();

                        for (FsPrescribeDrug fsPrescribeDrug : drugs) {

                            Long drugNum = fsPrescribeDrug.getDrugNum();
                            long dc = drugNum / c;
                            num=num+ dc;
                            if (dc!=0){
                                FsPrescribeDrug copy = BeanCopyUtils.copy(fsPrescribeDrug, FsPrescribeDrug.class);
                                copy.setDrugNum(dc);
                                d.add(copy);
                                if (fsPrescribeDrug.getProductId()!=null){

                                    FsStoreProductAttrVO value = fsStoreProductMapper.selectFsStoreProductAttrVOByProdId(fsPrescribeDrug.getProductId());
                                    if (value!=null&&!value.getBarCode().equals("106013")&&!value.getBarCode().equals("SPZ00004288")&&!value.getBarCode().equals("109066")){
                                        gl=false;
                                    }else {
                                        continue;
                                    }
                                    if (value!=null){
                                        copy.setBarCode(value.getBarCode());
                                        copy.setDrugUnit(value.getUnitName());
                                        copy.setPrescribeCode(value.getPrescribeCode());
                                    }
                                    if (value!=null&&value.getCostPrice()!=null){
                                        prodCostPrice=prodCostPrice.add(value.getCostPrice().multiply(BigDecimal.valueOf(fsPrescribeDrug.getDrugNum())));
                                    }
                                }
                                if(fsPrescribe.getPrescribeType().equals(2)){
                                    FsPrescribeUsageDTO dto= JSONUtil.toBean(fsPrescribe.getUsageJson(),FsPrescribeUsageDTO.class);
                                    prodCostPrice=prodCostPrice.multiply(BigDecimal.valueOf(dto.getCounts()));
                                }
                            }
                        }
                        BigDecimal payMoneyC1 = payMoneyD.divide(new BigDecimal(c), RoundingMode.HALF_UP);
                        BigDecimal payPriceC1 = payPriceD.divide(new BigDecimal(c), RoundingMode.HALF_UP);
                        BigDecimal payRemainC1 = payRemainD.divide(new BigDecimal(c), RoundingMode.HALF_UP);
                        BigDecimal discountMoneyC1 = discountMoneyD.divide(new BigDecimal(c), RoundingMode.HALF_UP);
                        BigDecimal payDeliveryC1 = payDeliveryD.divide(new BigDecimal(c), RoundingMode.HALF_UP);
                        BigDecimal prescribePriceC1 = prescribePriceD.divide(new BigDecimal(c), RoundingMode.HALF_UP);
                        payMoneyC=  payMoneyC.subtract(payMoneyC1);
                        payPriceC=  payPriceC.subtract(payPriceC1);
                        payRemainC=  payRemainC.subtract(payRemainC1);
                        discountMoneyC=  discountMoneyC.subtract(discountMoneyC1);
                        payDeliveryC=  payDeliveryC.subtract(payDeliveryC1);
                        prescribePriceC=  prescribePriceC.subtract(prescribePriceC1);
                        sub.setPayMoney(payMoneyC1);
                        sub.setPayPrice(payPriceC1);

                        sub.setPayRemain(payRemainC1);
                        sub.setCycle(90);
                        sub.setTotalNum(num);
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(fsStoreOrder.getCreateTime());
                        calendar.add(Calendar.DAY_OF_MONTH, (i - 1)*90);
                        sub.setCreateTime(calendar.getTime());
                        calendar.setTime(fsStoreOrder.getPayTime());
                        calendar.add(Calendar.DAY_OF_MONTH, (i - 1)*90);
                        sub.setPayTime(calendar.getTime());
                        if (fsPatient!=null){
                            sub.setPatientName(fsPatient.getPatientName());
                            sub.setPatientIdcard(fsPatient.getIdCard());
                        }

                        sub.setIsPush(0);
                        if (fsPrescribe.getPrescribeType()==2){
                            sub.setDetailsUsage("口服");
                            if (fsPrescribe.getRecipeType()!=null&&fsPrescribe.getRecipeType()==1){
                                sub.setDetailsUsage("外敷");
                            }
                            FsPrescribeUsageDTO fsPrescribeUsageDTO = JSON.parseObject(fsPrescribe.getUsageJson(), FsPrescribeUsageDTO.class);
                            sub.setPrescriptionNum(fsPrescribeUsageDTO.getCounts());
                            sub.setPrescriptionTaking(fsPrescribeUsageDTO.getUsageMethod());
                            sub.setPrescriptionRequirements(fsPrescribeUsageDTO.getUsageFrequencyUnit());
                        }
                        sub.setPatientId(fsPatient.getPatientId());
                        sub.setDiagnosis(fsPrescribe.getDiagnose());
                        sub.setDiscountMoney(discountMoneyC1);
                        sub.setPayDelivery(payDeliveryC1);
                        sub.setPrescribePrice(prescribePriceC1);
                        sub.setCostPrice(prodCostPrice);
                        sub.setTotalCostPrice(prodCostPrice.add(new BigDecimal("4500")));
                        sub.setInquiryCostPrice(new BigDecimal("4500"));
                        sub.setCostDiscountMoney(sub.getTotalCostPrice().subtract(prescribePriceC1));
                        String prescribeJson = JSON.toJSONString(fsPrescribe);
                        sub.setPrescribeJson(prescribeJson);
                        sub.setIcdCode(fsPrescribe.getIcdCode());
                        sub.setPrescribeDrugJson(JSON.toJSONString(d));
                        sub.setSubOrderCode(IdUtil.getSnowflake(0, 0).nextIdStr());
                        sub.setDrugDoctorId(fsPrescribe.getDrugDoctorId());
                        fsStoreSubOrderMapper.insertFsStoreSubOrder(sub);
                        logger.info("药师id："+fsPrescribe.getDrugDoctorId());
                    }
                    FsStoreSubOrder sub = BeanCopyUtils.copy(fsStoreOrder, FsStoreSubOrder.class);
                    BigDecimal prodCostPrice = new BigDecimal("0");
                    List<FsPrescribeDrug> d = new ArrayList<>();
                    long  num=0L;
                    for (FsPrescribeDrug fsPrescribeDrug : drugs) {

                        Long drugNum = fsPrescribeDrug.getDrugNum();
                        long dc = (drugNum / c)+(drugNum % c);
                        num=num+ dc;
                        if (dc!=0){
                            FsPrescribeDrug copy = BeanCopyUtils.copy(fsPrescribeDrug, FsPrescribeDrug.class);
                            copy.setDrugNum(dc);
                            if (fsPrescribeDrug.getProductId()!=null){

                              FsStoreProductAttrVO value = fsStoreProductMapper.selectFsStoreProductAttrVOByProdId(fsPrescribeDrug.getProductId());
                                if (value!=null&&!value.getBarCode().equals("106013")&&!value.getBarCode().equals("SPZ00004288")&&!value.getBarCode().equals("109066")){
                                    gl=false;
                                }else {
                                    continue;
                                }
                                if (value!=null){
                                    copy.setBarCode(value.getBarCode());
                                    copy.setDrugUnit(value.getUnitName());
                                    copy.setPrescribeCode(value.getPrescribeCode());
                                }

                                if (value!=null&&value.getCostPrice()!=null){
                                    prodCostPrice=prodCostPrice.add(value.getCostPrice().multiply(BigDecimal.valueOf(fsPrescribeDrug.getDrugNum())));
                                }
                            }
                            if(fsPrescribe.getPrescribeType().equals(2)){
                                FsPrescribeUsageDTO dto= JSONUtil.toBean(fsPrescribe.getUsageJson(),FsPrescribeUsageDTO.class);
                                prodCostPrice=prodCostPrice.multiply(BigDecimal.valueOf(dto.getCounts()));
                            }
                            d.add(copy);
                        }
                    }
                    if (gl){
                        return;
                    }
                    String itemJson = fsStoreOrder.getItemJson();
                    if (itemJson!=null&&itemJson!=""){
                        List<FsStoreOrderItem> fsStoreOrderItems = JSON.parseArray(itemJson, FsStoreOrderItem.class);
                        if (fsStoreOrderItems!=null&&fsStoreOrderItems.size()>0){
                            for (FsStoreOrderItem fsStoreOrderItem : fsStoreOrderItems) {
                                if(fsStoreOrderItem.getIsGift()!=null&&fsStoreOrderItem.getIsGift()==1){
                                    String jsonInfo = fsStoreOrderItem.getJsonInfo();
                                    FsStoreOrderItemDTO fsStoreOrderItemDTO = JSON.parseObject(jsonInfo, FsStoreOrderItemDTO.class);
                                    FsPrescribeDrug item = new FsPrescribeDrug();
                                    FsStoreProductAttrVO value = fsStoreProductMapper.selectFsStoreProductAttrVOByProdId(fsStoreOrderItemDTO.getProductId());

                                    if (value!=null&&value.getCostPrice()!=null){
                                        item.setBarCode(value.getBarCode());
                                        item.setDrugUnit(value.getUnitName());
                                        item.setDrugName(fsStoreOrderItemDTO.getProductName());
                                        item.setDrugPrice(value.getPrice());
                                        item.setDrugImgUrl(value.getImage());
                                        item.setDrugNum(1L);
                                        prodCostPrice= prodCostPrice.add(value.getCostPrice());
                                        num++;
                                    }
                                    item.setProductId(fsStoreOrderItem.getProductId());
                                    item.setProductAttrValueId(fsStoreOrderItem.getProductAttrValueId());
                                    item.setDrugNum(Long.parseLong(fsStoreOrderItem.getNum().toString()));
                                    d.add(item);

                                }

                            }
                        }
                    }
                    sub.setTotalNum(num);
                    sub.setCycle(ys);

                    if (fsPatient!=null){
                        sub.setPatientName(fsPatient.getPatientName());
                        sub.setPatientIdcard(fsPatient.getIdCard());
                    }

                    sub.setIsPush(0);
                    if (fsPrescribe.getPrescribeType()==2){
                        sub.setDetailsUsage("口服");
                        if (fsPrescribe.getRecipeType()!=null&&fsPrescribe.getRecipeType()==1){
                            sub.setDetailsUsage("外敷");
                        }
                        FsPrescribeUsageDTO fsPrescribeUsageDTO = JSON.parseObject(fsPrescribe.getUsageJson(), FsPrescribeUsageDTO.class);
                        sub.setPrescriptionNum(fsPrescribeUsageDTO.getCounts());
                        sub.setPrescriptionTaking(fsPrescribeUsageDTO.getUsageMethod());
                        sub.setPrescriptionRequirements(fsPrescribeUsageDTO.getUsageFrequencyUnit());
                    }
                    sub.setPatientId(fsPatient.getPatientId());
                    sub.setDiagnosis(fsPrescribe.getDiagnose());

                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(fsStoreOrder.getCreateTime());
                    calendar.add(Calendar.DAY_OF_MONTH, (c - 1)*90);
                    sub.setCreateTime(calendar.getTime());
                    calendar.setTime(fsStoreOrder.getPayTime());
                    calendar.add(Calendar.DAY_OF_MONTH, (c - 1)*90);
                    sub.setPayTime(calendar.getTime());
                    sub.setPayMoney(payMoneyC);
                    sub.setPayPrice(payPriceC);
                    sub.setPayRemain(payRemainC);
                    sub.setDiscountMoney(discountMoneyC);
                    sub.setPayDelivery(payDeliveryC);
                    sub.setPrescribePrice(prescribePriceC);
                    sub.setCostPrice(prodCostPrice);
                    BigDecimal inquiryCostPrice = new BigDecimal("300").multiply(new BigDecimal(ys/6));
                    sub.setTotalCostPrice(prodCostPrice.add(inquiryCostPrice));
                    sub.setInquiryCostPrice(inquiryCostPrice);
                    sub.setCostDiscountMoney(sub.getTotalCostPrice().subtract(prescribePriceC));
                    String prescribeJson = JSON.toJSONString(fsPrescribe);
                    sub.setPrescribeJson(prescribeJson);
                    String drugsJson = JSON.toJSONString(d);
                    sub.setPrescribeDrugJson(drugsJson);
                    sub.setIcdCode(fsPrescribe.getIcdCode());
                    sub.setSubOrderCode(IdUtil.getSnowflake(0, 0).nextIdStr());
                    sub.setDrugDoctorId(fsPrescribe.getDrugDoctorId());
                    logger.info("药师id："+fsPrescribe.getDrugDoctorId());
                    fsStoreSubOrderMapper.insertFsStoreSubOrder(sub);
                }
            }
        }

    }

    @Override
    public FsSubOrderResultVO TuiFsStoreSubOrderByStoreOrder(Long orderId) {
        FsSysConfig sysConfig = configUtil.getSysConfig();
        System.out.println(orderId);
        FsStoreSubOrder fsStoreSubOrder = fsStoreSubOrderMapper.selectFsStoreSubOrderBySubOrderId(orderId);
        FsStore fsStore = fsStoreMapper.selectFsStoreByStoreId(fsStoreSubOrder.getStoreId());
        FsSubOrderParam param = new FsSubOrderParam();
        param.setPresentIllness("无");
        param.setDrugType(fsStoreSubOrder.getOrderType());
        param.setToken(sysConfig.getPrescribeToken()); // token
        param.setDiagnosis("[{\"diagnosis\":\""+fsStoreSubOrder.getDiagnosis()+"\"}]"); // 诊断列表
        param.setPrescriptionNum(fsStoreSubOrder.getPrescriptionNum() + "");
        param.setPrescriptionTaking(fsStoreSubOrder.getPrescriptionTaking());
        param.setPrescriptionRequirements(fsStoreSubOrder.getPrescriptionRequirements());
        param.setPatientName(fsStoreSubOrder.getPatientName()); // 患者姓名
        param.setPatientIdcard(fsStoreSubOrder.getPatientIdcard()); // 患者身份证号
        param.setMainSuit(fsStoreSubOrder.getDiagnosis()); // 主诉
        param.setPrice(fsStoreSubOrder.getPayPrice().doubleValue()); // 价格

        FsDoctor fsDoctor = fsDoctorMapper.selectFsDoctorByDoctorId(fsStoreSubOrder.getDoctorId());
        param.setDoctorIdCard(fsDoctor.getIdCard()); // 医生身份证号
        param.setDoctorName(fsDoctor.getDoctorName()); // 医生姓名
        FsDoctor drugDoctor = fsDoctorMapper.selectFsDoctorByDoctorId(fsStoreSubOrder.getDrugDoctorId());
        param.setPharmacistIdCard(drugDoctor.getIdCard()); // 药师身份证号
        param.setPharmacistName(drugDoctor.getDoctorName()); // 药师姓名
        param.setThirdPlatformName("互联网医院"); // 第三方平台名称
        param.setThirdPatientEvaluate("0"); // 患者满意度评价


        String createDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(fsStoreSubOrder.getCreateTime());

        param.setFurtherConsultApplyTime(createDate); // 复诊申请时间
        param.setFurtherConsulStartTime(createDate); // 复诊开始时间
        param.setFurtherConsulEndTime(createDate); // 复诊结束时间
        param.setThirdFurtherConsultPrice("0"); // 复诊价格
        param.setPrimaryHospital("无"); // 初诊医院
        param.setPrimaryTime("无"); // 初诊时间
        param.setPrescriptionNum(fsStoreSubOrder.getPrescriptionNum()!=null?fsStoreSubOrder.getPrescriptionNum()+"":"1");
        param.setPrescriptionTaking(fsStoreSubOrder.getPrescriptionTaking()!=null&&fsStoreSubOrder.getPrescriptionTaking()!=""?fsStoreSubOrder.getPrescriptionTaking():"无");
        param.setPrescriptionRequirements(fsStoreSubOrder.getPrescriptionRequirements()!=null&&fsStoreSubOrder.getPrescriptionRequirements()!=""?fsStoreSubOrder.getPrescriptionRequirements():"无");
        ArrayList<FsSubOrderDrugListParam> drugs = new ArrayList<>();
        String prescribeDrugJson = fsStoreSubOrder.getPrescribeDrugJson();
        List<FsPrescribeDrug> fsPrescribeDrugs = JSON.parseArray(prescribeDrugJson, FsPrescribeDrug.class);
        for (FsPrescribeDrug drug : fsPrescribeDrugs) {
            FsSubOrderDrugListParam d = new FsSubOrderDrugListParam();
            d.setStoreId(fsStoreSubOrder.getStoreId() + "");
            d.setStoreName(fsStore.getStoreName());
            d.setDrugMedicineCode(drug.getBarCode());
            d.setDetailsDay(fsStoreSubOrder.getCycle());
            d.setDetailsNum(drug.getDrugNum().intValue());
            d.setDrugPackagingUnit(drug.getDrugUnit());

            d.setDetailsConsumption(drug.getUsagePerUseCount()!=null&&drug.getUsagePerUseCount()!=""?drug.getUsagePerUseCount():"无");
            d.setDetailsConsumptionUnit(drug.getUsagePerUseUnit()!=null&&drug.getUsagePerUseUnit()!=""?drug.getUsagePerUseUnit():"无");
            d.setDetailsUsage(fsStoreSubOrder.getDetailsUsage()!=null&&fsStoreSubOrder.getDetailsUsage()!=""?fsStoreSubOrder.getDetailsUsage():"无");
            d.setDetailsFrequencyStr(drug.getUsageFrequencyUnit()!=null&&drug.getUsageFrequencyUnit()!=""?drug.getUsageFrequencyUnit():"无");
            d.setDrugCommonCode(drug.getPrescribeCode()!=null&&drug.getPrescribeCode().trim().length()!=0?drug.getPrescribeCode():"无");
            logger.info("国药准字:"+d.getDrugCommonCode());
            drugs.add(d);
        }
        param.setDrugList(drugs); // 药品列表
        System.out.println(param);
        String url = sysConfig.getPrescribeUrl();
        String requestData = JSON.toJSONString(param);
        // 创建 HttpClient 实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建 HTTP POST 请求
            HttpPost httpPost = new HttpPost(url);
            // 设置请求头参数
            httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
            StringEntity stringEntity = new StringEntity(requestData, StandardCharsets.UTF_8);
            httpPost.setEntity(stringEntity);
            System.out.println("传参："+requestData);
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应状态
                HttpEntity entity = response.getEntity();
                String responseBody = EntityUtils.toString(entity);
                logger.info(orderId+"上传处方返回："+responseBody);
                FsSubOrderResultVO fsSubOrderResultVO = JSON.parseObject(responseBody, FsSubOrderResultVO.class);
                if (fsSubOrderResultVO.getCode()==1){
                    FsStoreSubOrder o = new FsStoreSubOrder();
                    o.setSubOrderId(orderId);
                    o.setIsPush(1);
                    fsStoreSubOrderMapper.updateFsStoreSubOrder(o);
                }else {
                    FsStoreSubOrder o = new FsStoreSubOrder();
                    o.setSubOrderId(orderId);
                    o.setIsPush(2);
                    fsStoreSubOrderMapper.updateFsStoreSubOrder(o);
                    logger.info(orderId+"：上传处方错误："+fsSubOrderResultVO+":"+param.getDoctorName());
                }
                return fsSubOrderResultVO;
            }

        } catch (Exception e){

        }
        return null;
    }

    @Override
    public List<Long> selectFsStoreSubOrderByNoPush() {
        return fsStoreSubOrderMapper.selectFsStoreSubOrderByNoPush();
    }

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

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

    @Override
    public Long selectFsStoreSubOrderListCount(FsStoreOrderParam fsStoreSubOrder) {
        return fsStoreSubOrderMapper.selectFsStoreSubOrderListCount(fsStoreSubOrder);
    }

}
