package com.fs.his.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.CustomException;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.ip.IpUtils;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyDept;
import com.fs.company.domain.CompanyMoneyLogs;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyMapper;
import com.fs.company.mapper.CompanyMoneyLogsMapper;
import com.fs.company.param.FsStoreStatisticsParam;
import com.fs.company.service.ICompanyDeptService;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.vo.FsStoreOrderStatisticsVO;
import com.fs.company.vo.FsStoreProductStatisticsVO;
import com.fs.core.config.WxPayProperties;
import com.fs.core.utils.OrderCodeUtils;
import com.fs.erp.domain.*;
import com.fs.erp.dto.ErpOrderQueryRequert;
import com.fs.erp.dto.ErpOrderQueryResponse;
import com.fs.erp.dto.ErpOrderResponse;
import com.fs.erp.dto.ErpRefundUpdateRequest;
import com.fs.erp.service.IErpOrderService;
import com.fs.event.*;
import com.fs.his.config.FsSysConfig;
import com.fs.his.config.StoreConfig;
import com.fs.his.domain.*;
import com.fs.his.dto.*;
import com.fs.his.enums.FsStoreOrderLogEnum;
import com.fs.his.enums.FsStoreOrderStatusEnum;
import com.fs.his.enums.ShipperCodeEnum;
import com.fs.his.mapper.*;
import com.fs.his.param.*;
import com.fs.his.service.*;
import com.fs.his.utils.ConfigUtil;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.vo.*;
import com.fs.hisapi.domain.ApiResponse;
import com.fs.hisapi.param.CreateOrderParam;
import com.fs.hisapi.param.RecipeDetailParam;
import com.fs.hisapi.service.HisApiService;
import com.fs.huifuPay.domain.HuiFuCreateOrder;
import com.fs.huifuPay.domain.HuifuCreateOrderResult;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.im.dto.*;
import com.fs.im.service.IImService;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.domain.QwUser;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.sop.mapper.QwSopLogsMapper;
import com.fs.qw.service.impl.QwUserServiceImpl;
import com.fs.system.domain.SysConfig;
import com.fs.tzBankPay.doman.*;
import com.fs.ybPay.domain.CreateWxOrderResult;
import com.fs.ybPay.domain.OrderResult;
import com.fs.ybPay.dto.OrderQueryDTO;
import com.fs.ybPay.dto.WxJspayDTO;
import com.fs.ybPay.service.IPayService;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.system.service.ISysConfigService;
import com.fs.tzBankPay.TzBankService.TzBankService;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.google.gson.Gson;
import lombok.Synchronized;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.Charset;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.fs.his.utils.PhoneUtil.decryptPhone;

/**
 * 订单Service业务层处理
 *
 * @author fs
 * @date 2023-06-13
 */
@Lazy
@Service
public class FsStoreOrderServiceImpl implements IFsStoreOrderService
{
    Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private FsStorePaymentErrorMapper fsStorePaymentErrorMapper;
    @Autowired
    private FsFollowTempMapper fsFollowTempMapper;
    @Autowired
    private WxPayProperties wxPayProperties;
    @Autowired
    private TzBankService tzBankService;
    @Autowired
    private FsFollowMapper fsFollowMapper;
    @Autowired
    RedisCache redisCache;
    @Autowired
    private HuiFuService huiFuService;
    @Autowired
    private FsStoreOrderMapper fsStoreOrderMapper;
    @Autowired
    private FsStoreOrderItemMapper fsStoreOrderItemMapper;
    @Autowired
    private FsStoreOrderLogsMapper fsStoreOrderLogsMapper;
    @Autowired
    private FsPrescribeMapper prescribeMapper;
    @Autowired
    private FsPrescribeDrugMapper prescribeDrugMapper;
    @Autowired
    private FsStoreProductAttrValueMapper fsStoreProductAttrValueMapper;
    @Autowired
    private FsStoreProductMapper fsStoreProductMapper;
    @Autowired
    private IFsStoreOrderLogsService fsStoreOrderLogsService;

    @Autowired
    private IFsStorePaymentService storePaymentService;
    @Autowired
    private FsStorePaymentMapper fsStorePaymentMapper;
    @Autowired
    private IFsExpressService expressService;
    @Autowired
    HisApiService hisApiService;
    @Autowired
    FsInquiryOrderMapper fsInquiryOrderMapper;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    ICompanyUserService companyUserService;
    @Autowired
    private IFsUserService userService;
    @Autowired
    private ConfigUtil configUtil;
    @Autowired
    private IFsUserCouponService userCouponService;
    @Autowired
    private IFsCouponService couponService;
    @Autowired
    private IFsUserAddressService userAddressService;
    @Autowired
    private IFsStoreOrderItemService storeOrderItemService;
    @Autowired
    private IPayService payService;
    @Autowired
    private ICompanyDeptService companyDeptService;
    @Autowired
    private IErpOrderService erpOrderService;
    @Autowired
    private IFsStoreAfterSalesService fsStoreAfterSalesService;
    @Autowired
    private FsStoreAfterSalesLogsMapper fsStoreAfterSalesLogsMapper;
    @Autowired
    private FsStoreAfterSalesItemMapper fsStoreAfterSalesItemMapper;
    @Autowired
    private FsPackageMapper fsPackageMapper;
    @Autowired
    private FsPackageOrderMapper fsPackageOrderMapper;
    @Autowired
    private IFsStoreOrderService fsStoreOrderService;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private CompanyMoneyLogsMapper companyMoneyLogsMapper;
    @Autowired
    private IFsDoctorService iFsDoctorService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IFsUserAddressService fsUserAddressService;
    @Autowired
    private IPayService ybPayService;
    @Autowired
    private IImService imService;
    @Autowired
    private IFsUserService fsUserService;
    @Autowired
    private FsStoreMapper fsStoreMapper;
    @Autowired
    private IFsInquiryOrderService inquiryOrderService;
    @Autowired
    FsFollowReportMapper fsFollowReportMapper;
    @Autowired
    FsStoreSubOrderServiceImpl storeSubOrderService;
    @Autowired
    ApplicationEventPublisher publisher;

    @Autowired
    IFsUserWatchService fsUserWatchService;
    @Autowired
    QwExternalContactMapper qwExternalContactMapper;
    @Autowired
    QwSopLogsMapper qwSopLogsMapper;

    @Autowired
    private IFsExportTaskService exportTaskService;
    @Autowired
    private QwUserServiceImpl qwUserServiceImpl;

    /**
     * 查询订单
     *
     * @param orderId 订单主键
     * @return 订单
     */
    @Override
    public FsStoreOrder selectFsStoreOrderByOrderId(Long orderId)
    {
        return fsStoreOrderMapper.selectFsStoreOrderByOrderId(orderId);
    }

    /**
     * 查询订单列表
     *
     * @param fsStoreOrder 订单
     * @return 订单
     */
    @Override
    public List<FsStoreOrder> selectFsStoreOrderList(FsStoreOrder fsStoreOrder)
    {
        return fsStoreOrderMapper.selectFsStoreOrderList(fsStoreOrder);
    }

    /**
     * 新增订单
     *
     * @param fsStoreOrder 订单
     * @return 结果
     */
    @Override
    public int insertFsStoreOrder(FsStoreOrder fsStoreOrder)
    {
        fsStoreOrder.setCreateTime(DateUtils.getNowDate());
        return fsStoreOrderMapper.insertFsStoreOrder(fsStoreOrder);
    }

    /**
     * 修改订单
     *
     * @param fsStoreOrder 订单
     * @return 结果
     */
    @Override
    public int updateFsStoreOrder(FsStoreOrder fsStoreOrder)
    {
        fsStoreOrder.setUpdateTime(DateUtils.getNowDate());
        return fsStoreOrderMapper.updateFsStoreOrder(fsStoreOrder);
    }

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

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

    @Override
    public List<FsStoreOrderListVO> selectFsStoreOrderListVO(FsStoreOrderParam param) {
        return fsStoreOrderMapper.selectFsStoreOrderListVO(param);
    }


    @Override
    public List<FsStoreOrderItem> selectFsStoreOrderItemList(String orderId) {
        return fsStoreOrderMapper.selectFsStoreOrderItemList(orderId);
    }

    @Override
    public List<FsStoreOrderLogs> selectFsStoreOrderLogsList(String orderId) {
        return fsStoreOrderMapper.selectFsFsStoreOrderLogsList(orderId);
    }





    @Override
    public int sendGoods(FsStoreOrder fsStoreOrder) {
        FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderId(fsStoreOrder.getOrderId());
        if (order==null)throw new CustomException("订单不存在");
        if (order.getStatus()!=2)throw new CustomException("非法更改");
        FsStoreOrder o1 = new FsStoreOrder();
        o1.setOrderId(fsStoreOrder.getOrderId());
        o1.setStatus(3);
        o1.setUpdateTime(new DateTime());
        o1.setDeliveryCode(fsStoreOrder.getDeliveryCode());
        o1.setDeliveryName(fsStoreOrder.getDeliveryName());
        o1.setDeliverySn(fsStoreOrder.getDeliverySn());
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(new Date());
        o1.setDeliveryTime( dateString);
        int i = fsStoreOrderMapper.updateFsStoreOrder(o1);
        if (order.getCompanyId()!=null){
            companyService.subtractCompanyMoney(order);
        }
        FsStoreOrderLogs Logs = new FsStoreOrderLogs();
        Logs.setChangeMessage("订单发货");
        Logs.setOrderId(fsStoreOrder.getOrderId());
        Logs.setChangeTime(new DateTime());
        Logs.setChangeType("delivery_goods");
        fsStoreOrderLogsMapper.insertFsStoreOrderLogs(Logs);

        String lastFourNumber = "";
        if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
            lastFourNumber = order.getUserPhone();
            if (lastFourNumber.length() == 11) {
                lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
            }
        }
        expressService.subscribeEspress(order.getOrderCode(),fsStoreOrder.getDeliveryCode(),fsStoreOrder.getDeliverySn(),lastFourNumber);
        return i;
    }

    @Override
    public int getGoods(Long orderId) {

        FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderId(orderId);
        if (order==null)throw new CustomException("订单不存在");
        if (order.getStatus()!=FsStoreOrderStatusEnum.STATUS_3.getValue())throw new CustomException("非法更改");
        FsStoreOrder o1 = new FsStoreOrder();
        o1.setUpdateTime(new DateTime());
        o1.setFinishTime(new Date());
        o1.setOrderId(orderId);
        o1.setStatus(FsStoreOrderStatusEnum.STATUS_4.getValue());
        logger.info("确认收货："+orderId);
        if (order.getCompanyId()!=null&&order.getTuiMoneyStatus()==0&&order.getPayType()==1){
            logger.info("分佣："+orderId);
            companyService.addCompanyMoney(order);
            o1.setTuiMoneyTime(new Date());
        }
        fsUserWatchService.addUserWatch(order);
        int i = fsStoreOrderMapper.updateFsStoreOrder(o1);
        fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.FINISH_ORDER.getValue(),
                FsStoreOrderLogEnum.FINISH_ORDER.getDesc());
        return i;
    }



    @Override
    public int updateMoney(FsStoreOrder fsStoreOrder) {
        FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderId(fsStoreOrder.getOrderId());
        if (order==null){
            throw new CustomException("订单不存在");
        }
        if (order.getStatus()!=1){
            throw new CustomException("非法更改");
        }
        FsStoreOrder o1 = new FsStoreOrder();
        o1.setUpdateTime(new DateTime());
        o1.setPayPrice(fsStoreOrder.getPayPrice());
        o1.setOrderId(fsStoreOrder.getOrderId());
        int i = fsStoreOrderMapper.updateFsStoreOrder(o1);
        FsStoreOrderLogs Logs = new FsStoreOrderLogs();
        Logs.setChangeMessage("改价");
        Logs.setOrderId(fsStoreOrder.getOrderId());
        Logs.setChangeTime(new DateTime());
        Logs.setChangeType("edit_order_money");
        fsStoreOrderLogsMapper.insertFsStoreOrderLogs(Logs);
        return i;
    }

    @Override
    public R cancelOrder(Long orderId) {
        FsStoreOrder order= fsStoreOrderMapper.selectFsStoreOrderByOrderId(orderId);
        if(order.getStatus()== FsStoreOrderStatusEnum.STATUS_1.getValue()){
            if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
                FsUserCoupon userCoupon=new FsUserCoupon();
                userCoupon.setId(order.getUserCouponId());
                userCoupon.setBusinessId(0l);
                userCoupon.setStatus(0);
                userCouponService.updateFsUserCoupon(userCoupon);
            }
            //退回库存
//            this.refundStock(order);
            fsStoreOrderMapper.cancelOrder(orderId);
            //添加记录
            fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.CANCEL_ORDER.getValue(),
                    FsStoreOrderLogEnum.CANCEL_ORDER.getDesc());

//            TemplateBean templateBean = TemplateBean.builder()
//                    .orderId(order.getOrderId().toString())
//                    .remark("您的订单已取消")
//                    .uid(order.getUserId())
//                    .templateType(TemplateListenEnum.TYPE_1.getValue())
//                    .build();
//            publisher.publishEvent(new TemplateEvent(this, templateBean));
            return R.ok("操作成功");
        }
        else{
            return R.error("非法操作");
        }

    }

    @Override
    public List<FsStoreOrderListUVO> selectFsStoreOrderListUVO(FsStoreOrderListUParam param) {
        List<FsStoreOrderListUVO>  list=fsStoreOrderMapper.selectFsStoreOrderListUVO(param);
        for(FsStoreOrderListUVO vo:list){
            vo.setIsAfterSales(0);
            if(vo.getStatus().equals(FsStoreOrderStatusEnum.STATUS_4.getValue())){
                //已完成订单
                vo.setIsAfterSales(1);
                if(vo.getFinishTime()!=null){
                    String json=configService.selectConfigByKey("his.store");
                    StoreConfig storeConfig=JSONUtil.toBean(json,StoreConfig.class);
                    if(storeConfig.getStoreAfterSalesDay()!=null&&storeConfig.getStoreAfterSalesDay()>0){
                        //判断完成时间是否超过指定时间
                        Calendar calendar = new GregorianCalendar();
                        calendar.setTime(vo.getFinishTime());
                        calendar.add(calendar.DATE,storeConfig.getStoreAfterSalesDay()); //把日期往后增加一天,整数  往后推,负数往前移动
                        if(calendar.getTime().getTime()<new Date().getTime()){
                            vo.setIsAfterSales(0);
                        }
                    }
                }
            }
            else if(vo.getStatus()==2||vo.getStatus()==3){
                vo.setIsAfterSales(1);
            }
        }
        return list;
    }

    @Override
    public R createOrder(Long prescribeId) {
        FsPrescribe prescribe=prescribeMapper.selectFsPrescribeByPrescribeId(prescribeId);
        FsPrescribeDrug map=new FsPrescribeDrug();
        map.setPrescribeId(prescribeId);
        List<FsPrescribeDrug> drugs=prescribeDrugMapper.selectFsPrescribeDrugList(map);
        FsStoreOrder order=new FsStoreOrder();
        List<FsStoreOrderItem> items=new ArrayList<>();
        String orderSn =  OrderCodeUtils.getOrderSn();
        if(StringUtils.isEmpty(orderSn)){
            return R.error("订单生成失败，请重试");
        }
        order.setOrderCode(orderSn);
        order.setCycle(prescribe.getCycle());
        order.setStoreId(prescribe.getStoreOrderId());
        order.setUserId(prescribe.getUserId());
        order.setStoreId(prescribe.getStoreId());
        order.setDoctorId(prescribe.getDoctorId());
        order.setInquiryOrderId(prescribe.getInquiryOrderId());
        FsInquiryOrder fsInquiryOrder = fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(prescribe.getInquiryOrderId());
        if (fsInquiryOrder != null) {
            order.setCompanyId(fsInquiryOrder.getCompanyId());
            order.setCompanyUserId(fsInquiryOrder.getCompanyUserId());
        }
        order.setPackageSecondName("医生处方");
        order.setPackageName("医生处方");
        order.setStatus(1);
        order.setPayType(1);
        order.setIsPrescribe(1);
        order.setPrescribeId(prescribe.getPrescribeId());
        order.setCreateTime(new Date());
        if (prescribe.getSource()!=null){
            order.setSource(prescribe.getSource());
        }
        Long totalNum=0l;
        BigDecimal totalPrice=new BigDecimal(0);
        BigDecimal totalCostPrice = new BigDecimal("0");
        for(FsPrescribeDrug drug:drugs){
            totalPrice=totalPrice.add(drug.getDrugPrice().multiply(BigDecimal.valueOf(drug.getDrugNum())));
            totalNum=totalNum+drug.getDrugNum();
            FsStoreOrderItem item=new FsStoreOrderItem();
            item.setProductId(drug.getProductId());
            item.setIsDrug(drug.getIsDrug());
            item.setStoreId(prescribe.getStoreId());
            item.setProductAttrValueId(drug.getProductAttrValueId());
            if (drug.getProductAttrValueId()!=null){
                FsStoreProductAttrValue value = fsStoreProductAttrValueMapper.selectFsStoreProductAttrValueById(drug.getProductAttrValueId());
                if (value.getCost()!=null){
                    if (drug.getDrugNum()!=null){
                        totalCostPrice=totalCostPrice.add(value.getCost().multiply(BigDecimal.valueOf(drug.getDrugNum())));
                    }
                }
            }

            item.setNum(drug.getDrugNum());
            FsStoreOrderItemDTO dto=new FsStoreOrderItemDTO();
            dto.setImage(drug.getDrugImgUrl());
            dto.setNum(drug.getDrugNum());
            FsStoreProduct product=fsStoreProductMapper.selectFsStoreProductByProductId(drug.getProductId());
            if(product!=null){
                dto.setProductName(product.getProductName());
                dto.setProductId(product.getProductId());
            }
            FsStoreProductAttrValue value=fsStoreProductAttrValueMapper.selectFsStoreProductAttrValueById(drug.getProductAttrValueId());
            if(value!=null){
                dto.setSku(value.getSku());
                dto.setBarCode(value.getBarCode());
                dto.setPrice(value.getPrice());
                dto.setNum(drug.getDrugNum());
                dto.setImage(value.getImage());
            }
            item.setIsPrescribe(1);
            item.setJsonInfo(JSON.toJSONString(dto));
            items.add(item);
        }
        //中药总价处理
        if(prescribe.getPrescribeType().equals(2)){
            FsPrescribeUsageDTO dto=JSONUtil.toBean(prescribe.getUsageJson(),FsPrescribeUsageDTO.class);
            totalPrice=totalPrice.multiply(BigDecimal.valueOf(dto.getCounts()));
            totalNum=dto.getCounts();
            totalCostPrice=totalCostPrice.multiply(BigDecimal.valueOf(dto.getCounts()));
        }
        order.setCostPrice(totalCostPrice);
        order.setOrderType(prescribe.getPrescribeType());
        order.setTotalNum(totalNum);
        order.setTotalPrice(totalPrice);
        order.setPayPrice(totalPrice);
        order.setItemJson(JSONUtil.toJsonStr(items));
        if(fsStoreOrderMapper.insertFsStoreOrder(order)>0){
            prescribe.setStoreOrderId(order.getOrderId());
            prescribeMapper.updateFsPrescribe(prescribe);
            for(FsStoreOrderItem item:items){
                item.setOrderId(order.getOrderId());
                fsStoreOrderItemMapper.insertFsStoreOrderItem(item);
            }
            fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.CREATE_ORDER.getValue(),
                    FsStoreOrderLogEnum.CREATE_ORDER.getDesc());
        }
        return R.ok();
    }

    @Override
    public R createOrderByPackageOrder(FsPackageOrder packageOrder) {
        if (packageOrder.getDoctorId()==null){
            Long doctorID = iFsDoctorService.selectFsDoctorDoctorByPackage();
            packageOrder.setDoctorId(doctorID);
        }
        FsPackage fsPackage=fsPackageMapper.selectFsPackageByPackageId(packageOrder.getPackageId());
        JSONArray objects =JSONUtil.parseArray(fsPackage.getProductJson());
        List<FsPackagePruductDTO> products=JSONUtil.toList(objects,FsPackagePruductDTO.class);
//        boolean isDrug=false;
//        for (FsPackagePruductDTO product : products) {
//            if (product.getIsDrug()==1){
//                isDrug=true;
//            }
//        }
//        Long prescribeId=null;

        Map<String,Object> packageJson = (Map)JSON.parse(packageOrder.getPackageJson());
        Integer packageSubType = (Integer)packageJson.get("packageSubType");
        if (packageSubType==3){
            R orderByPackageOrderStatus4 = inquiryOrderService.createOrderByPackageOrderStatus4(packageOrder);
        }
        Long  prescribeId= fsPrescribeService.insertFsPrescribeByPackageOrder(packageOrder);

        FsStoreOrder order=new FsStoreOrder();
        List<FsStoreOrderItem> items=new ArrayList<>();
        logger.info("套餐包生成药品订单："+packageOrder.getOrderSn());
        order.setOrderCode(packageOrder.getOrderSn());
        order.setUserId(packageOrder.getUserId());
        order.setStoreId(fsPackage.getStoreId());
        order.setPrescribeId(prescribeId);
        order.setStatus(2);
        order.setPayDelivery(packageOrder.getPayDelivery());
        order.setPayRemain(packageOrder.getPayRemain());
        order.setPayType(packageOrder.getPayType());
        order.setPackageSecondName(packageOrder.getPackageSecondName());
        order.setDoctorId(packageOrder.getDoctorId());
        order.setIsPrescribe(0);
        order.setPackageId(packageOrder.getPackageId());
        order.setPackageName(packageOrder.getPackageName());
        order.setPrescribePrice(packageOrder.getTotalPrice());
        order.setDiscountMoney(packageOrder.getDiscountMoney());
        order.setDeptId(packageOrder.getDeptId());
        order.setCompanyId(packageOrder.getCompanyId());
        order.setCompanyUserId(packageOrder.getCompanyUserId());
        order.setInquiryOrderId(packageOrder.getInquiryOrderId());
        order.setPackageOrderId(packageOrder.getOrderId());
        order.setCreateTime(new Date());
        if (packageOrder.getSource()!=null){
            order.setSource(packageOrder.getSource());
        }
        String addressJson = packageOrder.getAddressJson();
        if (addressJson!=null&&addressJson!=""){
            Map<String,String> parse = (Map)JSON.parse(addressJson);
            order.setUserName(parse.get("userName"));
            order.setUserPhone(parse.get("userPhone"));
            order.setUserAddress(parse.get("userAddress"));
        }


        Long totalNum=0l;
        BigDecimal totalPrice=new BigDecimal(0);
        boolean noTui=false;
        for(FsPackagePruductDTO product:products){
            if (product.getBarCode().equals("106013")){
                noTui=true;
            }
            totalPrice=totalPrice.add(product.getPrice().multiply(BigDecimal.valueOf(product.getCount())));
            totalNum=totalNum+product.getCount();
            FsStoreOrderItem item=new FsStoreOrderItem();
            item.setProductId(product.getProductId());
            item.setStoreId(fsPackage.getStoreId());
            item.setProductAttrValueId(product.getId());
            item.setNum(Long.parseLong(product.getCount().toString()));
            item.setIsDrug(product.getIsDrug());
            FsStoreOrderItemDTO dto=new FsStoreOrderItemDTO();
            dto.setImage(product.getImage());
            dto.setNum(Long.parseLong(product.getCount().toString()));
            dto.setProductName(product.getProductName());
            dto.setProductId(product.getProductId());
            dto.setSku(product.getSku());
            dto.setBarCode(product.getBarCode());
            dto.setPrice(product.getPrice());
            dto.setNum(Long.parseLong(product.getCount().toString()));
            dto.setImage(product.getImage());
            item.setIsPrescribe(0);
            item.setJsonInfo(JSON.toJSONString(dto));
            item.setIsGift(0);
            items.add(item);
        }
        String json=configService.selectConfigByKey("his.package");
        PackageConfigDTO configDTO=JSONUtil.toBean(json, PackageConfigDTO.class);
        FsPackageOrder fsPackageOrder = new FsPackageOrder();
        //赠品处理
        if(configDTO.getGiftStoreId()!=null&&configDTO.getGiftStoreId()==packageOrder.getStoreId()&&packageOrder.getCompanyId()!=null&&packageOrder.getCompanyId()>0&&packageOrder.getPayType().equals(1)&&packageOrder.getPayMoney().compareTo(configDTO.getGiftPrice())>=0){
            if(configDTO.getGift()!=null&&configDTO.getGift().size()>0){
                for(StoreOrderProductDTO product:configDTO.getGift()){
                    totalNum=totalNum+product.getCount();
                    FsStoreOrderItem item=new FsStoreOrderItem();
                    item.setProductId(product.getProductId());
                    item.setStoreId(fsPackage.getStoreId());
                    item.setProductAttrValueId(product.getId());
                    item.setNum(Long.parseLong(product.getCount().toString()));
                    FsStoreOrderItemDTO dto=new FsStoreOrderItemDTO();
                    dto.setImage(product.getImage());
                    dto.setNum(Long.parseLong(product.getCount().toString()));
                    dto.setProductName(product.getProductName());
                    dto.setProductId(product.getProductId());
                    dto.setSku(product.getSku());
                    dto.setBarCode(product.getBarCode());
                    dto.setPrice(product.getPrice());
                    if(product.getCount()!=null){
                        dto.setNum(Long.parseLong(product.getCount().toString()));
                    }
                    dto.setImage(product.getImage());
                    item.setIsPrescribe(0);
                    item.setJsonInfo(JSON.toJSONString(dto));
                    item.setIsGift(1);
                    items.add(item);
                    fsPackageOrder.setProductCostPrice(packageOrder.getProductCostPrice().add(product.getCostPrice()));
                    fsPackageOrder.setTotalCostPrice(packageOrder.getTotalCostPrice().add(product.getCostPrice()));
                    fsPackageOrder.setCostDiscountMoney(packageOrder.getCostDiscountMoney().subtract(product.getCostPrice()));
                }
            }
        }
        //物流代收赠品
        if(configDTO.getGiftStoreId()!=null&&configDTO.getGiftStoreId()==packageOrder.getStoreId()&&packageOrder.getCompanyId()!=null&&packageOrder.getCompanyId()>0&&packageOrder.getPayType().equals(2)&&packageOrder.getPayPrice().compareTo(configDTO.getGiftPrice())>=0){
            if(configDTO.getDeliveryGift()!=null&&configDTO.getDeliveryGift().size()>0){
                for(StoreOrderProductDTO product:configDTO.getDeliveryGift()){
                    totalNum=totalNum+product.getCount();
                    FsStoreOrderItem item=new FsStoreOrderItem();
                    item.setProductId(product.getProductId());
                    item.setStoreId(fsPackage.getStoreId());
                    item.setProductAttrValueId(product.getId());
                    item.setNum(Long.parseLong(product.getCount().toString()));
                    FsStoreOrderItemDTO dto=new FsStoreOrderItemDTO();
                    dto.setImage(product.getImage());
                    dto.setNum(Long.parseLong(product.getCount().toString()));
                    dto.setProductName(product.getProductName());
                    dto.setProductId(product.getProductId());
                    dto.setSku(product.getSku());
                    dto.setBarCode(product.getBarCode());
                    dto.setPrice(product.getPrice());
                    if(product.getCount()!=null){
                        dto.setNum(Long.parseLong(product.getCount().toString()));
                    }
                    dto.setImage(product.getImage());
                    item.setIsPrescribe(0);
                    item.setJsonInfo(JSON.toJSONString(dto));
                    item.setIsGift(1);
                    items.add(item);
                    fsPackageOrder.setProductCostPrice(packageOrder.getProductCostPrice().add(product.getCostPrice()));
                    fsPackageOrder.setTotalCostPrice(packageOrder.getTotalCostPrice().add(product.getCostPrice()));
                    fsPackageOrder.setCostDiscountMoney(packageOrder.getCostDiscountMoney().subtract(product.getCostPrice()));
                }
            }
        }
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.store");
        Map<String, Object> config = (Map<String, Object>) JSON.parse(sysConfig.getConfigValue());
        Integer followRate = (Integer)config.get("followRate");
        Integer FollowTempId = (Integer)config.get("oneFollowTempId");
        Long followDoctorId = fsPackageOrderMapper.selectFsPackageOrderByUserId(order.getUserId());
        if (followDoctorId!=null&&followDoctorId>0){
            order.setFollowDoctorId(followDoctorId);
        }else {
            if (packageOrder.getCompanyId()!=null){
                Company company = companyService.selectCompanyById(packageOrder.getCompanyId());
                if (company!=null){
                    String followDoctorIdsJson = company.getFollowDoctorIds();
                    if (followDoctorIdsJson!=null&&followDoctorIdsJson!=""){
                        long[] ids = JSON.parseObject(followDoctorIdsJson, long[].class);
                        if (ids.length>0){
                            Random random = new Random();
                            // 从数组中随机选择一个数字
                            int randomIndex = random.nextInt(ids.length);
                            long randomId = ids[randomIndex];
                            order.setFollowDoctorId(randomId);
                        }
                    }
                }
            }
            if (order.getFollowDoctorId()==null){
                order.setFollowDoctorId(iFsDoctorService.selectFollowDoctorDoctorByPackage());
            }
        }





        order.setOrderType(fsPackage.getProductType());
        order.setTotalNum(totalNum);
        order.setTotalPrice(totalPrice);
        order.setPayPrice(packageOrder.getPayPrice());
        order.setPayMoney(packageOrder.getPayMoney());
        order.setIsPay(1);
        order.setItemJson(JSONUtil.toJsonStr(items));
        order.setPayTime(new Date());

        if (packageOrder.getCycle()>=followRate){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, followRate);
            order.setFollowTime(calendar.getTime());
            order.setCycle(packageOrder.getCycle());
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(new Date());
            calendar2.add(Calendar.DAY_OF_MONTH, 30+packageOrder.getCycle());
            order.setFollowEndTime(calendar2.getTime());
            order.setFollowStatus(0);
        }

        if(fsStoreOrderMapper.insertFsStoreOrder(order)>0){
            if (packageOrder.getCycle()>=followRate){
                FsFollow fsFollow = new FsFollow();
                fsFollow.setTempId(FollowTempId+0L);
                fsFollow.setPatientPhone(order.getUserPhone());
                if (packageOrder.getPatientJson()!=null&&packageOrder.getPatientJson()!=""){
                FsPackagePatientDTO patJson = JSON.parseObject(packageOrder.getPatientJson(),FsPackagePatientDTO.class);
                fsFollow.setPatientName(patJson.getPatientName());
                fsFollow.setPatientId(patJson.getPatientId()+0L);
                }
                fsFollow.setUserId(packageOrder.getUserId());
                fsFollow.setDoctorId(order.getFollowDoctorId());
                fsFollow.setTotalNum(1);
                fsFollow.setStoreOrderId(order.getOrderId());
                fsFollow.setCompanyId(packageOrder.getCompanyId());
                fsFollow.setCompanyUserId(packageOrder.getCompanyUserId());
                fsFollow.setDeptId(packageOrder.getDeptId());
                fsFollow.setNum(1);
//            fsFollow.setPackageOrderId(order.getOrderId());
                fsFollow.setInquiryOrderId(packageOrder.getInquiryOrderId());
                fsFollow.setPlanTime(DateUtils.getNowDate());
                fsFollow.setPushStatus(1);
                fsFollow.setWriteStatus(0);
                FsFollowTemp fsFollowTemp = fsFollowTempMapper.selectFsFollowTempByTempId(FollowTempId+0L);
                fsFollow.setFormJson(fsFollowTemp.getFormJson());
                fsFollow.setCreateTime(DateUtils.getNowDate());
                int i = fsFollowMapper.insertFsFollow(fsFollow);
                TemplateBean templateBean = TemplateBean.builder()
                        .followId(fsFollow.getFollowId().toString())
                        .orderId(order.getOrderId().toString())
                        .title("您收到一个随访单")
                        .remark("您有一个随访单待填写")
                        .uid(order.getUserId())
                        .templateType(TemplateListenEnum.TYPE_4.getValue())
                        .build();
                publisher.publishEvent(new TemplateEvent(this, templateBean));
               }
            if (order.getOrderId()==null){
                throw new CustomException("订单id为空"+order);
            }
            fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.CREATE_ORDER.getValue(),
                    FsStoreOrderLogEnum.CREATE_ORDER.getDesc());
            fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.PAY_ORDER_SUCCESS.getValue(),
                    FsStoreOrderLogEnum.PAY_ORDER_SUCCESS.getDesc());

            fsPackageOrder.setOrderId(packageOrder.getOrderId());
            fsPackageOrder.setStoreOrderId(order.getOrderId());
            fsPackageOrder.setDoctorId(packageOrder.getDoctorId());
            fsPackageOrderMapper.updateFsPackageOrder(fsPackageOrder);

            if (prescribeId!=null){
                FsPrescribe fsPrescribe = new FsPrescribe();
                fsPrescribe.setPrescribeId(prescribeId);
                fsPrescribe.setStoreOrderId(order.getOrderId());
                fsPrescribeService.updateFsPrescribe(fsPrescribe);
            }

            for(FsStoreOrderItem item:items){
                item.setOrderId(order.getOrderId());
                fsStoreOrderItemMapper.insertFsStoreOrderItem(item);
            }
            if (noTui){
                FsStoreOrder fsStoreOrder = new FsStoreOrder();
                fsStoreOrder.setOrderId(order.getOrderId());
                fsStoreOrder.setExtendOrderId("XN");
                fsStoreOrderMapper.updateFsStoreOrder(fsStoreOrder);
            }
            FsUser fsUser = fsUserService.selectFsUserByUserId(order.getUserId());
            if (fsUser.getIsBuy()==null||fsUser.getIsBuy()==0){
                FsUser u = new FsUser();
                u.setUserId(order.getUserId());
                u.setIsBuy(1);
                fsUserService.updateFsUser(u);
            }


            try {
                storeSubOrderService.insertFsStoreSubOrderByStoreOrder(order.getOrderId());
            }catch (Exception e){
                logger.info("拆分订单错误："+order.getOrderId());
            }
//            try {
//                if (fsPackage.getProductType()==2){
//                    fsStoreOrderService.tuiOrder(order.getOrderId());
//                }else if (fsPackage.getProductType()==1){
//                    fsStoreOrderService.createOmsOrder(order.getOrderId());
//                }else {
//
//                }
//
//            } catch (ParseException e) {
//                throw new RuntimeException(e);
//            }
//            tuiOrderUtil.TuiOrderByPackage(order);
        }

        return R.ok();
    }

    @SuppressWarnings("all")
    @Override
    public String importSroreOrder(List<FsStoreProductDeliverExcelVO> list,Long storeId,Long companyId) {
        if (com.fs.common.utils.StringUtils.isNull(list) || list.size() == 0)
        {
            throw new ServiceException("导入商品数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (FsStoreProductDeliverExcelVO vo : list)
        {
            try
            {
                FsStoreOrder o = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(vo.getOrderCode());
                if (storeId!=null){
                    if (o.getStoreId()!=storeId){
                        throw new CustomException("不是本店铺订单");
                    }
                }

                if (companyId!=null){
                    if (o.getCompanyId()!=companyId){
                        throw new CustomException("不是本公司订单");
                    }
                }
                if (o.getStatus()!=2){
                    throw new CustomException("订单状态不为待发货");
                }
                // 判断每个字段是否为null或为空字符串
                if (vo.getOrderCode() == null || vo.getOrderCode().isEmpty()) {
                    throw new CustomException("订单编号为空");
                }

//                if (vo.getDeliveryCode() == null || vo.getDeliveryCode().isEmpty()) {
//                    throw new CustomException("快递公司编号为空");
//                }

                if (vo.getDeliveryName() == null || vo.getDeliveryName().isEmpty()) {
                    throw new CustomException("快递名称为空");
                }

                if (vo.getDeliverySn() == null || vo.getDeliverySn().isEmpty()) {
                    throw new CustomException("快递单号为空");
                }
                FsStoreOrder fsStoreOrder = new FsStoreOrder();

                fsStoreOrder.setDeliverySn(vo.getDeliverySn());
                fsStoreOrder.setDeliveryName(vo.getDeliveryName());
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                fsStoreOrder.setDeliveryTime(formatter.format(new Date()));
                fsStoreOrder.setDeliveryCode(vo.getDeliveryCode());

                fsStoreOrder.setOrderCode(vo.getOrderCode());
                fsStoreOrder.setStatus(3);
                if (o.getCompanyId()!=null){
                    companyService.subtractCompanyMoney(o);
                }
                FsStore store = fsStoreMapper.selectFsStoreByStoreId(o.getStoreId());
                int i = fsStoreOrderMapper.updateFsStoreOrderByOrderCode(fsStoreOrder);
                String lastFourNumber = "";
                if (fsStoreOrder.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
                    if (store.getSendPhone()!=null){
                        lastFourNumber = store.getSendPhone();
                    }else {
                        lastFourNumber = o.getUserPhone();
                    }
                    if (lastFourNumber.length() == 11) {
                        lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
                    }
                }
                expressService.subscribeEspress(o.getOrderCode(),fsStoreOrder.getDeliveryCode(),fsStoreOrder.getDeliverySn(),lastFourNumber);

                try {
                    String s = fsPrescribeService.PrescribeImg(o.getPrescribeId());
                }catch (Exception e){

                }

                successNum++;
                successMsg.append("<br/>" + successNum + "、订单编号 " + vo.getOrderCode() + " 导入成功");

            }
            catch (Exception e)
            {

                failureNum++;
                String msg = "<br/>" + failureNum + "、订单编号 " + vo.getOrderCode()  + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public FsStoreOrderVO selectFsStoreOrderByOrderIdVO(Long orderId) {
        return fsStoreOrderMapper.selectFsStoreOrderByOrderIdVO(orderId);
    }

    @Override
    public List<FsStorePayment> selectFsStorePaymentByOrderId(Long orderId) {
        FsStoreOrder fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderByOrderId(orderId);
        if (fsStoreOrder.getPackageOrderId()==null){
            return fsStorePaymentMapper.selectFsStorePaymentByOrderId(orderId);
        }else {
            return  fsStorePaymentMapper.selectFsStorePaymentByPay(3,fsStoreOrder.getPackageOrderId());

        }
    }





    @Override
    public int tuiOrder(Long orderId) {

        CreateOrderParam op = new CreateOrderParam();

        FsStoreOrder o = fsStoreOrderMapper.selectFsStoreOrderByOrderId(orderId);

        if ( o.getStatus()!=2) {
            throw new CustomException("订单状态不为代发货");
        }
        if (o.getUserAddress()==null||o.getUserAddress()==""){
            throw new CustomException("用户收货地址为空");
        }
        if (o.getUserPhone()==null||o.getUserPhone()==""){
            throw new CustomException("用户收货电话为空");
        }
        FsPrescribeVO fp = prescribeMapper.selectFsPrescribeByPrescribeIdVO(o.getPrescribeId());

        String s = fsPrescribeService.PrescribeImg(fp.getPrescribeId());

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

        FsInquiryOrderVO io = fsInquiryOrderMapper.selectFsInquiryOrderVOByOrderId(fp.getInquiryOrderId());

        FsStoreOrderItem item = new FsStoreOrderItem();
        item.setOrderId(o.getOrderId());
        List<FsStoreOrderItem> fsStoreOrderItems = fsStoreOrderItemMapper.selectFsStoreOrderItemList(item);
        logger.info(""+fsStoreOrderItems);
        ArrayList<RecipeDetailParam> list = new ArrayList<>();
        Integer i=1;
        BigDecimal dprice = new BigDecimal(0);
        for (FsStoreOrderItem fsStoreOrderItem : fsStoreOrderItems) {

            RecipeDetailParam p = new RecipeDetailParam();
            String json = fsStoreOrderItem.getJsonInfo();
            FsProdItemDTO fsProdItemDTO = JSON.parseObject(json, FsProdItemDTO.class);
            String barCode = fsProdItemDTO.getBarCode();

            logger.info(""+fsProdItemDTO);
            if(fsStoreOrderItem.getIsGift()!=null&&fsStoreOrderItem.getIsGift()==1){
                continue;
            }
            if (barCode.equals("106013")){
                continue;
            }

            String barCodeTrim = barCode.replaceAll("[^a-zA-Z0-9]", "");;
            p.setGranule_his(barCodeTrim);
            p.setGranule_name(new JSONObject(json).getString("productName"));
            BigDecimal price = new JSONObject(json).getBigDecimal("price");
            p.setGranule_price(price.toString());
            BigDecimal counts = new JSONObject(json).getBigDecimal("num");
            p.setHerb_dose(counts.toString());
            p.setGranule_no(i.toString());
            list.add(p);
            i++;
             dprice = dprice.add(price.multiply(counts));
        }

        op.setRecipe_name(fp.getPrescribeCode());

        op.setBirthday(fp.getPatientBirthday());
        op.setName(fp.getPatientName());
        op.setSex(fp.getPatientGender().equals("1")?"男":"女");
        op.setAge(Integer.parseInt(fp.getPatientAge()));
        if (o.getUserPhone().length()>11){
            op.setPhone(decryptPhone(o.getUserPhone()));
        }else {
            op.setPhone(o.getUserPhone());
        }

        if (io!=null){
            op.setDepartment(io.getDeptName());
        }
        op.setDoctor(fp.getDoctorName());
        op.setRecipe_no(usage.getCounts().intValue());//处方副数
        op.setGranule_total_no(i-1);
        String usageFrequencyUnit = usage.getUsageFrequencyUnit();
        int dayNum = 2;
        if (usageFrequencyUnit!=null){
            if (usageFrequencyUnit.equals("每日一次")) {
                dayNum = 1;
            } else if (usageFrequencyUnit.equals("每日二次")) {
                dayNum = 2;
            } else if (usageFrequencyUnit.equals("每日三次")) {
                dayNum = 3;
            } else if (usageFrequencyUnit.equals("每日四次")) {
                dayNum = 4;
            }
        }

        if (fp.getRecipeType()!=null){
            op.setRecipe_type(fp.getRecipeType());
        }
        op.setTimes_day(dayNum);
        op.setFactor(0);
        String remark = usage.getRemark();
        if (remark!=null&&remark.length()>50){
                remark = remark.substring(0, 40);
        }

        op.setAttention(remark);//医嘱
        op.setSymptoms(fp.getDiagnose());
        op.setRecipe_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(fp.getCreateTime()));
//        op.setOperation_time("Jane");
//        op.setOperation_time("2023-08-22 11:00:00");
//        op.setPricing_id("pricing123");
//        op.setPricing_cashier("Alice");
//        op.setPricing_time("2023-08-22 12:00:00");
        op.setPrice(dprice.toString());
        op.setPrice_total(dprice.multiply(new BigDecimal(usage.getCounts())).toString());
        op.setRecipe_sale_price(o.getPayMoney().toString()); //实际收款
        op.setPayment_type("1");
        op.setPayment_status("PAYED");
        op.setRecipe_source("HIS");
        op.setMachine_name("");
        op.setRecipe_status("NEW");
        op.setDescription(s);
        if (fp.getPatientId()!=null){
            op.setPatient_id(fp.getPatientId().toString());
        }

        //op.setVisit_id("visit789");
     //   op.setUsage_desc("备用字段描述");
        op.setAddress(o.getUserAddress());
       // op.setRefund_name("");
        op.setRecipe_detail_list(list);
        ApiResponse order = hisApiService.createOrder(op);
        if (order.getState().equals("error")){
            throw new CustomException(order.getMsg());
        }
        FsStoreOrder fso = new FsStoreOrder();
        fso.setOrderId(o.getOrderId());
        fso.setExtendOrderId("HIS");
        fsStoreOrderMapper.updateFsStoreOrder(fso);

        return 1;
    }
    @Autowired
    IFsPrescribeService fsPrescribeService;
    @Override
    public FsPrescribeVO selectFsPrescribeByPrescribeIdVO(Long prescribeId) {
        return  prescribeMapper.selectFsPrescribeByPrescribeIdVO(prescribeId);
    }

    @Override
    public List<FsStoreOrderSVO> selectFsStoreOrderListSVO(FsStoreOrderListSParam fsStoreOrder) {
            return fsStoreOrderMapper.selectFsStoreOrderListSVO(fsStoreOrder);
    }

    @Override
    public R computeOrder(FsStoreOrderComputeParam param) {
        FsStoreOrder order=fsStoreOrderMapper.selectFsStoreOrderByOrderId(param.getOrderId());
        if(order==null){
            return R.error("订单不存在");
        }
        if(order.getStatus()!= FsStoreOrderStatusEnum.STATUS_1.getValue()){
            return R.error("订单状态不正确");
        }

        FsUser user=userService.selectFsUserByUserId(order.getUserId());
        Map<String,BigDecimal> data=new HashMap<>();
        if(user!=null&& StringUtils.isNotEmpty(user.getMaOpenId())){
            if(param.getUserCouponId()!=null&&param.getUserCouponId()>0l){
                FsUserCoupon userCoupon=userCouponService.selectFsUserCouponById(param.getUserCouponId());
                if(userCoupon==null){
                    return R.error("优惠券不存在");
                }
                if(userCoupon.getStatus()!=0){
                    return R.error("优惠券已过期或已使用");
                }
                FsCoupon coupon=couponService.selectFsCouponByCouponId(userCoupon.getCouponId());
                if(coupon.getCouponType().equals(1)){
                    if(coupon.getMinPrice().compareTo(order.getPayPrice())==1){
                        return R.error("此优惠券不可用");
                    }
                    if(coupon.getPrice().compareTo(order.getPayPrice())>=0){
                        data.put("payMoney",new BigDecimal(0));
                        data.put("discountMoney",coupon.getPrice());
                    }
                    else{
                        data.put("payMoney",order.getPayPrice().subtract(coupon.getPrice()));
                        data.put("discountMoney",coupon.getPrice());

                    }
                }
                else if(coupon.getCouponType().equals(2)){
                    data.put("payMoney",new BigDecimal(0));
                    data.put("discountMoney",order.getPayPrice());
                }
                else if(coupon.getCouponType().equals(3)){
                    return R.error("此优惠券不可用于问诊订单");

                }

                else if(coupon.getCouponType().equals(4)){
                    BigDecimal payMoney = order.getPayPrice().multiply(coupon.getRate()).divide(new BigDecimal(100));
                    data.put("payMoney",payMoney);
                    data.put("discountMoney",coupon.getPrice().subtract(payMoney));
                }
            }
            else{
                data.put("payMoney",order.getPayPrice());
                data.put("discountMoney",new BigDecimal(0));
            }
            return R.ok().put("data",data);

        }
        else{
            return R.error("用户OPENID不存在");
        }
    }



    @Override
    @Transactional
    @Synchronized
    public R payOrder(FsStoreOrderPayParam param) {
        FsStoreOrder order=fsStoreOrderMapper.selectFsStoreOrderByOrderId(param.getOrderId());
        if(order==null){
            return R.error("订单不存在");
        }
        if(order.getStatus()!= FsStoreOrderStatusEnum.STATUS_1.getValue()){
            return R.error("订单状态不正确");
        }
        FsStoreOrder storeOrder=new FsStoreOrder();
        storeOrder.setOrderId(param.getOrderId());
        if(StringUtils.isEmpty(order.getUserName())){
            if(param.getAddressId()!=null&&param.getAddressId()>0){
                FsUserAddress address=userAddressService.selectFsUserAddressByAddressId(param.getAddressId());
                if(address!=null){
                    storeOrder.setUserName(address.getRealName().trim());
                    storeOrder.setUserPhone(address.getPhone().trim());
                    storeOrder.setUserAddress(address.getProvince()+" "+address.getCity()+" "+address.getDistrict()+" "+address.getDetail());
//                    String noAdd="南通市,镇江市,淮安市,江阴市,金华市,驻马店市";
//                    String[] split = noAdd.split(",");
//                    for (String s : split) {
//                        if (s.equals(address.getCity())){
//                            return R.error("此地区暂不支持配送");
//                        }
//                    }
//                    if ("民权县".equals(address.getDistrict())){
//                        return R.error("此地区暂不支持配送");
//                    }
                }
            }
            else{
                return R.error("收货地址不能为空");
            }

        }
        else{
            if(param.getAddressId()!=null&&param.getAddressId()>0){
                FsUserAddress address=userAddressService.selectFsUserAddressByAddressId(param.getAddressId());
                if(address!=null){
                    storeOrder.setUserName(address.getRealName().trim());
                    storeOrder.setUserPhone(address.getPhone().trim());
                    storeOrder.setUserAddress(address.getProvince()+address.getCity()+address.getDistrict()+address.getDetail());

                }
            }
        }

        if(StringUtils.isNotEmpty(param.getRemark())){
            storeOrder.setRemark(param.getRemark());
        }
        //获取支付金额
        BigDecimal payMoney=new BigDecimal(0);
        BigDecimal discountMoney=new BigDecimal(0);
        if(storeOrder.getUserCouponId()!=null&&storeOrder.getUserCouponId()>0){
            //已经选择了优惠券，不做处理
        }
        else{
            if(param.getUserCouponId()!=null&&param.getUserCouponId()>0l){
                FsUserCoupon userCoupon=userCouponService.selectFsUserCouponById(param.getUserCouponId());
                if(userCoupon==null){
                    return R.error("优惠券不存在");
                }
                if(userCoupon.getStatus()!=0){
                    return R.error("优惠券已过期或已使用");
                }
                FsCoupon coupon=couponService.selectFsCouponByCouponId(userCoupon.getCouponId());
                if(coupon.getCouponType().equals(1)){
                    if(coupon.getMinPrice().compareTo(order.getPayPrice())==1){
                        return R.error("此优惠券不可用");
                    }
                    if(coupon.getPrice().compareTo(order.getPayPrice())>=0){
                        payMoney=new BigDecimal(0);
                        discountMoney=coupon.getPrice();
                    }
                    else{
                        payMoney=order.getPayPrice().subtract(coupon.getPrice());
                        discountMoney=coupon.getPrice();

                    }
                }
                else if(coupon.getCouponType().equals(2)){
                    payMoney=new BigDecimal(0);
                    discountMoney=order.getPayPrice();
                }
                else if(coupon.getCouponType().equals(3)){
                    return R.error("此优惠券不可用于问诊订单");

                }
                else if(coupon.getCouponType().equals(4)){
                    payMoney = order.getPayPrice().multiply(coupon.getRate()).divide(new BigDecimal(100));
                    discountMoney=coupon.getPrice().subtract(payMoney);
                }
                storeOrder.setUserCouponId(param.getUserCouponId());
                userCoupon.setUseTime(new Date());
                userCoupon.setBusinessId(order.getOrderId());
                userCoupon.setBusinessType(2);
                userCoupon.setStatus(1);
                userCouponService.updateFsUserCoupon(userCoupon);
            }
            else{
                payMoney=order.getPayPrice();
                discountMoney=new BigDecimal(0);
            }
            storeOrder.setPayMoney(payMoney);
            storeOrder.setDiscountMoney(discountMoney);

        }
        fsStoreOrderMapper.updateFsStoreOrder(storeOrder);

        return R.ok();

    }

    @Override
    public List<com.alibaba.fastjson.JSONObject> selectFsStoreOrderCounts(Map<String, Object> toMap) {
        return fsStoreOrderMapper.selectFsStoreOrderCounts(toMap);
    }

    @Override
    public List<FsStoreOrderStatisticsVO> selectFsStoreOrderStatisticsList(FsStoreStatisticsParam param) {
        return fsStoreOrderMapper.selectFsStoreOrderStatisticsList(param);
    }

    @Override
    public List<FsStoreOrderVO> selectFsStoreOrderCusListVO(FsStoreOrderParam param) {
        return fsStoreOrderMapper.selectFsStoreOrderCusListVO(param);
    }

    @Override
    public List<FsStoreOrderListDVO> selectFsStoreOrderListDVO(FsStoreOrderListDParam param) {
        List<FsStoreOrderListDVO> list=fsStoreOrderMapper.selectFsStoreOrderListDVO(param);
        return  list;
    }


    @Override
    public List<FsStoreOrderExcelVO> selectFsStoreOrderExcelListVO(FsStoreOrderParam fsStoreOrder) {
        List<FsStoreOrderExcelVO> fsStoreOrderVOS = fsStoreOrderMapper.selectFsStoreOrderExcelListVO(fsStoreOrder);

               for (FsStoreOrderExcelVO vo : fsStoreOrderVOS) {
                   if (vo.getUserPhone() != null) {
                       vo.setUserPhone(vo.getUserPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                   }
                   if (vo.getUserAddress() != null) {
                       vo.setUserAddress(ParseUtils.parseAddress(vo.getUserAddress()));
                   }
                   vo.setProductName(vo.getPackageSecondName());
                   int count=1;
                   if (vo.getCycle()!=null){
                       count= vo.getCycle() / 6;
                       if (count==0){
                           count=1;
                       }
                       vo.setFollowNum(count);
                   }
                   BigDecimal money = new BigDecimal(count * 300);
                   vo.setInquiryMoney(money);
                   if (vo.getTotalCostMoney()==null){
                       if (vo.getCostPrice()!=null){
                            vo.setTotalCostMoney(vo.getCostPrice());
                       }else {
                           vo.setTotalCostMoney(new BigDecimal("0"));
                       }
                   }

                   vo.setTotalMoney(vo.getInquiryMoney().add(vo.getTotalCostMoney()));
                   vo.setInquiryDiscountMoney(vo.getTotalMoney().subtract(vo.getPrescribePrice()));


               }
        return fsStoreOrderVOS;
    }
    @Override
    @Transactional
    public R payConfirm(String orderCode,String payCode, String tradeNo,String payType,Integer type) {
        try {
            FsStoreOrder order=null;
            if(type.equals(1)){

                FsStorePayment storePayment = fsStorePaymentMapper.selectFsStorePaymentByPaymentCode(payCode);
                if (storePayment!=null){
                    if(storePayment.getStatus().equals(0)){
                        logger.info(payCode+"待支付");
                        FsStorePayment paymentMap=new FsStorePayment();
                        paymentMap.setPaymentId(storePayment.getPaymentId());
                        paymentMap.setStatus(1);
                        paymentMap.setPayTime(new Date());
                        paymentMap.setTradeNo(tradeNo);
                        if(payType.equals(PayType.微信小程序支付.getCode())){
                            paymentMap.setPayTypeCode(PayType.微信小程序支付.name());
                        }
                        else if(payType.equals(PayType.支付宝条码支付.getCode())){
                            paymentMap.setPayTypeCode(PayType.支付宝条码支付.name());
                        }
                        if (storePayment.getPayMode().equals("yb")){
                            OrderQueryDTO orderQueryDTO = new OrderQueryDTO();
                            orderQueryDTO.setUpOrderId(tradeNo);
                            OrderResult orderResult = ybPayService.getOrder(orderQueryDTO);
                            paymentMap.setBankSerialNo(orderResult.getBankOrderId());
                            paymentMap.setBankTransactionId(orderResult.getBankTrxId());
                        }
                        fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                        logger.info(payCode+"已支付");
                        order=fsStoreOrderMapper.selectFsStoreOrderByOrderId(Long.parseLong(storePayment.getBusinessId()));
                    }
                }
                else{
                    logger.info(payCode+"支付单号不存在");
                    return R.error("支付单号不存在");
                }
            }
            else if(type.equals(2)){
                order=fsStoreOrderMapper.selectFsStoreOrderByOrderCode(orderCode);
            }
            if(order!=null&&!order.getStatus().equals(FsStoreOrderStatusEnum.STATUS_1.getValue())){
                logger.info(payCode+"订单号不为待支付回退");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error();
            }
            if(order!=null&&!order.getIsPay().equals(0)){
                logger.info(payCode+"订单号支付不为待支付回退");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error();
            }
            fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.PAY_ORDER_SUCCESS.getValue(),
            FsStoreOrderLogEnum.PAY_ORDER_SUCCESS.getDesc());
            FsStoreOrder storeOrder = new FsStoreOrder();
            storeOrder.setOrderId(order.getOrderId());
            storeOrder.setIsPay(1);
            storeOrder.setStatus(2);
            storeOrder.setPrescribePrice(order.getTotalPrice());
            SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.store");
            Map<String, Object> config = (Map<String, Object>) JSON.parse(sysConfig.getConfigValue());
            Integer followRate = (Integer)config.get("followRate");


            Long followDoctorId = fsPackageOrderMapper.selectFsPackageOrderByUserId(order.getUserId());
             if (followDoctorId!=null&&followDoctorId>0){
                 storeOrder.setFollowDoctorId(followDoctorId);
             }else {
                 storeOrder.setFollowDoctorId(iFsDoctorService.selectFollowDoctorDoctorByPackage());
            }
                if (order.getCycle()>=followRate){
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    calendar.add(Calendar.DAY_OF_MONTH, followRate);
                    storeOrder.setFollowTime(calendar.getTime());
                }
            storeOrder.setPayTime(new Date());
            fsStoreOrderMapper.updateFsStoreOrder(storeOrder);
            //更新优惠券状态
            if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
                FsUserCoupon userCoupon=userCouponService.selectFsUserCouponById(order.getUserCouponId());
                if(userCoupon!=null&&userCoupon.getStatus().equals(0)){
                    userCoupon.setUseTime(new Date());
                    userCoupon.setBusinessId(order.getOrderId());
                    userCoupon.setBusinessType(2);
                    userCoupon.setStatus(1);
                    userCouponService.updateFsUserCoupon(userCoupon);
                }
            }
            return R.ok();
        }catch (Exception e){
            logger.info(payCode+"异常了"+e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            FsStorePaymentError err = new FsStorePaymentError();
            err.setOrderNo(orderCode);
            err.setOrderFlowNo(tradeNo);
            err.setStatus(0);
            err.setMsg(e.getMessage());
            err.setCreateTime(DateUtils.getNowDate());
            fsStorePaymentErrorMapper.insertFsStorePaymentError(err);
            return R.error();
        }
    }
    @Override
    public Long selectFsStoreOrderTotalCount(int type,Long companyId) {
        return fsStoreOrderMapper.selectFsStoreOrderTotalCount(type,companyId);
    }

    @Override
    public void deliveryOrder(String orderCode,String deliveryId,String deliverCode,String deliverName) {
        FsStoreOrder order= fsStoreOrderMapper.selectFsStoreOrderByOrderCode(orderCode);
        if(order!=null&&order.getStatus()==2){
            FsExpress express=expressService.selectFsExpressByOmsCode(deliverCode);
            if(express!=null){
                order.setDeliveryName(deliverName);
                order.setDeliveryCode(express.getCode());
            }
            order.setStatus(3);
            order.setDeliverySn(deliveryId);
            order.setDeliverySendTime(DateUtils.getNowDate());
            fsStoreOrderMapper.updateFsStoreOrder(order);
            fsStoreOrderLogsService.create(order.getOrderId(),  FsStoreOrderLogEnum.DELIVERY_GOODS.getValue(),FsStoreOrderLogEnum.DELIVERY_GOODS.getDesc());
            if (order.getCompanyId()!=null&&order.getCompanyId()>0){
                companyService.subtractCompanyMoney(order);
            }

            FsStore store = fsStoreMapper.selectFsStoreByStoreId(order.getStoreId());
            //订阅物流回调
            String lastFourNumber = "";
            if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
                if (store!=null&&store.getSendPhone()!=null){
                    lastFourNumber = store.getSendPhone();
                }else {
                    lastFourNumber = order.getUserPhone();
                }
                if (lastFourNumber.length() == 11) {
                    lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
                }
            }
            expressService.subscribeEspress(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);


        }

    }

    @Override
    @Transactional
    public int afterSales(FsStoreOrderSalesParam fsStoreOrderSalesParam) {
        FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderId(fsStoreOrderSalesParam.getOrderId());
        if (order.getStatus()<0){
            throw new CustomException("订单不可提交售后");
        }
        FsStoreAfterSales fsStoreAfterSales = new FsStoreAfterSales();
        fsStoreAfterSales.setOrderId(order.getOrderId());
        fsStoreAfterSales.setStoreId(order.getStoreId());
        fsStoreAfterSales.setRefundAmount(order.getPayMoney());
        fsStoreAfterSales.setCreateTime(DateUtils.getNowDate());
        if (order.getStatus()==2||order.getStatus()==3){
            fsStoreAfterSales.setRefundType(0);
        }
        if(order.getStatus()==4){
            FsStore fsStore = fsStoreMapper.selectFsStoreByStoreId(order.getStoreId());
            fsStoreAfterSales.setRefundType(1);
            fsStoreAfterSales.setPhoneNumber(fsStore.getRefundPhone());
            fsStoreAfterSales.setAddress(fsStore.getRefundAddress());
            fsStoreAfterSales.setConsignee(fsStore.getRefundConsignee());
        }
        fsStoreAfterSales.setStatus(0);
        fsStoreAfterSales.setDeptId(order.getDeptId());
        fsStoreAfterSales.setSalesStatus(0);
        fsStoreAfterSales.setOrderStatus(order.getStatus());
        fsStoreAfterSales.setUserId(order.getUserId());
        fsStoreAfterSales.setCompanyId(order.getCompanyId());
        fsStoreAfterSales.setCompanyUserId(order.getCompanyUserId());
        fsStoreAfterSales.setIsDel(0);
        fsStoreAfterSalesService.insertFsStoreAfterSales(fsStoreAfterSales);
        List<FsStoreOrderItem> fsStoreOrderItems = fsStoreOrderItemMapper.selectFsStoreOrderItemListByOrderId(order.getOrderId());
        for (FsStoreOrderItem fsStoreOrderItem : fsStoreOrderItems) {
            FsStoreAfterSalesItem item = new FsStoreAfterSalesItem();
            item.setAfterSalesId(fsStoreAfterSales.getId());
            item.setProductId(fsStoreOrderItem.getProductId());
            item.setJsonInfo(fsStoreOrderItem.getJsonInfo());
           fsStoreAfterSalesItemMapper.insertFsStoreAfterSalesItem(item);
        }
        //增加操作日志
        FsStoreAfterSalesLogs logs = new FsStoreAfterSalesLogs();
        logs.setChangeTime(new DateTime());
        logs.setChangeType(0);
        logs.setStoreAfterSalesId(fsStoreAfterSales.getId());
        logs.setOperator(fsStoreOrderSalesParam.getOperator());
        logs.setCompanyId(fsStoreOrderSalesParam.getCompanyId());
        logs.setChangeMessage("平台提交售后");
        fsStoreAfterSalesLogsMapper.insertFsStoreAfterSalesLogs(logs);
        //管易作废
        if(StringUtils.isNotEmpty(order.getExtendOrderId())){
            if (!order.getExtendOrderId().equals("HIS")){
                ErpRefundUpdateRequest request=new ErpRefundUpdateRequest();
                request.setTid(order.getOrderCode());
                request.setOid(order.getOrderCode());
                request.setRefund_state(1);
                erpOrderService.refundUpdate(request);
            }
        }
        order.setStatus(-1);
        order.setRefundStatus(1+"");
        fsStoreOrderMapper.updateFsStoreOrder(order);
        if (order.getPackageOrderId()!=null){
            FsPackageOrder fsPackageOrder = fsPackageOrderMapper.selectFsPackageOrderByOrderId(order.getPackageOrderId());
            fsPackageOrder.setRefundStatus(1);
            fsPackageOrderMapper.updateFsPackageOrder(fsPackageOrder);
        }
        return 1;
    }

    @Override
    public void createOmsOrder(Long orderId) throws ParseException {
        FsStoreOrder order=fsStoreOrderMapper.selectFsStoreOrderByOrderId(orderId);
        if(order!=null&&StringUtils.isEmpty(order.getExtendOrderId())&&order.getStatus()!=2){
            return;
        }
        if (order==null){
            return;
        }
        ErpOrder erpOrder=new ErpOrder();
        if (order.getCompanyId()!=null){
            erpOrder.setVip_code(order.getUserId().toString()+order.getCompanyId().toString());
        }else {
            erpOrder.setVip_code(order.getUserId().toString());
        }
        erpOrder.setPlatform_code(order.getOrderCode());
//        if(order.getStoreHouseCode()==null){
//            erpOrder.setWarehouse_code("CQDS001");
//        }else{
//            erpOrder.setWarehouse_code(order.getStoreHouseCode());
//        }
        FsSysConfig sysConfig = configUtil.getSysConfig();
        erpOrder.setShop_code(sysConfig.getErpShopCode());
        erpOrder.setSeller_memo(order.getRemark());
        List<ErpOrderPayment> payments=new ArrayList<>();
        ErpOrderPayment payment=new ErpOrderPayment();
        payment.setPay_type_code("weixin");
        payment.setPayment(order.getPayMoney().doubleValue());
        if(order.getPayTime()!=null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String timeString = sdf.format(order.getPayTime());
            Date date = sdf.parse(timeString); // 时间格式转为时间戳
            long timeLong = date.getTime();
            payment.setPaytime(new Timestamp(timeLong));
        }
        payments.add(payment);


        //物流代收都发 互联网医院顺丰
        if (order.getPayRemain().compareTo(new BigDecimal(0)) == 0) {
            //没有物流代收
            //大于100发发顺丰云配
            if(order.getPayMoney().compareTo(new BigDecimal(100))>0){
                //发互联网医院SF.0235488558_241101
                FsExpress express=expressService.selectFsExpressByOmsCode("SF.0235488558_241101");
                erpOrder.setExpress_code(express.getOmsCode());
                order.setDeliveryName(express.getName());
                order.setDeliveryCode(express.getCode());
            }else {
                //发ztpdd
                FsExpress express=expressService.selectFsExpressByOmsCode("CDYJFYD.400011111705_241230");
                erpOrder.setExpress_code(express.getOmsCode());
                order.setDeliveryName(express.getName());
                order.setDeliveryCode(express.getCode());
                }
        } else {
            FsExpress express = new FsExpress();
            if (order.getCompanyId()!=null){
                Company company = companyService.selectCompanyById(order.getCompanyId());
                if (company != null && StringUtils.isNotEmpty(company.getOmsCode())){
                    express = expressService.selectFsExpressByOmsCode(company.getOmsCode());
                }else {
                    express=expressService.selectFsExpressByOmsCode("SF.0235469535");
                }
            }else {
                express=expressService.selectFsExpressByOmsCode("SF.0235469535");
            }
                //物流代发互联网医院顺
                erpOrder.setExpress_code(express.getOmsCode());
                order.setDeliveryName(express.getName());
                order.setDeliveryCode(express.getCode());
                //物流代收金额
                ErpOrderPayment codPayment = new ErpOrderPayment();
                codPayment.setPay_type_code("cod");
                BigDecimal toal = order.getPayRemain();
                codPayment.setPayment(toal.doubleValue());
                payments.add(codPayment);
                erpOrder.setCod(true);

            }

        erpOrder.setPayments(payments);
        if(order.getCompanyId()!=null){
            Company company=companyService.selectCompanyById(order.getCompanyId());
            if(company!=null){
                erpOrder.setSeller_memo(company.getCompanyName());
            }
        }
        if(order.getCompanyUserId()!=null){
            CompanyUser companyUser=companyUserService.selectCompanyUserById(order.getCompanyUserId());
            if(companyUser!=null){
                CompanyDept dept=companyDeptService.selectCompanyDeptById(companyUser.getDeptId());
                if(dept!=null){
                    List<String> names=companyDeptService.selectCompanyDeptNamesByIds(dept.getAncestors());
                    if(names!=null&&names.size()>0){
                        //写备注
                        erpOrder.setSeller_memo(erpOrder.getSeller_memo()+"-"+StringUtils.join(names, ",")+","+dept.getDeptName() );
                    }
                }
                erpOrder.setSeller_memo(erpOrder.getSeller_memo()+"-"+companyUser.getNickName());
            }
        }

        ErpRemarkDTO remarkDTO=new ErpRemarkDTO();
        remarkDTO.setTotalPrice(order.getTotalPrice());
        remarkDTO.setPayPrice(order.getPayPrice());
        remarkDTO.setDeliveryMoney(order.getPayDelivery());
        remarkDTO.setPayMoney(order.getPayMoney());
        remarkDTO.setCouponMoney(order.getDiscountMoney());
        remarkDTO.setOrderId(order.getOrderCode());
        remarkDTO.setYdMoney(order.getPayPrice().subtract(order.getPayMoney().subtract(order.getPayDelivery())));
        if(order.getPayTime()!=null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(order.getPayTime());
            remarkDTO.setPayTime(format);
        }
        erpOrder.setSeller_memo(erpOrder.getSeller_memo()+JSONUtil.toJsonStr(remarkDTO));
        erpOrder.setOrder_type_code("order");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        erpOrder.setDeal_datetime(sdf.format(new Date()));
        FsStoreOrderItem itemMap=new FsStoreOrderItem();
        itemMap.setOrderId(order.getOrderId());
        List<FsStoreOrderItem> orderItems=storeOrderItemService.selectFsStoreOrderItemList(itemMap);
        List<ErpOrderItem> details=new ArrayList<>();
        for(FsStoreOrderItem orderItem: orderItems){
            FsStoreCartDTO cartDTO= JSONUtil.toBean(orderItem.getJsonInfo(),FsStoreCartDTO.class);
                ErpOrderItem item=new ErpOrderItem();
                item.setItem_code(cartDTO.getBarCode().trim());
                item.setPrice(cartDTO.getPrice().toString());
                item.setQty(cartDTO.getNum());
                item.setRefund(0);
                details.add(item);
        }
        erpOrder.setDetails(details);
        erpOrder.setReceiver_name(order.getUserName().replaceAll("[^\\u4e00-\\u9fa5a-zA-Z0-9]", ""));
        if (order.getUserPhone().length()>11){
            String phone = decryptPhone(order.getUserPhone());
            erpOrder.setReceiver_mobile(phone);
        }else {
            erpOrder.setReceiver_mobile(order.getUserPhone());
        }

        String[] address=order.getUserAddress().split(" ");
        if (address.length<3){
            String kdnAddress = fsUserAddressService.getKdnAddress(order.getUserAddress());
            Map<String,Object> addDAta = (Map<String,Object>)JSON.parse(kdnAddress);
            Map<String, String> add = (Map<String, String>)addDAta.get("Data");
            erpOrder.setReceiver_province(add.get("ProvinceName"));
            erpOrder.setReceiver_city(add.get("CityName"));
            erpOrder.setReceiver_district(add.get("ExpAreaName"));
            erpOrder.setReceiver_address(add.get("StreetName")+add.get("Address"));
        }else {
            erpOrder.setReceiver_province(address[0]);
            erpOrder.setReceiver_city(address[1]);
            erpOrder.setReceiver_district(address[2]);
            //处理地址多空隔问题
            if(address.length>3){
                StringBuffer addrs=new StringBuffer();
                for(int i=3;i<address.length;i++){
                    addrs.append(address[i]);
                }
                erpOrder.setReceiver_address(addrs.toString());
            }
            else if(address.length==3){
                erpOrder.setReceiver_address(address[2]);
            }
        }
        erpOrder.setReceiver_address(erpOrder.getReceiver_address().replace("+","加"));
        erpOrder.setReceiver_address(erpOrder.getReceiver_address().replace("\n",""));

        // 处方图片生成
        String s = fsPrescribeService.PrescribeImg(order.getPrescribeId());
        erpOrder.setSeller_memo(erpOrder.getSeller_memo()+"||"+s+"||");
        ErpOrderResponse response= erpOrderService.addOrder(erpOrder);
        logger.info("ErpCreate:"+order.getOrderCode()+":"+JSONUtil.toJsonStr(response));
        if(response.getSuccess()){

            //支付成功后 将订单号写入待发货的REDIS中
            redisCache.setCacheObject("delivery"+":"+response.getCode(),order.getOrderCode());
            //写入外部订单号
            order.setExtendOrderId(response.getCode());
            fsStoreOrderMapper.updateFsStoreOrder(order);
        }else {
//            if (response.getErrorDesc().equals("该订单已创建")){
//                ErpOrderQueryRequert erpOrderQueryRequert = new ErpOrderQueryRequert();
//                erpOrderQueryRequert.setPlatform_code(order.getOrderCode());
//                ErpOrderQueryResponse erp = erpOrderService.getOrder(erpOrderQueryRequert);
//                logger.info("ErpCreate:"+order.getOrderCode()+":"+JSONUtil.toJsonStr(response));
//
//                if (erp.getOrders()!=null&&erp.getOrders().size()>0){
//                    ErpOrderQuery epr = erp.getOrders().get(0);
//                    redisCache.setCacheObject("delivery"+":"+epr.getCode(),order.getOrderCode());
//                    order.setExtendOrderId(epr.getCode());
//                    fsStoreOrderMapper.updateFsStoreOrder(order);
//                }
//            }
        }
        //写入日志


    }




    @Override
    public ExpressResultDTO updateDeliveryItem(ExpressNotifyDTO notifyDTO) {
        String data= URLDecoder.decode(notifyDTO.getRequestData(), Charset.forName("UTF-8"));
        //ExpressInfoDTO
        logger.info("快递根踪回调:"+data);
        FsSysConfig sysConfig = configUtil.getSysConfig();
        ExpressDataDTO expressDataDTO=JSONUtil.toBean(data,ExpressDataDTO.class);
        if(expressDataDTO!=null&&expressDataDTO.getData()!=null){
            for(ExpressInfoDTO dto:expressDataDTO.getData()){
                List<FsStoreOrder> orders=this.selectFsStoreOrderListByDeliveryId(dto.getLogisticCode());
                if(orders!=null){
                    for(FsStoreOrder order:orders){
                        logger.info("订单信息:"+JSONUtil.toJsonStr(order));
                        logger.info("运单号:"+dto.getLogisticCode());
                        if(order!=null && (order.getDeliveryStatus()==null||order.getDeliveryStatus()!=3)){
                            if (dto.getState()!=null&&dto.getStateEx()!=null){
                                FsStoreOrder map=new FsStoreOrder();
                                map.setDeliveryStatus(Integer.parseInt(dto.getState()));
                                map.setOrderId(order.getOrderId());
                                map.setDeliveryType(dto.getStateEx());
                                map.setDeliveryUpdateTime(DateUtils.getNowDate());
                                this.updateFsStoreOrder(map);
                                //如果是正常签收，更新订单状态
                                if(dto.getState().equals("3")&&(dto.getStateEx().equals("301")||dto.getStateEx().equals("302")||dto.getStateEx().equals("304")||dto.getStateEx().equals("311"))){
                                    this.getGoods(order.getOrderId());
                                }
                            }
                            if (!dto.isSuccess()){
                                logger.info("物流状态异常：{}"+dto);
                            }
                            if ((!dto.isSuccess()&&dto.getReason()!=null&&dto.getReason().equals("三天无轨迹"))||(!dto.isSuccess()&&dto.getReason()!=null&&dto.getReason().equals("七天内无轨迹变化"))){
                                //订阅物流回调
                                String lastFourNumber = "";
                                if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
                                    lastFourNumber = order.getUserPhone();
                                    if (lastFourNumber.length() == 11) {
                                        lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
                                    }
                                }
                                expressService.subscribeEspress(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);
                                logger.info("物流重新订阅：{}",order.getDeliverySn());
                            }

                        }

                    }
                }
            }
            return ExpressResultDTO.success(sysConfig.getKdnId().trim());
        }
        return ExpressResultDTO.error(sysConfig.getKdnId().trim(),"物流详情数据为null");

    }

    private List<FsStoreOrder> selectFsStoreOrderListByDeliveryId(String logisticCode) {
        return fsStoreOrderMapper.selectFsStoreOrderListByDeliverySn(logisticCode);
    }

    @Override
    @Transactional
    public R syncExpress(Long id) {

        FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderId(id);
        String lastFourNumber = "";
        if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
            lastFourNumber = order.getUserPhone();
            if (lastFourNumber.length() == 11) {
                lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
            }else if(lastFourNumber.length() >11){
                String jm = decryptPhone(lastFourNumber);
                lastFourNumber = StrUtil.sub(jm, jm.length(), -4);
            }
        }
        ExpressInfoDTO dto=expressService.getExpressInfo(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);
        if(dto.getStateEx().equals("0")&&dto.getState().equals("0")){
            lastFourNumber = "19923690275";
            if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
                lastFourNumber = order.getUserPhone();
                if (lastFourNumber.length() == 11) {
                    lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
                }
            }
            dto=expressService.getExpressInfo(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);
        }

        FsStoreOrder map=new FsStoreOrder();
        map.setDeliveryStatus(Integer.parseInt(dto.getState()));
        map.setOrderId(order.getOrderId());
        map.setDeliveryType(dto.getStateEx());
        fsStoreOrderMapper.updateFsStoreOrder(map);
        //如果是正常签收，更新订单状态
        if(dto.getState().equals("3")&&(dto.getStateEx().equals("301")||dto.getStateEx().equals("302")||dto.getStateEx().equals("304")||dto.getStateEx().equals("311"))){
            this.getGoods(order.getOrderId());
        }
        return R.ok();
    }

    @Override
    public R updateExpress(Long id) {
        FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderId(id);
        if(order.getStatus()!=2){
            return R.error("只有待发货状态可以同步");
        }
        if(order.getExtendOrderId()==null){
            return R.error("未生成管易云订单");
        }
        ErpOrderQueryRequert request = new ErpOrderQueryRequert();
        request.setCode(order.getExtendOrderId());
        ErpOrderQueryResponse response = erpOrderService.getOrder(request);
        if(response.getOrders()!=null&&response.getOrders().size()>0){
            for(ErpOrderQuery orderQuery : response.getOrders()){
                if(orderQuery.getDeliverys()!=null&&orderQuery.getDeliverys().size()>0){
                    for(ErpDeliverys delivery:orderQuery.getDeliverys()){
                        if(delivery.getDelivery()&& org.apache.commons.lang3.StringUtils.isNotEmpty(delivery.getMail_no())){
                            //更新商订单状态 删除REDIS
                            fsStoreOrderService.deliveryOrder(order.getOrderCode(),delivery.getMail_no(),delivery.getExpress_code(),delivery.getExpress_name());
                            redisCache.deleteObject("delivery"+":"+order.getExtendOrderId());
                        }
                    }

                }
            }
        }
        return R.error("未生成运单信息");
    }

    @Override
    @Transactional
    public R editTuiMoney(Long id) {
        FsStoreOrder order= fsStoreOrderMapper.selectFsStoreOrderByOrderId(id);
        if(order.getStatus()==4){
            if(order.getTuiMoneyStatus().equals(0)){
                order.setTuiMoneyStatus(1);
                fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.UNLOCK_TUI_MONEY.getValue(),FsStoreOrderLogEnum.UNLOCK_TUI_MONEY.getDesc());
                //写入公司余额
                Company company=companyService.selectCompanyByIdForUpdate(order.getCompanyId());
                CompanyMoneyLogs companyMoneyLogs = companyMoneyLogsMapper.selectCompanyMoneyLogsByOrderId(id,3);
                if (companyMoneyLogs != null) {
                    company.setMoney(company.getMoney().add(companyMoneyLogs.getMoney()));
                    companyService.updateCompany(company);
                    //写入日志
                    CompanyMoneyLogs log=new CompanyMoneyLogs();
                    log.setCompanyId(order.getCompanyId());
                    log.setRemark("订单佣金解冻");
                    log.setMoney(companyMoneyLogs.getMoney());
                    log.setLogsType(14);
                    log.setBalance(company.getMoney());
                    log.setCreateTime(new Date());
                    log.setBusinessId(order.getOrderId().toString());
                    companyMoneyLogsMapper.insertCompanyMoneyLogs(log);
                    fsStoreOrderMapper.updateFsStoreOrder(order);
                    return R.ok("解冻成功");
                }
                return R.error("无分佣日志");
            }
            else{
                order.setTuiMoneyStatus(0);
                fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.LOCK_TUI_MONEY.getValue(),FsStoreOrderLogEnum.LOCK_TUI_MONEY.getDesc());
                //写入公司余额
                Company company=companyService.selectCompanyByIdForUpdate(order.getCompanyId());
                CompanyMoneyLogs companyMoneyLogs = companyMoneyLogsMapper.selectCompanyMoneyLogsByOrderId(id,3);
                if (companyMoneyLogs != null){
                    company.setMoney(company.getMoney().subtract(companyMoneyLogs.getMoney()));
                    companyService.updateCompany(company);
                    //写入日志
                    CompanyMoneyLogs log=new CompanyMoneyLogs();
                    log.setCompanyId(order.getCompanyId());
                    log.setRemark("订单佣金冻结");
                    log.setMoney(companyMoneyLogs.getMoney().multiply(new BigDecimal(-1)));
                    log.setLogsType(13);
                    log.setBalance(company.getMoney());
                    log.setCreateTime(new Date());
                    log.setBusinessId(order.getOrderId().toString());
                    companyMoneyLogsMapper.insertCompanyMoneyLogs(log);
                    fsStoreOrderMapper.updateFsStoreOrder(order);
                    return R.ok("冻结成功");
                }
                return R.error("无分佣日志");
            }

        }
        else {
            return R.error("订单状态错误");
        }
    }

    @Override
    public String importExpress(List<StoreOrderExpressExportDTO> list) {
        if (StringUtils.isNull(list) || list.size() == 0)
        {
            throw new CustomException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder importSuccessMsg = new StringBuilder();
        StringBuilder importErrorMsg = new StringBuilder();
        StringBuilder importMsg = new StringBuilder();

        for (StoreOrderExpressExportDTO dto : list)
        {
//            try
//            {
                FsStoreOrder order=fsStoreOrderMapper.selectFsStoreOrderListByDeliverySnLOne(dto.getDeliverySn());
                if (StringUtils.isNull(order))
                {
                    String msg = "<br/>" + failureNum + "、快递单号 " + dto.getDeliverySn() + "不存在";
                    importErrorMsg.append(msg);
                    failureNum++;
                }
                else
                {
                    //订单状态为已签收并且未导入过
                    if(order.getStatus()==4&& order.getDeliveryImportTime()==null&&(order.getPayType()==2||order.getPayType()==3)){
                        FsStoreOrder orderMap=new FsStoreOrder();
                        orderMap.setOrderId(order.getOrderId());
                        orderMap.setDeliveryTime(dto.getDeliveryTime());
                        orderMap.setDeliveryPayStatus(Integer.parseInt(dto.getDeliveryPayStatus()));
                        orderMap.setDeliveryPayMoney(dto.getDeliveryPayMoney());
                        orderMap.setDeliveryPayTime(dto.getDeliveryPayTime());
                        orderMap.setDeliveryImportTime(new Date());
                        //未分佣写入分佣
                        if(order.getCompanyId()!=null&&order.getCompanyId()>0){
                            orderMap.setTuiMoneyTime(new Date());
                            companyService.addCompanyMoney(order);
                        }
                        this.updateFsStoreOrder(orderMap);

                        successNum++;
                        importSuccessMsg.append("<br/>" + successNum + "、快递单号 " +dto.getDeliverySn() + " 导入成功");
                    }
                    else{
                        String msg = "<br/>" + failureNum + "、快递单号 " + dto.getDeliverySn() + " 订单未完成或已导入,不能导入";
                        importErrorMsg.append(msg);
                        failureNum++;
                    }
                }
            }
//            catch (Exception e)
//            {
//                String msg = "<br/>" + failureNum + "、快递单号 " + dto.getDeliverySn() + " 导入异常：";
//                importErrorMsg.append(msg+e.getMessage());
//                failureNum++;
//            }
//        }
        importMsg.insert(0, "导入完成！成功" + successNum + " 条，失败"+failureNum+"条。");
        importMsg.append(importErrorMsg.toString());
        importMsg.append(importSuccessMsg.toString());
        return importMsg.toString();
    }

    @Override
    public R getExpress(FsStoreOrder order) {
        //顺丰轨迹查询处理
        String lastFourNumber = "";
        if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
            lastFourNumber = order.getUserPhone();
            if (lastFourNumber.length() == 11) {
                lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
            }
        }
        ExpressInfoDTO dto=expressService.getExpressInfo(order.getOrderCode(),order.getDeliveryCode(),order.getDeliverySn(),lastFourNumber);
        System.out.println(dto);
        dto.setShipperName(order.getDeliveryName());
        FsExpress express=expressService.selectFsExpressByName(order.getDeliveryName());
        System.out.println(express);
        return R.ok().put("data", dto).put("express",express).put("deliverySn",order.getDeliverySn());
    }

    @Override
    public synchronized  R finishOrder(Long orderId) {
        return finishStoreOrder(orderId);
    }

    @Override
    public void addFsFollowByStoreOrder(FsStoreOrder order) {
        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.store");
        Map<String, Object> config = (Map<String, Object>) JSON.parse(sysConfig.getConfigValue());
        Integer followRate = (Integer)config.get("followRate");
        Integer followTempId = (Integer)config.get("followTempId");
        FsFollowTemp fsFollowTemp = fsFollowTempMapper.selectFsFollowTempByTempId(followTempId+0L);
        if (fsFollowTemp!=null){
            FsFollow fsFollow = new FsFollow();
            fsFollow.setTempId(followTempId+0L);
            FsPrescribe fsPrescribe = fsPrescribeService.selectFsPrescribeByPrescribeId(order.getPrescribeId());
            fsFollow.setPatientPhone(order.getUserPhone());
            if (fsPrescribe!=null){
                fsFollow.setPatientName(fsPrescribe.getPatientName());
                fsFollow.setPatientId(fsPrescribe.getPatientId());
            }
            fsFollow.setUserId(order.getUserId());
            fsFollow.setDoctorId(order.getFollowDoctorId());
            fsFollow.setTotalNum(1);
            fsFollow.setStoreOrderId(order.getOrderId());
            fsFollow.setCompanyId(order.getCompanyId());
            fsFollow.setCompanyUserId(order.getCompanyUserId());
            fsFollow.setDeptId(order.getDeptId());
            fsFollow.setNum(1);
            fsFollow.setInquiryOrderId(order.getInquiryOrderId());
            fsFollow.setPlanTime(DateUtils.getNowDate());
            fsFollow.setPushStatus(1);
            fsFollow.setWriteStatus(0);
            fsFollow.setFormJson(fsFollowTemp.getFormJson());
            fsFollow.setCreateTime(DateUtils.getNowDate());
            int i = fsFollowMapper.insertFsFollow(fsFollow);

            if (i>0){
                FsStoreOrder fsStoreOrder = new FsStoreOrder();
                fsStoreOrder.setOrderId(order.getOrderId());
                if ((order.getCycle()/followRate)>(order.getFollowNum()+1)){
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(order.getFollowTime());
                    calendar.add(Calendar.DAY_OF_MONTH, followRate);
                    fsStoreOrder.setFollowTime(calendar.getTime());
                }
                fsStoreOrder.setFollowNum(order.getFollowNum()+1);
                fsStoreOrderMapper.updateFsStoreOrder(fsStoreOrder);
                  TemplateBean templateBean = TemplateBean.builder()
                          .followId(fsFollow.getFollowId().toString())
                        .orderId(order.getOrderId().toString())
                        .title("您收到一个随访单")
                        .remark("您有一个随访单待填写")
                        .uid(order.getUserId())
                        .templateType(TemplateListenEnum.TYPE_4.getValue())
                        .build();
                publisher.publishEvent(new TemplateEvent(this, templateBean));

            }

        }
    }

    @Transactional
    R finishStoreOrder(Long orderId){
        FsStoreOrder order= fsStoreOrderMapper.selectFsStoreOrderByOrderId(orderId);
        if(order.getStatus()==FsStoreOrderStatusEnum.STATUS_3.getValue()){
            order.setFinishTime(new Date());
            order.setStatus(4);
            fsStoreOrderMapper.updateFsStoreOrder(order);
            fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.FINISH_ORDER.getValue(),
                    FsStoreOrderLogEnum.FINISH_ORDER.getDesc());

            //模板消息支付成功发布事件
//            TemplateBean templateBean = TemplateBean.builder()
//                    .orderId(order.getOrderId().toString())
//                    .title(order.getOrderCode().toString())
//                    .remark("您的订单已签收成功")
//                    .time(order.getFinishTime())
//                    .uid(order.getUserId())
//                    .templateType(TemplateListenEnum.TYPE_3.getValue())
//                    .build();
//            publisher.publishEvent(new TemplateEvent(this, templateBean));
            return R.ok("操作成功");
        }
        else {
            return R.error("非法操作");
        }
    }

    @Override
    public List<FsStoreOrderExportVO> selectFsStoreOrderListVOByExport(FsStoreOrderParam param) {
        return fsStoreOrderMapper.selectFsStoreOrderListVOByExport(param);
    }

    @Override
    public List<FsInquiryOrderMsg> selectFsInquiryOrderMsgByStoreOrderId(FsFollowMsgParam fsFollowMsgParam) {

        return fsStoreOrderMapper.selectFsInquiryOrderMsgByStoreOrderId(fsFollowMsgParam.getUserId(),fsFollowMsgParam.getFollowDoctorId());
    }

    @Override
    public FsFollowVO selectFsFollowVOByFollowId(Long followId) {
        return fsFollowMapper.selectFsFollowVOByFollowId(followId);
    }

    @Override
    @Transactional
    public void addIntegralAndShareByStoreOrder(FsStoreOrder fsStoreOrder) {
        fsUserService.addUserIntegral(fsStoreOrder.getPayMoney(),fsStoreOrder.getUserId(),fsStoreOrder.getOrderId(),2);
        FsStoreOrder order = new FsStoreOrder();
        order.setOrderId(fsStoreOrder.getOrderId());
        order.setIsAfterSales(0);
        fsStoreOrderMapper.updateFsStoreOrder(order);
        //分账
        List<FsStorePayment> fsStorePayments =null;
        String orderType="";
        if (fsStoreOrder.getPackageOrderId()!=null){
             fsStorePayments = fsStorePaymentMapper.selectFsStorePaymentByPackageOrderId(fsStoreOrder.getPackageOrderId());
            orderType="package";
        }else {
            fsStorePayments = fsStorePaymentMapper.selectFsStorePaymentByOrderId(fsStoreOrder.getOrderId());
            orderType="store";
        }
        if (fsStorePayments!=null && fsStorePayments.size()==1){
            FsStorePayment fsStorePayment = fsStorePayments.get(0);
            if (fsStorePayment.getPayMode()!=null&&fsStorePayment.getPayMode().equals("tz")&&fsStorePayment.getShareStatus()!=null&&fsStorePayment.getShareStatus()==0&&fsStorePayment.getIsShare()==1){

                //交易金额
                BigDecimal payMoney = fsStorePayment.getPayMoney();
                BigDecimal share = payMoney.multiply(new BigDecimal(0.001)).setScale(2, RoundingMode.HALF_UP);

                    OrderShareParam orderShareParam = new OrderShareParam();
                    //// 传的分账订单号
                    orderShareParam.setOutOrderNo("share"+fsStorePayment.getPayCode());
                    //旧的支付外部订单号 支付时上上传的
                    orderShareParam.setOldPayOutOrderNo(orderType+fsStorePayment.getPayCode());
                    orderShareParam.setTrxAmt(fsStorePayment.getPayMoney().doubleValue());
                    OrderShareParam.sharers sharer = new OrderShareParam.sharers();
                    //分账金额
                if (share.compareTo(BigDecimal.ZERO)!=0){
                    sharer.setShareAmt(share.doubleValue());
                    sharer.setSharerCstName("重庆云联融智科技有限公司");
                    sharer.setSharerCstNo("943103603046907709");
                    List<OrderShareParam.sharers> sharers = new ArrayList<>();
                    sharers.add(sharer);
                    orderShareParam.setSharers(sharers);
                }
                    TzBankResult<OrderShareResult> r = tzBankService.orderShare(orderShareParam);
                    if (r.getRetType().equals("S")){
                        if (r.getBody().getShareOrdStatus().equals("90")||r.getBody().getShareOrdStatus().equals("60")){
                            FsStorePayment sharePayment = new FsStorePayment();
                            sharePayment.setPaymentId(fsStorePayment.getPaymentId());
                            sharePayment.setShareStatus(1);
                            sharePayment.setShareCode(r.getBody().getShareOrderNo());
                            sharePayment.setShareMoney(new BigDecimal(r.getBody().getTrxAmt()));
                            fsStorePaymentMapper.updateFsStorePayment(sharePayment);
                        }else {
                            logger.info("分账失败:"+fsStorePayment);
                        }
                    }else {
                        logger.info("分账请求失败:"+fsStorePayment+r.getRetMsg());
                    }

            }
        }



    }

    @Override
    public void endFollow() {
        List<FsStoreOrder> fsStoreOrders = fsStoreOrderMapper.selectFsStoreOrderEndFollow();
        for (FsStoreOrder fsStoreOrder : fsStoreOrders) {
            Long userId = fsStoreOrder.getUserId();
            Long followDoctorId = fsStoreOrder.getFollowDoctorId();
            List<FsStoreOrder> orders = fsStoreOrderMapper.selectFsStoreOrderEndFollowByUserIdAndDocId(userId,followDoctorId);

            if (orders==null||orders.size()==0){
                Long l = fsStoreOrderMapper.selectFsStoreOrderFollow(userId, followDoctorId);
                MsgDTO msgDTO=new MsgDTO();
                MsgCustomDTO customDTO=new MsgCustomDTO();
                customDTO.setType("finishFollow");
                customDTO.setFollowId(l+"");
                customDTO.setImType(0);
                msgDTO.setCloudCustomData(JSONUtil.toJsonStr(customDTO));
                msgDTO.setFrom_Account("D-"+userId);
                msgDTO.setTo_Account("U-"+followDoctorId);
                List<MsgDataDTO> msgs1=new ArrayList<>();
                MsgDataDTO msg1=new MsgDataDTO();
                MsgDataFormatDTO dto=new MsgDataFormatDTO("尊敬的用户，您好，咨询结束。\n");
                msg1.setMsgContent(dto);
                msg1.setMsgType("TIMTextElem");//TIMCustomElem
                msgs1.add(msg1);
                msgDTO.setMsgBody(msgs1);
                MsgResponseDTO msgResponseDTO = imService.sendMsg(msgDTO);
                logger.info("医生结束随访"+msgResponseDTO);



            }
            FsStoreOrder o = new FsStoreOrder();
            o.setOrderId(fsStoreOrder.getOrderId());
            o.setFollowStatus(1);
            fsStoreOrderMapper.updateFsStoreOrder(o);

        }
    }

    @Override
    public void updateDeliveryOrder(Long id,String deliveryId,String deliverCode,String deliverName) {
        FsStoreOrder order= fsStoreOrderMapper.selectFsStoreOrderByOrderId(id);
        if(order!=null){
            FsExpress express=expressService.selectFsExpressByOmsCode(deliverCode);
            if(express!=null){
                order.setDeliveryName(deliverName);
                order.setDeliveryCode(express.getCode());
                order.setDeliverySn(deliveryId);
                order.setDeliverySendTime(new Date());
                fsStoreOrderMapper.updateFsStoreOrder(order);
                //订阅物流回调
                String lastFourNumber = "";
                if (express.getCode().equals(ShipperCodeEnum.SF.getValue())) {
                    lastFourNumber = order.getUserPhone();
                    if (lastFourNumber.length() == 11) {
                        lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
                    }
                }
                expressService.subscribeEspress(order.getOrderCode(),express.getCode(),deliveryId,lastFourNumber);
            }
        }
    }
    @Transactional
    @Override
    public void endDeliveryOrder() {
        List<FsStoreOrder> fsStoreOrders = fsStoreOrderMapper.selectEndDeliveryOrder();
        for (FsStoreOrder fsStoreOrder : fsStoreOrders) {
             if (fsStoreOrder.getStatus()==3&&fsStoreOrder.getDeliveryType().equals("406")&&fsStoreOrder.getPayType()==3){
                 if (fsStoreOrder.getCompanyId()!=null){
                     companyService.refundCompanyMoney(fsStoreOrder);
                 }
                 FsStoreOrder o = new FsStoreOrder();
                 o.setOrderId(fsStoreOrder.getOrderId());
                 o.setStatus(-2);
                 o.setRefundTime(DateUtils.getNowDate());
                 fsStoreOrderMapper.updateFsStoreOrder(o);
                 FsStoreOrderLogs Logs = new FsStoreOrderLogs();
                 Logs.setChangeMessage(FsStoreOrderStatusEnum.REFUND_STATUS_2.getDesc());
                 Logs.setOrderId(fsStoreOrder.getOrderId());
                 Logs.setChangeTime(new DateTime());
                 Logs.setChangeType(FsStoreOrderStatusEnum.REFUND_STATUS_2.getValue().toString());
                 fsStoreOrderLogsMapper.insertFsStoreOrderLogs(Logs);
                 if (fsStoreOrder.getPackageOrderId()!=null){
                     FsPackageOrder fsPackageOrder = fsPackageOrderMapper.selectFsPackageOrderByOrderId(fsStoreOrder.getPackageOrderId());
                     if (fsPackageOrder!=null){
                         fsPackageOrder.setStatus(-2);
                         fsPackageOrder.setRefundStatus(2);
                         fsPackageOrderMapper.updateFsPackageOrder(fsPackageOrder);
                     }
                 }
             }
        }
    }

    @Override
    @Transactional
    public R returnCost(Long orderId) {
        FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderId(orderId);
        if (order!=null){
            if(order.getCompanyId()!=null&&order.getCompanyId()>0){
                Company company=companyMapper.selectCompanyByIdForUpdate(order.getCompanyId());
                if(company!=null){
                    List<CompanyMoneyLogs> logsList = companyMoneyLogsMapper.selectCompanyMoneyAllTypeByOrderId(orderId);
                    List<CompanyMoneyLogs> companyMoneyLogs = companyMoneyLogsMapper.selectCompanyMoneyByOrderId(order.getOrderId());
                    boolean containsAllLogsTypes  = logsList.stream().anyMatch(log -> log.getLogsType() == 4) &&
                            logsList.stream().anyMatch(log -> log.getLogsType() == 6);
                    boolean doesNotContain4 = logsList.stream().anyMatch(log -> log.getLogsType() == 4);
                    boolean doesNotContain6 = logsList.stream().anyMatch(log -> log.getLogsType() == 6);
                    if (containsAllLogsTypes){
                        return R.error("成本返还和分佣记录已存在");
                    }
                    for (CompanyMoneyLogs logs : companyMoneyLogs) {
                        if(!doesNotContain4){
                            if (logs.getLogsType()==3){
                                if (order.getTuiMoneyStatus()!=null&&order.getTuiMoneyStatus()==0){
                                    continue;
                                }
                                BigDecimal money = logs.getMoney().multiply(new BigDecimal(-1));
                                logger.info("退款佣金扣除:"+company.getCompanyId()+":"+money);
                                company.setMoney(company.getMoney().subtract(logs.getMoney()));
                                companyMapper.updateCompany(company);
                                CompanyMoneyLogs log=new CompanyMoneyLogs();
                                log.setCompanyId(company.getCompanyId());
                                log.setRemark("退款佣金扣除");
                                log.setMoney(money);
                                log.setLogsType(4);
                                log.setBalance(company.getMoney());
                                log.setCreateTime(new Date());
                                log.setBusinessId(order.getOrderId().toString());
                                companyMoneyLogsMapper.insertCompanyMoneyLogs(log);
                            }
                        }
                        if (!doesNotContain6){
                            if(logs.getLogsType()==5){
                                BigDecimal money = logs.getMoney().multiply(new BigDecimal(-1));
                                logger.info("退款成本返还:"+company.getCompanyId()+":"+money);
                                company.setMoney(company.getMoney().add(money));
                                companyMapper.updateCompany(company);
                                CompanyMoneyLogs log=new CompanyMoneyLogs();
                                log.setCompanyId(company.getCompanyId());
                                log.setRemark("退款成本返还");
                                log.setMoney(money);
                                log.setLogsType(6);
                                log.setBalance(company.getMoney());
                                log.setCreateTime(new Date());
                                log.setBusinessId(order.getOrderId().toString());
                                companyMoneyLogsMapper.insertCompanyMoneyLogs(log);
                            }
                        }

                    }

                }
            }
            return R.ok();
        }
        return R.error();
    }

    @Override
    public String sendStartMsg(Long orderId) {
        FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderId(orderId);
        if (order.getFollowDoctorId()==null||order.getFollowEndTime()==null||order.getFollowEndTime().before(new Date())){
            throw new CustomException("次订单随访已结束或没有随访");
        }
        MsgDTO msgDTO=new MsgDTO();
        MsgCustomDTO customDTO=new MsgCustomDTO();
        customDTO.setType("startFollow");
        customDTO.setImType(2);
        customDTO.setOrderId(order.getOrderId().toString());
        FsFollow fsFollow = fsFollowReportMapper.selectFsFollowOrderById(order.getUserId(), order.getFollowDoctorId());
        if (fsFollow==null){
            throw new CustomException("没有随访单订单");
        }
        customDTO.setFollowId(fsFollow.getFollowId()+"");
        msgDTO.setCloudCustomData(JSONUtil.toJsonStr(customDTO));
        msgDTO.setFrom_Account("D-"+order.getFollowDoctorId());
        msgDTO.setTo_Account("U-"+order.getUserId());
        List<MsgDataDTO> msgs=new ArrayList<>();
        MsgDataDTO msg=new MsgDataDTO();
        msg.setMsgType("TIMCustomElem");
        msg.setMsgContent(new MsgDataFormatDTO("为您服务"));
        msgs.add(msg);
        msgDTO.setMsgBody(msgs);
        MsgResponseDTO msgResponseDTO = imService.sendMsg(msgDTO);
        System.out.println(msgResponseDTO);
        return "ok";
    }

    @Override
    public List<FsStoreOrderExcelVO> selectFsStoreOrderExcelListSVO(FsStoreOrderParam fsStoreOrder) {
        List<FsStoreOrderExcelVO> fsStoreOrderVOS = fsStoreOrderMapper.selectFsStoreOrderExcelListVO(fsStoreOrder);

        for (FsStoreOrderExcelVO vo : fsStoreOrderVOS) {
            vo.setProductName(vo.getPackageSecondName());
            int count=1;
            if (vo.getCycle()!=null){
                count= vo.getCycle() / 6;
                if (count==0){
                    count=1;
                }
                vo.setFollowNum(count);
            }
            BigDecimal money = new BigDecimal(count * 300);
            vo.setInquiryMoney(money);
            if (vo.getTotalCostMoney()==null){
                if (vo.getCostPrice()!=null){
                    vo.setTotalCostMoney(vo.getCostPrice());
                }else {
                    vo.setTotalCostMoney(new BigDecimal("0"));
                }
            }
            vo.setTotalMoney(vo.getInquiryMoney().add(vo.getTotalCostMoney()));
            vo.setInquiryDiscountMoney(vo.getTotalMoney().subtract(vo.getPrescribePrice()));
        }
        return fsStoreOrderVOS;
    }

    @Override
    public List<FsStoreOrderStatisticsVO> selectFsPackageOrderStatisticsList(FsStoreStatisticsParam param) {
        return fsStoreOrderMapper.selectFsPackageOrderStatisticsList(param);
    }

    @Override
    public List<com.alibaba.fastjson.JSONObject> selectFsPackageOrderCounts(Map<String, Object> map) {
        return fsStoreOrderMapper.selectFsPackageOrderCounts(map);
    }


    @Override
    public List<FsStoreOrderStatisticsVO> selectFsInquiryOrderStatisticsList(FsStoreStatisticsParam param) {
        return fsStoreOrderMapper.selectFsInquiryOrderStatisticsList(param);
    }

    @Override
    public List<com.alibaba.fastjson.JSONObject> selectFsInquiryOrderCounts(Map<String, Object> map) {
        return fsStoreOrderMapper.selectFsInquiryOrderCounts(map);
    }

    @Override
    public List<FsStoreProductStatisticsVO> selescChartProdVOStatisticsList(FsStoreStatisticsParam param) {
        return fsStoreOrderMapper.selescChartProdVOStatisticsList(param);
    }

    @Override
    public R payment(FsStoreOrderDoPayParam param) {
        FsStoreOrder order=fsStoreOrderMapper.selectFsStoreOrderByOrderId(param.getOrderId());
        if(order==null){
            return R.error("订单不存在");
        }
        if(order.getStatus()!= FsStoreOrderStatusEnum.STATUS_1.getValue()){
            return R.error("订单状态不正确");
        }

        FsUser user=userService.selectFsUserByUserId(param.getUserId());
        if(user!=null&& StringUtils.isNotEmpty(user.getMaOpenId())){

            if(order.getPayMoney().compareTo(new BigDecimal(0))==0){
                this.payConfirm(order.getOrderCode(),"","","",2);
                // tuiOrderUtil.TuiOrder(order.getOrderId());
                return R.ok().put("data",param.getOrderId()).put("isPay","1");
            }
            else {
                //在线支付
                String json = configService.selectConfigByKey("his.pay");
                PayConfigDTO payConfigDTO = JSONUtil.toBean(json, PayConfigDTO.class);
                String payCode =  OrderCodeUtils.getOrderSn();
                if(StringUtils.isEmpty(payCode)){
                    return R.error("订单生成失败，请重试");
                }
                FsStorePayment storePayment = new FsStorePayment();
                storePayment.setStatus(0);
                storePayment.setPayCode(payCode);
                storePayment.setPayMode(payConfigDTO.getType());
                storePayment.setPayMoney(order.getPayMoney());
                storePayment.setBusinessCode(order.getOrderCode());
                storePayment.setCreateTime(new Date());
                storePayment.setPayTypeCode("weixin");
                storePayment.setBusinessType(2);
                storePayment.setRemark("药品订单支付");
                storePayment.setOpenId(user.getMaOpenId());
                storePayment.setUserId(user.getUserId());
                storePayment.setCompanyId(order.getCompanyId());
                storePayment.setCompanyUserId(order.getCompanyUserId());
                storePayment.setStoreId(order.getStoreId());
                storePayment.setBusinessId(order.getOrderId().toString());
                if (storePaymentService.insertFsStorePayment(storePayment) > 0) {

                    if (payConfigDTO.getType().equals("wx")) {
                        //创建微信订单
                        WxPayConfig payConfig = new WxPayConfig();
                        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.pay");
                        FsPayConfig fsPayConfig = new Gson().fromJson(sysConfig.getConfigValue(), FsPayConfig.class);
                        payConfig.setAppId(fsPayConfig.getAppId());
                        payConfig.setMchId(fsPayConfig.getWxMchId());
                        payConfig.setMchKey(fsPayConfig.getWxMchKey());
                        payConfig.setSubAppId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                        payConfig.setSubMchId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                        payConfig.setKeyPath(null);
                        payConfig.setNotifyUrl(wxPayProperties.getNotifyUrl());
                        wxPayService.setConfig(payConfig);
                        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
                        orderRequest.setOpenid(user.getMaOpenId());//公众号支付提供用户openid
                        orderRequest.setBody("药品订单支付");
                        orderRequest.setOutTradeNo("store-" + storePayment.getPayCode());
                        orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(storePayment.getPayMoney().toString()));//测试
                        //orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(money));//测试
                        orderRequest.setTradeType("JSAPI");
                        orderRequest.setSpbillCreateIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
                        //调用统一下单接口，获取"预支付交易会话标识"
                        try {
                            WxPayMpOrderResult orderResult = wxPayService.createOrder(orderRequest);
                            return R.ok().put("data", orderResult).put("type", "wx").put("isPay", 0);
                        } catch (WxPayException e) {
                            e.printStackTrace();
                            throw new CustomException("支付失败" + e.getMessage());
                        }
                    } else if (payConfigDTO.getType().equals("yb")) {
                        WxJspayDTO p = new WxJspayDTO();
                        // 使用setter方法为对象赋值
                        p.setPayMoney(storePayment.getPayMoney().toString());
                        p.setLowOrderId("store-" + storePayment.getPayCode());
                        p.setBody("药品订单支付");
                        p.setIsMinipg("1");
                        p.setOpenId(user.getMaOpenId());
                        p.setAttach("");
                        p.setStoreid("0");
                        CreateWxOrderResult wxOrder = payService.createWxOrder(p);
                        if (wxOrder.getStatus().equals("100")) {
                            FsStorePayment mt=new FsStorePayment();
                            mt.setPaymentId(storePayment.getPaymentId());
                            mt.setTradeNo(wxOrder.getUpOrderId());
                            fsStorePaymentMapper.updateFsStorePayment(mt);
                            return R.ok().put("isPay", 0).put("data", wxOrder).put("type", "yb");
                        } else {
                            throw new CustomException("支付失败");
                        }
                    } else if (payConfigDTO.getType().equals("tz")) {
                        PayCreateOrder o = new PayCreateOrder();
                        o.setOrderNo("store" + storePayment.getPayCode()); // 业务系统订单号
                        o.setTrxAmt(storePayment.getPayMoney().doubleValue()); // 交易金额
                        o.setBusinessCstNo(order.getUserId().toString()); // 业务平台客户号
                        String phone="";
                        if (user.getPhone()!=null&&user.getPhone().length()>4){
                            phone=user.getPhone().substring(user.getPhone().length()-4);
                            if (user.getPhone().length()>11){
                                o.setPayerMobileNo(PhoneUtil.decryptPhone(user.getPhone()));
                            }else {
                                o.setPayerMobileNo(user.getPhone());
                            }
                        }
                        o.setPayerName("微信用户"+phone);
                        o.setGoodsInfo("药品订单支付"); // 订单信息
                        o.setOpenId(user.getMaOpenId());
                        o.setOrderType(2);
                        o.setOrderId(order.getOrderId().toString());
                        TzBankResult<PayCreateOrderResult> result = tzBankService.createOrder(o);
                        FsStorePayment mt=new FsStorePayment();
                        mt.setPaymentId(storePayment.getPaymentId());
                        mt.setTradeNo(result.getBody().getOrderFlowNo());
                        fsStorePaymentMapper.updateFsStorePayment(mt);
                        return R.ok().put("isPay", 0).put("data", result).put("type", "tz");
                    }else if (payConfigDTO.getType().equals("hf")) {
                        HuiFuCreateOrder o = new HuiFuCreateOrder();
                        o.setTradeType("T_MINIAPP");
                        o.setOpenid(user.getMaOpenId());
                        o.setReqSeqId("store-"+storePayment.getPayCode());
                        o.setTransAmt(storePayment.getPayMoney().toString());
                        o.setGoodsDesc("药品订单支付");
                        HuifuCreateOrderResult result = huiFuService.createOrder(o);
                        FsStorePayment mt=new FsStorePayment();
                        mt.setPaymentId(storePayment.getPaymentId());
                        mt.setTradeNo(result.getHf_seq_id());
                        storePaymentService.updateFsStorePayment(mt);
                        return R.ok().put("isPay",0).put("data",result).put("type","hf");
                    }

                } else {
                    return R.error("用户不存在");

                }
            }
        }
        return R.error();
    }

    @Override
    public R zfbPayment(FsStoreOrderDoPayParam param) {
        FsStoreOrder order=fsStoreOrderMapper.selectFsStoreOrderByOrderId(param.getOrderId());
        if(order==null){
            return R.error("订单不存在");
        }
        if(order.getStatus()!= FsStoreOrderStatusEnum.STATUS_1.getValue()){
            return R.error("订单状态不正确");
        }

        FsUser user=userService.selectFsUserByUserId(param.getUserId());
        if(user!=null&& StringUtils.isNotEmpty(user.getMaOpenId())){

            if(order.getPayMoney().compareTo(new BigDecimal(0))==0){
                this.payConfirm(order.getOrderCode(),"","","",2);
                return R.ok().put("data",param.getOrderId()).put("isPay","1");
            }
            else {
                //在线支付
                String payCode =  OrderCodeUtils.getOrderSn();
                if(StringUtils.isEmpty(payCode)){
                    return R.error("订单生成失败，请重试");
                }
                String json = configService.selectConfigByKey("his.pay");
                PayConfigDTO payConfigDTO = JSONUtil.toBean(json, PayConfigDTO.class);
                FsStorePayment storePayment = new FsStorePayment();
                storePayment.setStatus(0);
                storePayment.setPayCode(payCode);
                storePayment.setPayMode(payConfigDTO.getType());
                storePayment.setPayMoney(order.getPayMoney());
                storePayment.setBusinessCode(order.getOrderCode());
                storePayment.setCreateTime(new Date());
                storePayment.setPayTypeCode("alipay");
                storePayment.setBusinessType(2);
                storePayment.setRemark("药品订单支付");
                storePayment.setOpenId(user.getMaOpenId());
                storePayment.setUserId(user.getUserId());
                storePayment.setCompanyId(order.getCompanyId());
                storePayment.setCompanyUserId(order.getCompanyUserId());
                storePayment.setStoreId(order.getStoreId());
                storePayment.setBusinessId(order.getOrderId().toString());
                if (storePaymentService.insertFsStorePayment(storePayment) > 0) {
                    if (payConfigDTO.getType().equals("yb")) {
                        return R.error("支付暂不可用!");
                    } else if (payConfigDTO.getType().equals("tz")) {
                        PayCreateOrder o = new PayCreateOrder();
                        o.setOrderNo("store" + storePayment.getPayCode()); // 业务系统订单号
                        o.setTrxAmt(storePayment.getPayMoney().doubleValue()); // 交易金额
                        o.setBusinessCstNo(order.getUserId().toString()); // 业务平台客户号
                        String phone="";
                        if (user.getPhone()!=null&&user.getPhone().length()>4){
                            phone=user.getPhone().substring(user.getPhone().length()-4);
                        }
                        o.setPayerName("微信用户"+phone);
                        o.setGoodsInfo("药品订单支付"); // 订单信息
                        o.setOrderType(2);
                        o.setOrderId(order.getOrderId().toString());
                        o.setPayType(Arrays.asList(PayType.支付宝条码支付.getCode()));
                        TzBankResult<PayCreateOrderResult> result = tzBankService.createOrder(o);
                        FsStorePayment mt=new FsStorePayment();
                        mt.setPaymentId(storePayment.getPaymentId());
                        mt.setTradeNo(result.getBody().getOrderFlowNo());
                        fsStorePaymentMapper.updateFsStorePayment(mt);
                        return R.ok().put("isPay", 0).put("data", result).put("type", "tz");
                    }else if (payConfigDTO.getType().equals("hf")) {
                        HuiFuCreateOrder o = new HuiFuCreateOrder();
                        o.setTradeType("A_NATIVE");
                        o.setOpenid(user.getMaOpenId());
                        o.setReqSeqId("store-"+storePayment.getPayCode());
                        o.setTransAmt(storePayment.getPayMoney().toString());
                        o.setGoodsDesc("药品订单支付");
                        HuifuCreateOrderResult result = huiFuService.createOrder(o);
                        FsStorePayment mt=new FsStorePayment();
                        mt.setPaymentId(storePayment.getPaymentId());
                        mt.setTradeNo(result.getHf_seq_id());
                        storePaymentService.updateFsStorePayment(mt);
                        return R.ok().put("isPay",0).put("data",result).put("type","hf");
                    }

                } else {
                    return R.error("用户不存在");

                }
            }
        }
        return R.error();
    }

    @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 FsStoreOrderExportDataVO selectFsStoreOrderExportDataVOByOrderId(long orderId) {
        return fsStoreOrderMapper.selectFsStoreOrderExportDataVOByOrderId(orderId);
    }
    public Long selectFsStoreOrderExcelListVOCount(FsStoreOrderParam fsStoreOrder) {
        return fsStoreOrderMapper.selectFsStoreOrderExcelListVOCount(fsStoreOrder);
    }

    @Override
    public Long selectFsStoreOrderListVOByExportCount(FsStoreOrderParam param) {
        return fsStoreOrderMapper.selectFsStoreOrderListVOByExportCount(param);
    }

    @Override
    public void addOrderEatMsg(FsStoreOrder fsStoreOrder) {

        QwExternalContact qwExternalContact = qwExternalContactMapper.selectExternalByFsUserId(fsStoreOrder.getUserId());
        if (qwExternalContact!=null){

            QwUser qwUser = qwUserServiceImpl.selectQwUserById(qwExternalContact.getQwUserId());
            if (qwUser.getAppKey()!=null&&qwUser.getAppKey()!=""){
                //可以发生消息

            }
        }
    }

    @Override
    public List<FsStoreOrder> selectFsStoreOrderByOrderIdIn(List<Long> ids) {
        return fsStoreOrderMapper.selectFsStoreOrderByOrderIdIn(ids);
    }

    @Override
    public List<FsStoreOrder> selectFsStoreOrderStatisticsByUserId(List<Long> fsUserIdList) {
        return fsStoreOrderMapper.selectFsStoreOrderStatisticsByUserId(fsUserIdList);
    }


}
