package com.fs.his.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import com.alibaba.fastjson.JSON;
import com.fs.common.constant.FsConstants;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.CustomException;
import com.fs.common.service.impl.SmsServiceImpl;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyMoneyLogs;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyMoneyLogsMapper;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.core.config.WxPayProperties;
import com.fs.core.utils.OrderCodeUtils;
import com.fs.event.TemplateBean;
import com.fs.event.TemplateEvent;
import com.fs.event.TemplateListenEnum;
import com.fs.his.domain.*;
import com.fs.his.dto.*;
import com.fs.his.enums.FsInquiryOrderStatusEnum;
import com.fs.his.mapper.*;
import com.fs.his.param.*;
import com.fs.his.service.*;
import com.fs.his.vo.*;
import com.fs.huifuPay.domain.HuiFuRefundResult;
import com.fs.huifuPay.sdk.opps.core.request.V2TradePaymentScanpayRefundRequest;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.im.dto.*;
import com.fs.im.service.IImService;
import com.fs.jpush.service.JpushService;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.tzBankPay.doman.*;
import com.fs.ybPay.domain.OrderResult;
import com.fs.ybPay.domain.RefundResult;
import com.fs.ybPay.dto.OrderQueryDTO;
import com.fs.ybPay.dto.RefundDTO;
import com.fs.ybPay.service.IPayService;
import com.fs.system.service.ISysConfigService;
import com.fs.tzBankPay.TzBankService.TzBankService;
import com.fs.tzBankPay.config.TzBankConfig;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.fs.common.utils.SecurityUtils.getUserId;
import static com.fs.his.utils.PhoneUtil.encryptPhone;

/**
 * 问诊订单Service业务层处理
 *
 * @author fs
 * @date 2023-06-12
 */
@Service
public class FsInquiryOrderServiceImpl implements IFsInquiryOrderService
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private WxPayProperties wxPayProperties;
    @Autowired
    private TzBankService tzBankService;
    @Autowired
    private ApplicationEventPublisher publisher;
    @Autowired
    private IFsInquiryOrderLogsService fsInquiryOrderLogsService;
    @Autowired
    private JpushService jpushService;
    @Autowired
    IPayService payService;
    @Autowired
    SmsServiceImpl smsService;
    @Autowired
    private FsInquiryOrderMapper fsInquiryOrderMapper;
    @Autowired
    private FsStorePaymentMapper fsStorePaymentMapper;
    @Autowired
    HuiFuService huiFuService;
    @Autowired
    private FsInquiryOrderPingMapper fsInquiryOrderPingMapper;
    @Autowired
    private FsPatientMapper fsPatientMapper;
    @Autowired
    FsUserMapper userMapper;
    @Autowired
    private FsDoctorMapper doctorMapper;
    @Autowired
    private IFsDoctorService fsDoctorService;
    @Autowired
    private FsUserCouponMapper userCouponMapper;
    @Autowired
    RedisCache redisCache;
    @Autowired
    FsPackageOrderMapper fsPackageOrderMapper;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IFsInquiryOrderReportService inquiryOrderReportService;
    @Autowired
    private IFsPrescribeService prescribeService;
    @Autowired
    private IImService imService;
    @Autowired
    private ICompanyUserService companyUserService;
    @Autowired
    SysConfigMapper sysConfigMapper;
    @Autowired
    private FsPackageOrderMapper packageOrderMapper;
    @Autowired
    private FsStorePaymentErrorMapper fsStorePaymentErrorMapper;
    @Autowired
    private IPayService ybPayService;
    @Autowired
    private IFsUserService fsUserService;
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @Autowired
    private CompanyMoneyLogsMapper moneyLogsMapper;
    @Autowired
    private IFsUserCouponService userCouponService;
    @Autowired
    private IFsCouponService couponService;

    /**
     * 查询问诊订单
     *
     * @param orderId 问诊订单主键
     * @return 问诊订单
     */
    @Override
    public FsInquiryOrder selectFsInquiryOrderByOrderId(Long orderId)
    {
        return fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(orderId);
    }

    /**
     * 查询问诊订单列表
     *
     * @param fsInquiryOrder 问诊订单
     * @return 问诊订单
     */
    @Override
    public List<FsInquiryOrder> selectFsInquiryOrderList(FsInquiryOrder fsInquiryOrder)
    {
        return fsInquiryOrderMapper.selectFsInquiryOrderList(fsInquiryOrder);
    }

    /**
     * 新增问诊订单
     *
     * @param fsInquiryOrder 问诊订单
     * @return 结果
     */
    @Override
    public int insertFsInquiryOrder(FsInquiryOrder fsInquiryOrder)
    {
        fsInquiryOrder.setCreateTime(DateUtils.getNowDate());
        return fsInquiryOrderMapper.insertFsInquiryOrder(fsInquiryOrder);
    }

    /**
     * 修改问诊订单
     *
     * @param fsInquiryOrder 问诊订单
     * @return 结果
     */
    @Override
    public int updateFsInquiryOrder(FsInquiryOrder fsInquiryOrder)
    {
        return fsInquiryOrderMapper.updateFsInquiryOrder(fsInquiryOrder);
    }

    /**
     * 批量删除问诊订单
     *
     * @param orderIds 需要删除的问诊订单主键
     * @return 结果
     */
    @Override
    public int deleteFsInquiryOrderByOrderIds(Long[] orderIds)
    {
        return fsInquiryOrderMapper.deleteFsInquiryOrderByOrderIds(orderIds);
    }

    /**
     * 删除问诊订单信息
     *
     * @param orderId 问诊订单主键
     * @return 结果
     */
    @Override
    public int deleteFsInquiryOrderByOrderId(Long orderId)
    {
        return fsInquiryOrderMapper.deleteFsInquiryOrderByOrderId(orderId);
    }



    @Override
    public List<FsInquiryOrderListVO> selectFsInquiryOrderVOList(FsInquiryOrderParam fsInquiryOrder) {
        return fsInquiryOrderMapper.selectFsInquiryOrderVOList(fsInquiryOrder);
    }

    @Override
    public FsInquiryOrderVO selectFsInquiryOrderVOByOrderId(Long orderId) {
        return fsInquiryOrderMapper.selectFsInquiryOrderVOByOrderId(orderId);
    }

    @Override
    public List<FsInquiryOrderMsg> selectFsInquiryOrderMsgByOrderId(Long orderId) {
        return fsInquiryOrderMapper.selectFsInquiryOrderMsgByOrderId(orderId);
    }

    @Override
    public List<FsInquiryOrderListUVO> selectFsInquiryOrderListUVO(FsInquiryOrderListUParam param) {
        return fsInquiryOrderMapper.selectFsInquiryOrderListUVO(param);
    }

    @Override
    @Transactional
    public R cancelOrder(FsInquiryOrderCancelParam param) {
        logger.info("取消问诊订单:"+param.getOrderId());
        FsInquiryOrder order=fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(param.getOrderId());
        if(order.getStatus().equals(FsInquiryOrderStatusEnum.STATUS_1.getValue())){
            FsInquiryOrder map = new FsInquiryOrder();
            map.setOrderId(order.getOrderId());
            map.setStatus(FsInquiryOrderStatusEnum.STATUS_NE1.getValue());
            fsInquiryOrderMapper.updateFsInquiryOrder(map);
            if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
                FsUserCoupon userCoupon=new FsUserCoupon();
                userCoupon.setStatus(0);
                userCoupon.setId(order.getUserCouponId());
                userCouponMapper.updateFsUserCoupon(userCoupon);
            }
            TemplateBean templateBean = TemplateBean.builder()
                    .orderId(order.getOrderId().toString())
                    .title("订单已取消")
                    .remark("您的订单已取消")
                    .uid(order.getUserId())
                    .templateType(TemplateListenEnum.TYPE_1.getValue())
                    .build();
            publisher.publishEvent(new TemplateEvent(this, templateBean));
        }
        else if(order.getStatus().equals(FsInquiryOrderStatusEnum.STATUS_2.getValue())){
            if(order.getInquiryType().equals(2)){
                //会诊
                FsInquiryOrderReport report=inquiryOrderReportService.selectFsInquiryOrderReportByOrderId(order.getOrderId());
                if(report!=null&&report.getAuditUserId()!=null){
                    throw  new CustomException("问诊中不能取消订单...");
                }
            }
            if(order.getPayMoney().compareTo(new BigDecimal(0))==1){
                //退款
                List<FsStorePayment> payments = fsStorePaymentMapper.selectFsStorePaymentByPay(1,order.getOrderId());
                if(payments!=null&&payments.size()==1){
                    //只支付一笔

                    FsStorePayment payment=payments.get(0);
                    if(payment.getPayMode().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.setKeyPath(wxPayProperties.getKeyPath());
                        payConfig.setSubAppId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                        payConfig.setSubMchId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                        wxPayService.setConfig(payConfig);
                        WxPayRefundRequest refundRequest = new WxPayRefundRequest();
                        refundRequest.setOutTradeNo("inquiry-"+payment.getPayCode());
                        refundRequest.setOutRefundNo("inquiry-"+payment.getPayCode());
                        refundRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(payment.getPayMoney().toString()));
                        refundRequest.setRefundFee(WxPayUnifiedOrderRequest.yuanToFen(payment.getPayMoney().toString()));
                        try {
                            WxPayRefundResult refundResult = wxPayService.refund(refundRequest);
                            WxPayRefundQueryResult refundQueryResult = wxPayService.refundQuery("", refundResult.getOutTradeNo(), refundResult.getOutRefundNo(), refundResult.getRefundId());
                            if(refundQueryResult!=null&&refundQueryResult.getResultCode().equals("SUCCESS")){
                                FsStorePayment paymentMap=new FsStorePayment();
                                paymentMap.setPaymentId(payment.getPaymentId());
                                paymentMap.setStatus(-1);
                                paymentMap.setRefundTime(DateUtils.getNowDate());
                                paymentMap.setRefundMoney(payment.getPayMoney());
                                fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                                FsInquiryOrder map = new FsInquiryOrder();
                                map.setOrderId(order.getOrderId());
                                map.setStatus(FsInquiryOrderStatusEnum.STATUS_NE2.getValue());
                                fsInquiryOrderMapper.updateFsInquiryOrder(map);
                                if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
                                    FsUserCoupon userCoupon=new FsUserCoupon();
                                    userCoupon.setStatus(0);
                                    userCoupon.setId(order.getUserCouponId());
                                    userCouponMapper.updateFsUserCoupon(userCoupon);
                                }
                                TemplateBean templateBean = TemplateBean.builder()
                                        .orderId(order.getOrderId().toString())
                                        .title("订单已取消")
                                        .remark("您的订单已取消")
                                        .uid(order.getUserId())
                                        .templateType(TemplateListenEnum.TYPE_1.getValue())
                                        .build();
                                publisher.publishEvent(new TemplateEvent(this, templateBean));
                            }
                            else {
                                throw new CustomException("退款请求失败"+refundQueryResult.getReturnMsg());
                            }
                        } catch (WxPayException e) {

                            throw new CustomException("退款请求失败"+e.getReturnMsg());
                        }
                    }
                    else if(payment.getPayMode().equals("yb")){
                        //易宝
                        RefundDTO refundDTO=new RefundDTO();
                        refundDTO.setRefundMoney(order.getPayMoney().toString());
                        refundDTO.setLowRefundNo("inquiry-"+order.getOrderSn());
                        refundDTO.setUpOrderId(order.getTradeNo());
                        RefundResult result=payService.refund(refundDTO);
                        if(result.getState().equals("5")){
                            FsStorePayment paymentMap=new FsStorePayment();
                            paymentMap.setPaymentId(payment.getPaymentId());
                            paymentMap.setStatus(-1);
                            paymentMap.setRefundTime(DateUtils.getNowDate());
                            paymentMap.setRefundMoney(payment.getPayMoney());
                            fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                            FsInquiryOrder map = new FsInquiryOrder();
                            map.setOrderId(order.getOrderId());
                            map.setStatus(FsInquiryOrderStatusEnum.STATUS_NE2.getValue());
                            fsInquiryOrderMapper.updateFsInquiryOrder(map);
                            if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
                                FsUserCoupon userCoupon=new FsUserCoupon();
                                userCoupon.setStatus(0);
                                userCoupon.setId(order.getUserCouponId());
                                userCouponMapper.updateFsUserCoupon(userCoupon);
                            }
                            TemplateBean templateBean = TemplateBean.builder()
                                    .orderId(order.getOrderId().toString())
                                    .title("订单已取消")
                                    .remark("您的订单已取消")
                                    .uid(order.getUserId())
                                    .templateType(TemplateListenEnum.TYPE_1.getValue())
                                    .build();
                            publisher.publishEvent(new TemplateEvent(this, templateBean));
                        }
                    }
                    else if(payment.getPayMode().equals("tz")){
                        RefundParam tzBankResult = new RefundParam();
                        // 使用set方法为对象的字段赋值
                        //商户原支付订单号
                        tzBankResult.setOldPayOutOrderNo("inquiry"+payment.getPayCode());
                        // 商户退款订单号 对接平台系统里自己生成的退款订单号
                        tzBankResult.setRefundOrderNo("refund"+payment.getPayCode());
                        // 交易发送时间 yyyyMMddHHmmss
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                        tzBankResult.setTrxSendTime(sdf.format(new Date()));
                        // 退款金额
                        tzBankResult.setRefundOrdTransAmt(payment.getPayMoney().doubleValue());
                        TzBankResult<com.fs.tzBankPay.doman.RefundResult> result = tzBankService.refund(tzBankResult);
                        logger.info("问诊退款返回结果:问诊订单id:"+order.getOrderId()+result);
                        if(result.getBody().getRefundOrdStatus().equals("90")||result.getBody().getRefundOrdStatus().equals("60")){
                            FsStorePayment paymentMap=new FsStorePayment();
                            paymentMap.setPaymentId(payment.getPaymentId());
                            paymentMap.setStatus(-1);
                            paymentMap.setRefundTime(DateUtils.getNowDate());
                            paymentMap.setRefundMoney(payment.getPayMoney());
                            fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                            FsInquiryOrder map = new FsInquiryOrder();
                            map.setOrderId(order.getOrderId());
                            map.setStatus(FsInquiryOrderStatusEnum.STATUS_NE2.getValue());
                            fsInquiryOrderMapper.updateFsInquiryOrder(map);
                            if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
                                FsUserCoupon userCoupon=new FsUserCoupon();
                                userCoupon.setStatus(0);
                                userCoupon.setId(order.getUserCouponId());
                                userCouponMapper.updateFsUserCoupon(userCoupon);
                            }
                            TemplateBean templateBean = TemplateBean.builder()
                                    .orderId(order.getOrderId().toString())
                                    .title("订单已取消")
                                    .remark("您的订单已取消")
                                    .uid(order.getUserId())
                                    .templateType(TemplateListenEnum.TYPE_1.getValue())
                                    .build();
                            publisher.publishEvent(new TemplateEvent(this, templateBean));
                        }
                    }else if(payment.getPayMode().equals("hf")){
                        V2TradePaymentScanpayRefundRequest request = new V2TradePaymentScanpayRefundRequest();
                        request.setOrdAmt(payment.getPayMoney().toString());
                        request.setOrgReqDate(new SimpleDateFormat("yyyyMMdd").format(payment.getCreateTime()));
                        request.setReqSeqId("refund-"+payment.getPayCode());
                        Map<String, Object> extendInfoMap = new HashMap<>();
                        extendInfoMap.put("org_req_seq_id", "inquiry-"+payment.getPayCode());
                        request.setExtendInfo(extendInfoMap);
                        HuiFuRefundResult refund = huiFuService.refund(request);
                        logger.info("问诊退款返回结果:问诊订单id:"+order.getOrderId()+refund);
                        if((refund.getResp_code().equals("00000000")||refund.getResp_code().equals("00000100"))&&(refund.getTrans_stat().equals("S")||refund.getTrans_stat().equals("P"))){
                            FsStorePayment paymentMap=new FsStorePayment();
                            paymentMap.setPaymentId(payment.getPaymentId());
                            paymentMap.setStatus(-1);
                            paymentMap.setRefundTime(DateUtils.getNowDate());
                            paymentMap.setRefundMoney(payment.getPayMoney());
                            fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                            FsInquiryOrder map = new FsInquiryOrder();
                            map.setOrderId(order.getOrderId());
                            map.setStatus(FsInquiryOrderStatusEnum.STATUS_NE2.getValue());
                            fsInquiryOrderMapper.updateFsInquiryOrder(map);
                            if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
                                FsUserCoupon userCoupon=new FsUserCoupon();
                                userCoupon.setStatus(0);
                                userCoupon.setId(order.getUserCouponId());
                                userCouponMapper.updateFsUserCoupon(userCoupon);
                            }
                            TemplateBean templateBean = TemplateBean.builder()
                                    .orderId(order.getOrderId().toString())
                                    .title("订单已取消")
                                    .remark("您的订单已取消")
                                    .uid(order.getUserId())
                                    .templateType(TemplateListenEnum.TYPE_1.getValue())
                                    .build();
                            publisher.publishEvent(new TemplateEvent(this, templateBean));
                        }
                    }
                }

            }
            else {
                FsInquiryOrder map = new FsInquiryOrder();
                map.setOrderId(order.getOrderId());
                map.setStatus(FsInquiryOrderStatusEnum.STATUS_NE1.getValue());
                fsInquiryOrderMapper.updateFsInquiryOrder(map);
                if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
                    FsUserCoupon userCoupon=new FsUserCoupon();
                    userCoupon.setStatus(0);
                    userCoupon.setId(order.getUserCouponId());
                    userCouponMapper.updateFsUserCoupon(userCoupon);
                }
                TemplateBean templateBean = TemplateBean.builder()
                        .orderId(order.getOrderId().toString())
                        .title("订单已取消")
                        .remark("您的订单已取消")
                        .uid(order.getUserId())
                        .templateType(TemplateListenEnum.TYPE_1.getValue())
                        .build();
                publisher.publishEvent(new TemplateEvent(this, templateBean));

            }
        }
        else{
            throw  new CustomException("非法操作");
        }
        //日志
        FsInquiryOrderLogs log = new FsInquiryOrderLogs();
        log.setOrderId(order.getOrderId());
        if(param.getType().equals(1)){
            log.setChangeMessage("用户取消订单");
            log.setChangeType("用户取消订单");
            log.setOperator("用户");
        }
        else if(param.getType().equals(2)){
            log.setChangeMessage("未支付系统自动取消订单");
            log.setChangeType("未支付取消订单");
            log.setOperator("系统");
        }
        else if(param.getType().equals(3)){
            log.setChangeMessage("未接单系统自动取消订单");
            log.setChangeType("未接单取消订单");
            log.setOperator("系统");
        } else if(param.getType().equals(4)){
            log.setChangeMessage("平台操作取消订单");
            log.setChangeType("平台取消订单");
            log.setOperator(SecurityUtils.getLoginUser().getUser().getNickName());
        }else if(param.getType().equals(5)){
            log.setChangeMessage("销售公司操作取消订单");
            log.setChangeType("销售公司取消订单");
            log.setOperator("销售人员");
        }else if(param.getType().equals(6)){
            log.setChangeMessage("医生取消订单");
            log.setChangeType("医生取消订单");
            log.setOperator("医生");
        }
        fsInquiryOrderLogsService.insertFsInquiryOrderLogs(log);
        return R.ok("操作成功");
    }

    @Override
    @Transactional
    public R createOrder(FsInquiryOrderCreateParam param) {
        FsUser user=userMapper.selectFsUserByUserId(param.getUserId());
        if(user.getStatus()!=1){
            return R.error("非法用户操作");
        }
        String orderKey= redisCache.getCacheObject("orderKey:"+param.getOrderKey());
        if (StringUtils.isEmpty(orderKey)) {
            return R.error("订单已过期");
        }
        FsPatient patient=fsPatientMapper.selectFsPatientByPatientId(param.getPatientId());
        if(patient==null){
            return R.error("患者不能为空");
        }
        FsInquiryOrderPatientDTO dto=new FsInquiryOrderPatientDTO();
        BeanUtils.copyProperties(patient,dto);
        dto.setAge(String.valueOf( DateUtil.ageOfNow(patient.getBirthday())));

        // 使用 SimpleDateFormat 格式化日期对象
        dto.setBirthday(new SimpleDateFormat("yyyy-MM-dd").format(patient.getBirthday()));
        dto.setDuration(param.getDuration());
        dto.setReportImages(param.getReportImages());
        dto.setTongueImages(param.getTongueImages());
        dto.setFaceImages(param.getFaceImages());
        dto.setHandImages(param.getHandImages());
        dto.setTitle(param.getTitle());
        dto.setIsVisit(param.getIsVisit());
        dto.setHeight(param.getHeight());
        dto.setWeight(param.getWeight());
        if(StringUtils.isEmpty(param.getMobile())){
            if (patient.getMobile()!=null&&patient.getMobile().length()==11&&patient.getMobile().matches("\\d+")){
                dto.setMobile(encryptPhone(patient.getMobile()));
            }else {
                dto.setMobile(patient.getMobile());
            }
        }
        else{

            if (param.getMobile()!=null&&param.getMobile().length()==11&&param.getMobile().matches("\\d+")){
                dto.setMobile(encryptPhone(param.getMobile()));
            }else {
                dto.setMobile(param.getMobile());
            }
        }

        dto.setUsage(param.getUsage());
        dto.setMedication(param.getMedication());
        FsInquiryOrder order=new FsInquiryOrder();
        String orderSn =  OrderCodeUtils.getOrderSn();
        if(StringUtils.isEmpty(orderSn)) {
            return R.error("订单生成失败，请重试");
        }
        order.setOrderSn(orderSn);
        order.setOrderType(param.getOrderType());
        order.setInquiryType(param.getInquiryType());
        order.setTitle(param.getTitle());
        order.setUserId(param.getUserId());
        order.setPatientId(patient.getPatientId());
        order.setInquirySubType(param.getInquirySubType());
        if (param.getSource()!=null){
            order.setSource(param.getSource());
        }
        FsInquiryOrderReport report=null;
        String json=configService.selectConfigByKey("his.inquiryConfig");
        InquiryConfigDTO configDTO=JSONUtil.toBean(json, InquiryConfigDTO.class);
        if(param.getInquiryType().equals(1)){
            FsDoctor doctor=doctorMapper.selectFsDoctorByDoctorId(param.getDoctorId());
            if(doctor==null||doctor.getStatus()==0){
                return R.error("医生不存在或已被禁用");
            }
            else{
                if(doctor.getWorkStatus()!=1){
                    return R.error("医生已停诊");
                }
                if(doctor.getPriceJson()==null){
                    return R.error("医生未设置价格");
                }

                Integer orderCount=fsInquiryOrderMapper.checkAcceptOrder(param.getDoctorId(),param.getUserId());
                if(orderCount>0){
                    return R.error("您正在咨询此医生,不能下单");
                }

                List<FsPriceDTO> priceDTOList= JSONUtil.parseArray(doctor.getPriceJson()).toList(FsPriceDTO.class);
                List<FsPriceDTO> doctorPrice = priceDTOList.stream().filter(x -> x.getType().equals(param.getOrderType())).collect(Collectors.toList());
                if(doctorPrice!=null&&doctorPrice.size()==1){
                    order.setMoney(doctorPrice.get(0).getPrice());
                    order.setPayMoney(doctorPrice.get(0).getPrice());
                }
                order.setDoctorId(doctor.getDoctorId());
                order.setDepartmentId(doctor.getDeptId());
                order.setIsReceive(1);

            }
            order.setIsAudit(1);
        }
        else if(param.getInquiryType().equals(2)){
            //快速

            List<FsPriceDTO> price = configDTO.getPrices().stream().filter(x -> x.getType().equals(param.getOrderType())).collect(Collectors.toList());
            if(price!=null&&price.size()==1){
                order.setMoney(price.get(0).getPrice());
                order.setPayMoney(price.get(0).getPrice());
            }
            order.setIsReceive(0);
            if(param.getInquirySubType().equals(3)){
                //写入表单报告
                String reportSn =  OrderCodeUtils.getOrderSn();
                if(StringUtils.isEmpty(reportSn)){
                    return R.error("订单生成失败，请重试");
                }
                report=new FsInquiryOrderReport();
                report.setUserId(order.getUserId());
                report.setPatientId(order.getPatientId());
                report.setPatientJson(JSONUtil.toJsonStr(dto));
                report.setReportSn(reportSn);
                report.setStatus(1);
                order.setIsAudit(1);
            }
            else{
                //写入表单报告
                String reportSn =  OrderCodeUtils.getOrderSn();
                if(StringUtils.isEmpty(reportSn)){
                    return R.error("订单生成失败，请重试");
                }
                report=new FsInquiryOrderReport();
                report.setUserId(order.getUserId());
                report.setPatientId(order.getPatientId());
                report.setPatientJson(JSONUtil.toJsonStr(dto));
                report.setReportSn(reportSn);
                report.setStatus(0);
                order.setIsAudit(0);
            }

        }
        else if(param.getInquiryType().equals(3)){
            //开药

            List<FsPriceDTO> price = configDTO.getPrices().stream().filter(x -> x.getType().equals(param.getOrderType())).collect(Collectors.toList());
            if(price!=null&&price.size()==1){
                order.setMoney(price.get(0).getPrice());
                order.setPayMoney(price.get(0).getPrice());
            }
            order.setIsReceive(0);
            order.setIsAudit(1);
        }
        order.setStatus(1);
        order.setIsPay(0);
        order.setCreateTime(new Date());
        order.setIsPing(0);
        if(param.getCompanyId()!=null){
            Company company=companyService.selectCompanyById(param.getCompanyId());
            if(company!=null&&company.getStatus().equals(1)){
                CompanyUser companyUser=companyUserService.selectCompanyUserById(param.getCompanyUserId());
                if(companyUser!=null&&companyUser.getStatus().equals("0")){
                    BigDecimal money=order.getMoney();
                    order.setCompanyId(param.getCompanyId());
                    order.setCompanyUserId(param.getCompanyUserId());
                    order.setMoney(new BigDecimal(0.1));
                    order.setPayMoney(new BigDecimal(0.1));
                    order.setCompanyDeductMoney(money);
                    if (companyUser.getDeptId()!=null){
                        order.setDeptId(companyUser.getDeptId());
                    }
                }



            }
        }
        order.setPatientJson(JSONUtil.toJsonStr(dto));
        if(fsInquiryOrderMapper.insertFsInquiryOrder(order)>0){
            if(report!=null){
                report.setOrderId(order.getOrderId());
                inquiryOrderReportService.insertFsInquiryOrderReport(report);
            }
            redisCache.deleteObject("orderKey:" + param.getOrderKey());

            if(configDTO.getUnPayCancelTime()!=null&&configDTO.getUnPayCancelTime()>0){
                String redisKey = String.valueOf(StrUtil.format("{}{}", FsConstants.REDIS_INQUIRY_ORDER_OUTTIME_UNPAY, order.getOrderId()));
                redisCache.setCacheObject(redisKey,order.getOrderId(),configDTO.getUnPayCancelTime(), TimeUnit.MINUTES);
            }

            return R.ok().put("order",order);
        }
        else{
            return R.error("创建失败");
        }
    }

    @Override
    @Transactional
    public R payConfirm(String orderSn,String payCode, String tradeNo,String payType,Integer type) {
        try {
            FsInquiryOrder order=null;
            if(type.equals(1)){
                FsStorePayment storePayment = fsStorePaymentMapper.selectFsStorePaymentByPaymentCode(payCode);
                if (storePayment!=null){
                    if(storePayment.getStatus().equals(0)){
                        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);
                        order=fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(Long.parseLong(storePayment.getBusinessId()));
                    }
                }
                else{

                    return R.error("支付单号不存在");
                }
            }
            else if(type.equals(2)){
                order=fsInquiryOrderMapper.selectFsInquiryOrderByOrderSn(orderSn);
            }
            if(!order.getStatus().equals(FsInquiryOrderStatusEnum.STATUS_1.getValue())){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error("非法操作");
            }
            FsInquiryOrder map = new FsInquiryOrder();
            map.setOrderId(order.getOrderId());
            map.setIsPay(1);
            map.setPayType(1);
            map.setStatus(FsInquiryOrderStatusEnum.STATUS_2.getValue());
            map.setPayTime(new Date());
            map.setTradeNo(tradeNo);
            fsInquiryOrderMapper.updateFsInquiryOrder(map);
            try {
                FsUser fsUser = userMapper.selectFsUserByUserId(order.getUserId());
                imService.addAccount(fsUser.getUserId(),fsUser.getAvatar(),fsUser.getNickName());
            }catch (Exception e){
            }
            if(order.getDoctorId()!=null&&order.getIsAudit()==1&&order.getIsReceive()==1){
                FsDoctor doctor=doctorMapper.selectFsDoctorByDoctorId(order.getDoctorId());
                if(StringUtils.isNotEmpty(doctor.getJpushId())){
                    Map<String, String> extrasMap=new HashMap<>();
                    extrasMap.put("orderId",order.getOrderId().toString());
                    extrasMap.put("type","1");
                    try {
                        jpushService.sendRegisterIdPush("问诊订单消息","您有一个新的问诊订单",extrasMap,doctor.getJpushId());
                    } catch (APIConnectionException e) {
                    } catch (APIRequestException e) {
                    }
                }
            }
            else if(order.getIsAudit()==1&&order.getIsReceive()==0){
                //抢单，发送给所有医生

            }
            //写日志
            FsInquiryOrderLogs log = new FsInquiryOrderLogs();
            log.setOrderId(order.getOrderId());
            log.setChangeMessage("用户支付订单");
            log.setChangeType("用户支付");
            log.setOperator("用户");
            fsInquiryOrderLogsService.insertFsInquiryOrderLogs(log);
            String json=configService.selectConfigByKey("his.inquiryConfig");
            InquiryConfigDTO configDTO=JSONUtil.toBean(json, InquiryConfigDTO.class);
            if(configDTO.getUnReceiveCancelTime()!=null&&configDTO.getUnReceiveCancelTime()>0){
                String redisKey = String.valueOf(StrUtil.format("{}{}", FsConstants.REDIS_INQUIRY_ORDER_OUTTIME_UNRECEIVE, order.getOrderId()));
                redisCache.setCacheObject(redisKey,order.getOrderId(),configDTO.getUnReceiveCancelTime(), TimeUnit.MINUTES);
            }
            return R.ok();
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            FsStorePaymentError err = new FsStorePaymentError();
            err.setOrderNo(orderSn);
            err.setOrderFlowNo(tradeNo);
            err.setStatus(0);
            err.setMsg(e.getMessage());
            err.setCreateTime(DateUtils.getNowDate());
            fsStorePaymentErrorMapper.insertFsStorePaymentError(err);
            return R.error();
        }

    }

    @Override
    public R confirmOrder(FsInquiryOrderConfirmParam param) {
        String uuid = IdUtil.randomUUID();
        redisCache.setCacheObject("orderKey:"+uuid,uuid,200, TimeUnit.MINUTES);
        return R.ok().put("orderKey",uuid);
    }

    @Override
    public List<FsInquiryOrderListDVO> selectFsInquiryOrderListDVO(FsInquiryOrderListDParam param) {
        return fsInquiryOrderMapper.selectFsInquiryOrderListDVO(param);
    }

    @Override
    @Transactional
    @Synchronized
    public R acceptOrder(FsInquiryOrderAcceptParam param) {
        FsInquiryOrder order=fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(param.getOrderId());
        if(!order.getStatus().equals(FsInquiryOrderStatusEnum.STATUS_2.getValue())){
            return R.error("非法操作");
        }
        if(order.getInquiryType().equals(1)){
            return R.error("非法操作");
        }
        if(order.getIsReceive().equals(1)){
            return R.error("此单已被抢走");
        }
        Integer orderCount=fsInquiryOrderMapper.checkAcceptOrder(param.getDoctorId(),order.getUserId());
        if(orderCount>0){
            return R.error("您正在为此患者服务，不能接单");
        }
        FsInquiryOrder map=new FsInquiryOrder();
        map.setOrderId(order.getOrderId());
        map.setDoctorId(param.getDoctorId());
        map.setIsReceive(1);
        map.setStatus(3);
        map.setStartTime(new Date());
        fsInquiryOrderMapper.updateFsInquiryOrder(map);

        TemplateBean templateBean = TemplateBean.builder()
                .orderId(order.getOrderId().toString())
                .title("问诊订单医生已接单")
                .remark("您的问诊订单,订单号:"+order.getOrderSn()+"医生已接单")
                .uid(order.getUserId())
                .templateType(TemplateListenEnum.TYPE_2.getValue())
                .build();
        publisher.publishEvent(new TemplateEvent(this, templateBean));

        if (order.getInquiryType()!=2){
            FsInquiryOrderPatientDTO patientDTO = JSON.parseObject(order.getPatientJson(),FsInquiryOrderPatientDTO.class);
            if (patientDTO!=null&&patientDTO.getPatientName()!=null){
                FsUser fsUser = fsUserService.selectFsUserByUserId(order.getUserId());
                if (fsUser!=null&&fsUser.getPhone()!=null){
                    logger.info("医生接单发送短信:"+fsUser.getPhone()+patientDTO.getPatientName());
                    smsService.sendUserSms(fsUser.getPhone(), patientDTO.getPatientName(), "3");
                }

            }
        }
        MsgDTO msgDTO=new MsgDTO();
        MsgCustomDTO customDTO=new MsgCustomDTO();
        customDTO.setType("startInquiry");
        customDTO.setOrderType(order.getOrderType());
        customDTO.setOrderId(order.getOrderId().toString());
        customDTO.setImType(1);
        msgDTO.setCloudCustomData(JSONUtil.toJsonStr(customDTO));
        msgDTO.setFrom_Account("D-"+param.getDoctorId());
        msgDTO.setTo_Account("U-"+order.getUserId());
        List<MsgDataDTO> msgs=new ArrayList<>();
        MsgDataDTO msg=new MsgDataDTO();
        msg.setMsgType("TIMCustomElem");
        FsDoctor doctor=doctorMapper.selectFsDoctorByDoctorId(param.getDoctorId());
        String doc="医生";
        if (doctor.getDeptId()!=null&&doctor.getDeptId().compareTo(39L)==0){
            doc="药师";
        }
        InquiryOrderMsgDTO inquiryOrderMsgDTO=new InquiryOrderMsgDTO();
        inquiryOrderMsgDTO.setTitle(doctor.getDoctorName()+doc+"为您服务");
        String ext= JSONUtil.toJsonStr(inquiryOrderMsgDTO);
        msg.setMsgContent(new MsgDataFormatDTO("startInquiry",ext,order.getOrderId().toString()));
        msgs.add(msg);
        msgDTO.setMsgBody(msgs);
        imService.sendMsg(msgDTO);


        if (doc.equals("药师")){
            MsgDTO msgDTO1=new MsgDTO();
            MsgCustomDTO customDTO1=new MsgCustomDTO();
            customDTO1.setType("startInquiry");
            customDTO1.setOrderType(order.getOrderType());
            customDTO1.setOrderId(order.getOrderId().toString());
            customDTO1.setImType(1);
            msgDTO1.setCloudCustomData(JSONUtil.toJsonStr(customDTO1));
            msgDTO1.setFrom_Account("D-"+param.getDoctorId());
            msgDTO1.setTo_Account("U-"+order.getUserId());
            List<MsgDataDTO> msgs1=new ArrayList<>();
            MsgDataDTO msg1=new MsgDataDTO();
            msg1.setMsgType("TIMTextElem");
            MsgDataFormatDTO dto1=new MsgDataFormatDTO("您好，我是芸医汇互联网医院执业药师，请问您有什么问题想咨询?");
            msg1.setMsgContent(dto1);
            msgs1.add(msg1);
            msgDTO1.setMsgBody(msgs1);
            imService.sendMsg(msgDTO1);
        }





        FsInquiryOrderLogs log = new FsInquiryOrderLogs();
        log.setOrderId(order.getOrderId());
        log.setChangeMessage(doc+"已接单");
        log.setChangeType(doc+"已接单");
        log.setOperator(doctor.getDoctorName()+doc);
        fsInquiryOrderLogsService.insertFsInquiryOrderLogs(log);
//        try {
//            TemplateBean templateBean = TemplateBean.builder()
//                    .orderId(order.getOrderId().toString())
//                    .title("订单已接单")
//                    .remark("您的订单 医生已接单")
//                    .uid(order.getUserId())
//                    .templateType(TemplateListenEnum.TYPE_2.getValue())
//                    .build();
//            publisher.publishEvent(new TemplateEvent(this, templateBean));
//
//        }
//        catch (Exception e){
//
//        }

        //发送给医生
//        MsgDTO msgDTO1=new MsgDTO();
//        MsgCustomDTO customDTO1=new MsgCustomDTO();
//        customDTO.setType("startInquiry");
//        customDTO.setOrderId(order.getOrderId().toString());
//        msgDTO1.setCloudCustomData(JSONUtil.toJsonStr(customDTO1));
//        msgDTO1.setFrom_Account("U-"+order.getUserId());
//        msgDTO1.setTo_Account("D-"+order.getDoctorId());
//        List<MsgDataDTO> msgs1=new ArrayList<>();
//        MsgDataDTO msg1=new MsgDataDTO();
//        msg1.setMsgType("TIMCustomElem");
//        InquiryOrderMsgDTO inquiryOrderMsgDTO1=new InquiryOrderMsgDTO();
//        inquiryOrderMsgDTO1.setTitle("咨询:"+order.getTitle());
//        String ext1= JSONUtil.toJsonStr(inquiryOrderMsgDTO1);
//        msg1.setMsgContent(new MsgDataFormatDTO("startInquiry",ext1,order.getOrderId().toString()));
//        msgs1.add(msg1);
//        msgDTO1.setMsgBody(msgs1);
//        imService.sendMsg(msgDTO1);

        fsDoctorService.addFsDoctorOrderNumberByDoctorId(param.getDoctorId());

        return R.ok("抢单成功");
    }

    @Override
    @Transactional
    public R receiveOrder(FsInquiryOrderReceiveParam param) {
        FsInquiryOrder order=fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(param.getOrderId());
        if(!order.getStatus().equals(FsInquiryOrderStatusEnum.STATUS_2.getValue())){
            return R.error("非法操作");
        }
        Integer orderCount=fsInquiryOrderMapper.checkAcceptOrder(param.getDoctorId(),order.getUserId());
        if(orderCount>0){
            return R.error("您正在为此患者服务，不能接单");
        }
        FsInquiryOrder map=new FsInquiryOrder();
        map.setOrderId(order.getOrderId());
        map.setStatus(3);
        map.setStartTime(new Date());
        fsInquiryOrderMapper.updateFsInquiryOrder(map);
        TemplateBean templateBean = TemplateBean.builder()
                .orderId(order.getOrderId().toString())
                .title("问诊订单医生已接单")
                .remark("您的问诊订单,订单号:"+order.getOrderSn()+"医生已接单")
                .uid(order.getUserId())
                .templateType(TemplateListenEnum.TYPE_2.getValue())
                .build();
        publisher.publishEvent(new TemplateEvent(this, templateBean));


        if (order.getInquiryType()!=2){
            FsInquiryOrderPatientDTO patientDTO = JSON.parseObject(order.getPatientJson(),FsInquiryOrderPatientDTO.class);
            if (patientDTO!=null&&patientDTO.getPatientName()!=null){
                FsUser fsUser = fsUserService.selectFsUserByUserId(order.getUserId());
                if (fsUser!=null&&fsUser.getPhone()!=null){
                    logger.info("医生接单发送短信:"+fsUser.getPhone()+patientDTO.getPatientName());
                    smsService.sendUserSms(fsUser.getPhone(), patientDTO.getPatientName(), "3");
                }

            }
        }
        MsgDTO msgDTO=new MsgDTO();
        MsgCustomDTO customDTO=new MsgCustomDTO();
        customDTO.setType("startInquiry");
        customDTO.setImType(1);
        customDTO.setOrderType(order.getOrderType());
        customDTO.setOrderId(order.getOrderId().toString());
        msgDTO.setCloudCustomData(JSONUtil.toJsonStr(customDTO));
        msgDTO.setFrom_Account("D-"+order.getDoctorId());
        msgDTO.setTo_Account("U-"+order.getUserId());
        List<MsgDataDTO> msgs=new ArrayList<>();
        MsgDataDTO msg=new MsgDataDTO();
        msg.setMsgType("TIMCustomElem");
        FsDoctor doctor=doctorMapper.selectFsDoctorByDoctorId(param.getDoctorId());

        String doc="医生";
        if (doctor.getDeptId()!=null&&doctor.getDeptId().compareTo(39L)==0){
            doc="药师";
        }
        InquiryOrderMsgDTO inquiryOrderMsgDTO=new InquiryOrderMsgDTO();
        inquiryOrderMsgDTO.setTitle(doctor.getDoctorName()+doc+"为您服务");
        String ext= JSONUtil.toJsonStr(inquiryOrderMsgDTO);
        msg.setMsgContent(new MsgDataFormatDTO("startInquiry",ext,order.getOrderId().toString()));
        msgs.add(msg);
        msgDTO.setMsgBody(msgs);
        imService.sendMsg(msgDTO);
        if (doc.equals("药师")){
            MsgDTO msgDTO1=new MsgDTO();
            MsgCustomDTO customDTO1=new MsgCustomDTO();
            customDTO1.setType("startInquiry");
            customDTO1.setImType(1);
            customDTO1.setOrderType(order.getOrderType());
            customDTO1.setOrderId(order.getOrderId().toString());
            msgDTO1.setCloudCustomData(JSONUtil.toJsonStr(customDTO1));
            msgDTO1.setFrom_Account("D-"+param.getDoctorId());
            msgDTO1.setTo_Account("U-"+order.getUserId());
            List<MsgDataDTO> msgs1=new ArrayList<>();
            MsgDataDTO msg1=new MsgDataDTO();
            msg1.setMsgType("TIMTextElem");
            MsgDataFormatDTO dto1=new MsgDataFormatDTO("您好，我是芸医汇互联网医院执业药师，请问您有什么问题想咨询?");
            msg1.setMsgContent(dto1);
            msgs1.add(msg1);
            msgDTO1.setMsgBody(msgs1);
            imService.sendMsg(msgDTO1);
        }
        //发送给医生
//        MsgDTO msgDTO1=new MsgDTO();
//        MsgCustomDTO customDTO1=new MsgCustomDTO();
//        customDTO.setType("startInquiry");
//        customDTO.setOrderId(order.getOrderId().toString());
//        msgDTO1.setCloudCustomData(JSONUtil.toJsonStr(customDTO1));
//        msgDTO1.setFrom_Account("U-"+order.getUserId());
//        msgDTO1.setTo_Account("D-"+order.getDoctorId());
//        List<MsgDataDTO> msgs1=new ArrayList<>();
//        MsgDataDTO msg1=new MsgDataDTO();
//        msg1.setMsgType("TIMCustomElem");
//        InquiryOrderMsgDTO inquiryOrderMsgDTO1=new InquiryOrderMsgDTO();
//        inquiryOrderMsgDTO1.setTitle("咨询:"+order.getTitle());
//        String ext1= JSONUtil.toJsonStr(inquiryOrderMsgDTO1);
//        msg1.setMsgContent(new MsgDataFormatDTO("startInquiry",ext1,order.getOrderId().toString()));
//        msgs1.add(msg1);
//        msgDTO1.setMsgBody(msgs1);
//        imService.sendMsg(msgDTO1);


        FsInquiryOrderLogs log = new FsInquiryOrderLogs();
        log.setOrderId(order.getOrderId());
        log.setChangeMessage(doc+"已接单");
        log.setChangeType(doc+"已接单");
        log.setOperator(doctor.getDoctorName()+doc);
        fsInquiryOrderLogsService.insertFsInquiryOrderLogs(log);

        fsDoctorService.addFsDoctorOrderNumberByDoctorId(param.getDoctorId());
        return R.ok("接诊成功");
    }

    @Override
    @Transactional
    public R refuseOrder(FsInquiryOrderRefuseParam param) {
        FsInquiryOrder order=fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(param.getOrderId());
        if(!order.getStatus().equals(FsInquiryOrderStatusEnum.STATUS_2.getValue())){
            return R.error("非法操作");
        }
        FsInquiryOrderCancelParam cancelParam=new FsInquiryOrderCancelParam();
        cancelParam.setType(6);
        cancelParam.setOrderId(order.getOrderId());
        this.cancelOrder(cancelParam);
        FsInquiryOrder map=new FsInquiryOrder();
        map.setOrderId(order.getOrderId());
        map.setStatus(-3);
        fsInquiryOrderMapper.updateFsInquiryOrder(map);
        //退款
//
//        if(order.getPayMoney().compareTo(new BigDecimal(0))==1){
//            RefundDTO refundDTO=new RefundDTO();
//            refundDTO.setRefundMoney(order.getPayMoney().toString());
//            refundDTO.setLowRefundNo("refund-"+order.getOrderSn());
//            refundDTO.setUpOrderId(order.getTradeNo());
//            RefundResult result=payService.refund(refundDTO);
//            if(result.getState().equals("5")){
//                if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
//                    FsUserCoupon userCoupon=new FsUserCoupon();
//                    userCoupon.setStatus(0);
//                    userCoupon.setId(order.getUserCouponId());
//                    userCouponMapper.updateFsUserCoupon(userCoupon);
//                }
//            }
//        }
//        else {
//            if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
//                FsUserCoupon userCoupon=new FsUserCoupon();
//                userCoupon.setStatus(0);
//                userCoupon.setId(order.getUserCouponId());
//                userCouponMapper.updateFsUserCoupon(userCoupon);
//            }
//
//
//        }
        TemplateBean templateBean = TemplateBean.builder()
                .orderId(order.getOrderId().toString())
                .title("问诊订单已取消")
                .remark("您的问诊订单,订单号:"+order.getOrderSn()+",医生已取消订单")
                .uid(order.getUserId())
                .templateType(TemplateListenEnum.TYPE_1.getValue())
                .build();
        publisher.publishEvent(new TemplateEvent(this, templateBean));


        FsDoctor doctor=doctorMapper.selectFsDoctorByDoctorId(param.getDoctorId());
        FsInquiryOrderLogs log = new FsInquiryOrderLogs();
        log.setOrderId(order.getOrderId());
        log.setChangeMessage("医生已拒订单");
        log.setChangeType("医生已拒订单");
        log.setOperator(doctor.getDoctorName()+"医生");
        fsInquiryOrderLogsService.insertFsInquiryOrderLogs(log);
        return R.ok();
    }

    @Override
    @Transactional
    public R finishOrder(FsInquiryOrderFinishParam param) {
        FsInquiryOrder order=fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(param.getOrderId());
        if(!order.getStatus().equals(FsInquiryOrderStatusEnum.STATUS_3.getValue())){
            return R.error("非法操作");
        }
        FsInquiryOrder map=new FsInquiryOrder();
        map.setOrderId(order.getOrderId());
        map.setStatus(4);
        map.setFinishTime(new Date());
        fsInquiryOrderMapper.updateFsInquiryOrder(map);
        fsUserService.addUserIntegral(order.getPayMoney(),order.getUserId(),order.getOrderId(),1);
//        CompanyMoneyLogs moneyLogs = moneyLogsMapper.selectCompanyMoneyByInquiry(order.getOrderId());
//        if (moneyLogs==null){
//            companyService.inquirySubtractCompanyMoney(order);
//        }
        //发送给用户
        MsgDTO msgDTO=new MsgDTO();
        MsgCustomDTO customDTO=new MsgCustomDTO();
        customDTO.setType("finishInquiry");
        customDTO.setOrderId(order.getOrderId().toString());
        customDTO.setImType(0);
        msgDTO.setCloudCustomData(JSONUtil.toJsonStr(customDTO));
        msgDTO.setFrom_Account("D-"+order.getDoctorId());
        msgDTO.setTo_Account("U-"+order.getUserId());
        List<MsgDataDTO> msgs=new ArrayList<>();
        MsgDataDTO msg=new MsgDataDTO();
        msg.setMsgType("TIMCustomElem");
        FsDoctor doctor=doctorMapper.selectFsDoctorByDoctorId(param.getDoctorId());
        FsInquiryOrderLogs log = new FsInquiryOrderLogs();
        log.setOrderId(order.getOrderId());
        log.setChangeMessage("医生完成订单");
        log.setChangeType("医生完成订单");
        log.setOperator(doctor.getDoctorName()+"医生");
        fsInquiryOrderLogsService.insertFsInquiryOrderLogs(log);
        InquiryOrderMsgDTO inquiryOrderMsgDTO=new InquiryOrderMsgDTO();
        inquiryOrderMsgDTO.setTitle("问诊结束");
        String ext= JSONUtil.toJsonStr(inquiryOrderMsgDTO);
        msg.setMsgContent(new MsgDataFormatDTO("finishInquiry",ext,order.getOrderId().toString()));
        msgs.add(msg);
        msgDTO.setMsgBody(msgs);
        imService.sendMsg(msgDTO);
        //发送给医生
//        MsgDTO msgDTO1=new MsgDTO();
//        MsgCustomDTO customDTO1=new MsgCustomDTO();
//        customDTO1.setType("finishInquiry");
//        customDTO1.setOrderId(order.getOrderId().toString());
//        msgDTO1.setCloudCustomData(JSONUtil.toJsonStr(customDTO1));
//        msgDTO1.setFrom_Account("U-"+order.getUserId());
//        msgDTO1.setTo_Account("D-"+order.getDoctorId());
//        List<MsgDataDTO> msgs1=new ArrayList<>();
//        MsgDataDTO msg1=new MsgDataDTO();
//        msg1.setMsgType("TIMCustomElem");
//        msg1.setMsgContent(new MsgDataFormatDTO("finishInquiry",ext,order.getOrderId().toString()));
//        msgs1.add(msg1);
//        msgDTO1.setMsgBody(msgs1);
//        imService.sendMsg(msgDTO1);
        redisTemplate.delete("DrugReport:doctorId:" + order.getDoctorId() + ":userId:" + order.getUserId());
        //todo 将金额写入医生佣金
        return R.ok("接诊成功");
    }
    @Override
    @Transactional
    public R autoFinishOrder(FsInquiryOrderFinishParam param) {
        FsInquiryOrder order=fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(param.getOrderId());
        if(!order.getStatus().equals(FsInquiryOrderStatusEnum.STATUS_3.getValue())){
            return R.error("非法操作");
        }
        FsInquiryOrder map=new FsInquiryOrder();
        map.setOrderId(order.getOrderId());
        map.setStatus(4);
        map.setFinishTime(new Date());
        fsInquiryOrderMapper.updateFsInquiryOrder(map);
        fsUserService.addUserIntegral(order.getPayMoney(),order.getUserId(),order.getOrderId(),1);
//        CompanyMoneyLogs moneyLogs = moneyLogsMapper.selectCompanyMoneyByInquiry(order.getOrderId());
//        if (moneyLogs==null){
//            companyService.inquirySubtractCompanyMoney(order);
//        }
        MsgDTO msgDTO=new MsgDTO();
        MsgCustomDTO customDTO=new MsgCustomDTO();
        customDTO.setType("finishInquiry");
        customDTO.setOrderId(order.getOrderId().toString());
        customDTO.setImType(0);
        msgDTO.setCloudCustomData(JSONUtil.toJsonStr(customDTO));
        msgDTO.setFrom_Account("D-"+order.getDoctorId());
        msgDTO.setTo_Account("U-"+order.getUserId());
        List<MsgDataDTO> msgs=new ArrayList<>();
        MsgDataDTO msg=new MsgDataDTO();
        msg.setMsgType("TIMCustomElem");
        FsDoctor doctor=doctorMapper.selectFsDoctorByDoctorId(param.getDoctorId());
        FsInquiryOrderLogs log = new FsInquiryOrderLogs();
        log.setOrderId(order.getOrderId());
        log.setChangeMessage("医生完成订单");
        log.setChangeType("医生完成订单");
        log.setOperator(doctor.getDoctorName()+"医生");
        fsInquiryOrderLogsService.insertFsInquiryOrderLogs(log);
        InquiryOrderMsgDTO inquiryOrderMsgDTO=new InquiryOrderMsgDTO();
        inquiryOrderMsgDTO.setTitle("由于您长时间未回复，本次咨询自动结束");
        String ext= JSONUtil.toJsonStr(inquiryOrderMsgDTO);
        msg.setMsgContent(new MsgDataFormatDTO("finishInquiry",ext,order.getOrderId().toString()));
        msgs.add(msg);
        msgDTO.setMsgBody(msgs);
        imService.sendMsg(msgDTO);
        redisTemplate.delete("DrugReport:doctorId:" + order.getDoctorId() + ":userId:" + order.getUserId());
        return R.ok();
    }

    @Override
    @Transactional
    @Synchronized
    public R pingOrder(FsInquiryOrderPingParam param) {
        FsInquiryOrder order=fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(param.getOrderId());
        if(!order.getStatus().equals(FsInquiryOrderStatusEnum.STATUS_4.getValue())){
            return R.error("非法操作");
        }
        if(order.getIsPing()==1){
            return R.error("已评价");
        }

        FsInquiryOrderPing ping=new FsInquiryOrderPing();
        ping.setOrderId(order.getOrderId());
        ping.setDoctorId(order.getDoctorId());
        ping.setPingContent(param.getPingContent());
        ping.setPingStar(param.getPingStar());
        ping.setPingTime(new Date());
        ping.setUserId(param.getUserId());
        fsInquiryOrderPingMapper.insertFsInquiryOrderPing(ping);
        FsInquiryOrder map=new FsInquiryOrder();
        map.setOrderId(order.getOrderId());
        map.setIsPing(1);
        fsInquiryOrderMapper.updateFsInquiryOrder(map);
        return R.ok("评价成功");
    }
    @Transactional
    @Override
    public R refundOrder(FsInquiryOrderRefundParam param) {
        FsInquiryOrder o=fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(param.getOrderId());
        if (o==null){
            throw new CustomException("订单不存在");
        }
        if (o.getStatus()<0){
            throw new CustomException("此状态的订单不可退款");
        }
        if (o.getPackageOrderId()!=null){
            throw new CustomException("请在套餐包页面退款");
        }
        FsInquiryOrder order = new FsInquiryOrder();
        order.setOrderId(param.getOrderId());
        order.setStatus(-2);
        fsInquiryOrderMapper.updateFsInquiryOrder(order);
        if(order.getPayMoney().compareTo(new BigDecimal(0))==1){
            //退款
            List<FsStorePayment> payments = fsStorePaymentMapper.selectFsStorePaymentByPay(1,order.getOrderId());
            if(payments!=null&&payments.size()==1){
                FsStorePayment payment=payments.get(0);

                if(payment.getPayMode().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.setKeyPath(wxPayProperties.getKeyPath());

                    payConfig.setSubAppId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                    payConfig.setSubMchId(org.apache.commons.lang3.StringUtils.trimToNull(null));
                    wxPayService.setConfig(payConfig);
                    WxPayRefundRequest refundRequest = new WxPayRefundRequest();
                    refundRequest.setOutTradeNo("inquiry-"+payment.getPayCode());
                    refundRequest.setOutRefundNo("inquiry-"+payment.getPayCode());
                    refundRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(payment.getPayMoney().toString()));
                    refundRequest.setRefundFee(WxPayUnifiedOrderRequest.yuanToFen(payment.getPayMoney().toString()));
                    try {
                        WxPayRefundResult refundResult = wxPayService.refund(refundRequest);
                        WxPayRefundQueryResult refundQueryResult = wxPayService.refundQuery("", refundResult.getOutTradeNo(), refundResult.getOutRefundNo(), refundResult.getRefundId());
                        if(refundQueryResult!=null&&refundQueryResult.getResultCode().equals("SUCCESS")){
                            FsStorePayment paymentMap=new FsStorePayment();
                            paymentMap.setPaymentId(payment.getPaymentId());
                            paymentMap.setStatus(-1);
                            paymentMap.setRefundTime(DateUtils.getNowDate());
                            paymentMap.setRefundMoney(payment.getPayMoney());
                            fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                            FsInquiryOrder map = new FsInquiryOrder();
                            map.setOrderId(order.getOrderId());
                            map.setStatus(FsInquiryOrderStatusEnum.STATUS_NE2.getValue());
                            fsInquiryOrderMapper.updateFsInquiryOrder(map);
                            if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
                                FsUserCoupon userCoupon=new FsUserCoupon();
                                userCoupon.setStatus(0);
                                userCoupon.setId(order.getUserCouponId());
                                userCouponMapper.updateFsUserCoupon(userCoupon);
                            }
                        }
                        else {
                            throw new CustomException("退款请求失败"+refundQueryResult.getReturnMsg());
                        }
                    } catch (WxPayException e) {
                        throw new CustomException("退款请求失败"+e.getReturnMsg());
                    }
                }
                else if(payment.getPayMode().equals("yb")){
                    //易宝
                    RefundDTO refundDTO=new RefundDTO();
                    refundDTO.setRefundMoney(payment.getPayMoney().toString());
                    refundDTO.setLowRefundNo("inquiry-"+payment.getPayCode());
                    refundDTO.setUpOrderId(payment.getTradeNo());
                    RefundResult result=payService.refund(refundDTO);
                    if(result.getState().equals("5")){
                        FsStorePayment paymentMap=new FsStorePayment();
                        paymentMap.setPaymentId(payment.getPaymentId());
                        paymentMap.setStatus(-1);
                        paymentMap.setRefundTime(DateUtils.getNowDate());
                        paymentMap.setRefundMoney(payment.getPayMoney());
                        fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                        FsInquiryOrder map = new FsInquiryOrder();
                        map.setOrderId(order.getOrderId());
                        map.setStatus(FsInquiryOrderStatusEnum.STATUS_NE2.getValue());
                        fsInquiryOrderMapper.updateFsInquiryOrder(map);
                        if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
                            FsUserCoupon userCoupon=new FsUserCoupon();
                            userCoupon.setStatus(0);
                            userCoupon.setId(order.getUserCouponId());
                            userCouponMapper.updateFsUserCoupon(userCoupon);
                        }
                    }
                }
                else if(payment.getPayMode().equals("tz")){
                    RefundParam tzBankResult = new RefundParam();
                    // 使用set方法为对象的字段赋值
                    //商户原支付订单号
                    tzBankResult.setOldPayOutOrderNo("inquiry"+payment.getPayCode());
                    // 商户退款订单号 对接平台系统里自己生成的退款订单号
                    tzBankResult.setRefundOrderNo("inquiry"+payment.getPayCode());
                    // 交易发送时间 yyyyMMddHHmmss
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                    tzBankResult.setTrxSendTime(sdf.format(new Date()));

                    // 退款金额
                    tzBankResult.setRefundOrdTransAmt(payment.getPayMoney().doubleValue());
                    TzBankResult<com.fs.tzBankPay.doman.RefundResult> result = tzBankService.refund(tzBankResult);
                    if(result.getBody().getRefundOrdStatus().equals("90")){
                        FsStorePayment paymentMap=new FsStorePayment();
                        paymentMap.setPaymentId(payment.getPaymentId());
                        paymentMap.setStatus(-1);
                        paymentMap.setRefundTime(DateUtils.getNowDate());
                        paymentMap.setRefundMoney(payment.getPayMoney());
                        fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                        FsInquiryOrder map = new FsInquiryOrder();
                        map.setOrderId(order.getOrderId());
                        map.setStatus(FsInquiryOrderStatusEnum.STATUS_NE2.getValue());
                        fsInquiryOrderMapper.updateFsInquiryOrder(map);
                        if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
                            FsUserCoupon userCoupon=new FsUserCoupon();
                            userCoupon.setStatus(0);
                            userCoupon.setId(order.getUserCouponId());
                            userCouponMapper.updateFsUserCoupon(userCoupon);
                        }

                    }
                }else if(payment.getPayMode().equals("hf")){

                    V2TradePaymentScanpayRefundRequest request = new V2TradePaymentScanpayRefundRequest();
                    request.setOrdAmt(payment.getPayMoney().toString());
                    request.setOrgReqDate(new SimpleDateFormat("yyyyMMdd").format(payment.getCreateTime()));
                    request.setReqSeqId("refund-"+payment.getPayCode());
                    Map<String, Object> extendInfoMap = new HashMap<>();
                    extendInfoMap.put("org_req_seq_id", "inquiry-"+payment.getPayCode());
                    request.setExtendInfo(extendInfoMap);
                    HuiFuRefundResult refund = huiFuService.refund(request);
                    logger.info("问诊退款返回结果:问诊订单id:"+order.getOrderId()+refund);
                    if(refund.getResp_code().equals("00000000")&&(refund.getTrans_stat().equals("S")||refund.getTrans_stat().equals("P"))){  FsStorePayment paymentMap=new FsStorePayment();
                        paymentMap.setPaymentId(payment.getPaymentId());
                        paymentMap.setStatus(-1);
                        paymentMap.setRefundTime(DateUtils.getNowDate());
                        paymentMap.setRefundMoney(payment.getPayMoney());
                        fsStorePaymentMapper.updateFsStorePayment(paymentMap);
                        FsInquiryOrder map = new FsInquiryOrder();
                        map.setOrderId(order.getOrderId());
                        map.setStatus(FsInquiryOrderStatusEnum.STATUS_NE2.getValue());
                        fsInquiryOrderMapper.updateFsInquiryOrder(map);
                        if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
                            FsUserCoupon userCoupon=new FsUserCoupon();
                            userCoupon.setStatus(0);
                            userCoupon.setId(order.getUserCouponId());
                            userCouponMapper.updateFsUserCoupon(userCoupon);
                        }

                    }
                }

            }
        }
        else {
            FsInquiryOrder map = new FsInquiryOrder();
            map.setOrderId(order.getOrderId());
            map.setStatus(FsInquiryOrderStatusEnum.STATUS_NE1.getValue());
            fsInquiryOrderMapper.updateFsInquiryOrder(map);
            if(order.getUserCouponId()!=null&&order.getUserCouponId()>0){
                FsUserCoupon userCoupon=new FsUserCoupon();
                userCoupon.setStatus(0);
                userCoupon.setId(order.getUserCouponId());
                userCouponMapper.updateFsUserCoupon(userCoupon);
            }
        }
        //写入退款日志
        FsInquiryOrderLogs log = new FsInquiryOrderLogs();
        log.setOrderId(order.getOrderId());
        log.setChangeMessage("平台退款");
        log.setChangeType("平台退款");
        log.setOperator(param.getSysUserName());
        fsInquiryOrderLogsService.insertFsInquiryOrderLogs(log);
        return R.ok();
    }


    @Override
    public Integer getDoctorDoReceiveOrder(String doctorId) {
        return  fsInquiryOrderMapper.getDoctorDoReceiveOrder(doctorId);
    }

    @Override
    public List<FsStoreOrderLogs> selectFsInquiryOrderLogsList(String orderId) {
        return fsInquiryOrderMapper.selectFsInquiryOrderLogsList(orderId);
    }

    @Override
    public R createOrderByPackageOrderStatus4(FsPackageOrder packageOrder) {
        FsPatient patient=JSONUtil.toBean(packageOrder.getPatientJson(),FsPatient.class);
        FsInquiryOrderPatientDTO dto=new FsInquiryOrderPatientDTO();
        BeanUtils.copyProperties(patient,dto);
        FsPackagePatientDTO patJson = JSON.parseObject(packageOrder.getPatientJson(),FsPackagePatientDTO.class);
        long currentTimeMillis = System.currentTimeMillis();
        long ageInMillis = currentTimeMillis - patJson.getBirthday();
        long ageInSeconds = ageInMillis / 1000;
        long ageInYears = ageInSeconds / (365 * 24 * 3600);
        dto.setAge(ageInYears+"");
        // 使用 SimpleDateFormat 格式化日期对象
        dto.setBirthday(new SimpleDateFormat("yyyy-MM-dd").format(patient.getBirthday()));
        FsInquiryOrder order=new FsInquiryOrder();
        order.setOrderSn(packageOrder.getOrderSn());
        order.setOrderType(2);
        order.setPackageOrderId(packageOrder.getOrderId());
        order.setInquiryType(1);
        order.setTitle("服务问诊");
        order.setUserId(packageOrder.getUserId());
        order.setPatientId(patient.getPatientId());
        order.setInquirySubType(0);
        if (packageOrder.getSource()!=null){
            order.setSource(packageOrder.getSource());
        }
        order.setSource(packageOrder.getSource());
        if(packageOrder.getDoctorId()!=null){
            FsDoctor doctor=doctorMapper.selectFsDoctorByDoctorId(packageOrder.getDoctorId());
            order.setMoney(new BigDecimal(0));
            order.setPayMoney(new BigDecimal(0));
            order.setDoctorId(doctor.getDoctorId());
            order.setDepartmentId(doctor.getDeptId());
            order.setIsReceive(1);
            order.setIsAudit(1);
        }
        order.setStatus(4);
        order.setIsPay(1);
        // 创建新的时间对象
        order.setCreateTime(new Date(packageOrder.getCreateTime().getTime()- (10 * 60 * 1000)));
        order.setStartTime(new Date(packageOrder.getCreateTime().getTime()- (10 * 60 * 1000)));
        order.setFinishTime(DateUtils.getNowDate());
        order.setIsPing(0);
        order.setPatientJson(JSONUtil.toJsonStr(dto));
        if(fsInquiryOrderMapper.insertFsInquiryOrder(order)>0){
            packageOrder.setInquiryOrderId(order.getOrderId());
            FsPackageOrder fsPackageOrder = new FsPackageOrder();
            fsPackageOrder.setOrderId(packageOrder.getOrderId());
            fsPackageOrder.setInquiryOrderId(order.getOrderId());
            fsPackageOrderMapper.updateFsPackageOrder(fsPackageOrder);
            return R.ok();
        }
        else{
            return R.error("创建失败");
        }
    }

    @Override
    public String sendStartMsg(Long orderId) {

        FsInquiryOrder order = fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(orderId);
        MsgDTO msgDTO=new MsgDTO();
        MsgCustomDTO customDTO=new MsgCustomDTO();
        customDTO.setType("startInquiry");
        customDTO.setImType(1);
        customDTO.setOrderType(order.getOrderType());
        customDTO.setOrderId(order.getOrderId().toString());
        msgDTO.setCloudCustomData(JSONUtil.toJsonStr(customDTO));
        msgDTO.setFrom_Account("D-"+order.getDoctorId());
        msgDTO.setTo_Account("U-"+order.getUserId());
        List<MsgDataDTO> msgs=new ArrayList<>();
        MsgDataDTO msg=new MsgDataDTO();
        msg.setMsgType("TIMCustomElem");

        InquiryOrderMsgDTO inquiryOrderMsgDTO=new InquiryOrderMsgDTO();
        inquiryOrderMsgDTO.setTitle("为您服务");
        String ext= JSONUtil.toJsonStr(inquiryOrderMsgDTO);
        msg.setMsgContent(new MsgDataFormatDTO("startInquiry",ext,order.getOrderId().toString()));
        msgs.add(msg);
        msgDTO.setMsgBody(msgs);
        imService.sendMsg(msgDTO);
        return "OK";
    }

    @Override
    @Transactional
    public R createOrderByPackageOrder(FsPackageOrder packageOrder) {
        FsPackage fsPackage=JSONUtil.toBean(packageOrder.getPackageJson(),FsPackage.class);
        FsPatient patient=JSONUtil.toBean(packageOrder.getPatientJson(),FsPatient.class);

        FsInquiryOrderPatientDTO dto=new FsInquiryOrderPatientDTO();
        BeanUtils.copyProperties(patient,dto);
        dto.setAge(String.valueOf( DateUtil.ageOfNow(patient.getBirthday())));
        // 使用 SimpleDateFormat 格式化日期对象
        dto.setBirthday(new SimpleDateFormat("yyyy-MM-dd").format(patient.getBirthday()));
        FsInquiryOrder order=new FsInquiryOrder();
        order.setOrderSn(packageOrder.getOrderSn());
        order.setOrderType(2);
        order.setPackageOrderId(packageOrder.getOrderId());

        order.setInquiryType(1);
        order.setTitle("服务问诊");
        order.setUserId(packageOrder.getUserId());
        order.setPatientId(patient.getPatientId());
        order.setInquirySubType(0);
        if(packageOrder.getDoctorId()!=null){
            FsDoctor doctor=doctorMapper.selectFsDoctorByDoctorId(packageOrder.getDoctorId());
            order.setMoney(new BigDecimal(0));
            order.setPayMoney(new BigDecimal(0));
            order.setDoctorId(doctor.getDoctorId());
            order.setDepartmentId(doctor.getDeptId());
            order.setIsReceive(1);
            order.setIsAudit(1);
        }
        order.setStatus(1);
        order.setIsPay(1);
        order.setCreateTime(new Date(packageOrder.getCreateTime().getTime()- (10 * 60 * 1000)));
        order.setIsPing(0);
        if (packageOrder.getSource()!=null){
            order.setSource(packageOrder.getSource());
        }
        order.setPatientJson(JSONUtil.toJsonStr(dto));
        if(fsInquiryOrderMapper.insertFsInquiryOrder(order)>0){
            packageOrder.setInquiryOrderId(order.getOrderId());
            FsPackageOrder fsPackageOrder = new FsPackageOrder();
            fsPackageOrder.setOrderId(packageOrder.getOrderId());
            fsPackageOrder.setInquiryOrderId(order.getOrderId());
            fsPackageOrderMapper.updateFsPackageOrder(fsPackageOrder);
            this.payConfirm(packageOrder.getOrderSn(),"","","",2);
            return R.ok();
        }
        else{
            return R.error("创建失败");
        }
    }


    @Override
    public List<FsInquiryOrderExeclListVO> selectFsInquiryOrderExcelListVO(FsInquiryOrderParam fsInquiryOrder) {
        return fsInquiryOrderMapper.selectFsInquiryOrderExcelListVO(fsInquiryOrder);
    }

    @Override
    public List<FsInquiryFeedbackExportListVO> selectFsInquiryFeedbackExportListVO(FsInquiryOrderParam fsInquiryOrder) {
        return fsInquiryOrderMapper.selectFsInquiryFeedbackExportListVO(fsInquiryOrder);
    }

    @Override
    public R computeOrder(FsInquiryOrderComputeParam param, FsInquiryOrder order, FsUser user) {
        Map<String, BigDecimal> data = new HashMap<>();
        if (param.getUserCouponId() != null && param.getUserCouponId() > 0L) {
            if (order.getCompanyId() != null && order.getCompanyId() > 0) {
                return R.error("此订单不能使用优惠券");
            }
            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.getMoney()) == 1) {
                    return R.error("此优惠券不可用");
                }
                if (coupon.getPrice().compareTo(order.getMoney()) >= 0) {
                    data.put("payMoney", new BigDecimal(0));
                    data.put("discountMoney", coupon.getPrice());
                } else {
                    data.put("payMoney", order.getMoney().subtract(coupon.getPrice()));
                    data.put("discountMoney", coupon.getPrice());
                }
            } else if (coupon.getCouponType().equals(2)) {
                return R.error("此优惠券不可用于问诊订单");
            } else if (coupon.getCouponType().equals(3)) {
                data.put("payMoney", new BigDecimal(0));
                data.put("discountMoney", order.getMoney());
            }
        } else {
            data.put("payMoney", order.getMoney());
            data.put("discountMoney", new BigDecimal(0));
        }
        return R.ok().put("data", data);
    }

    @Override
    public List<FsInquiryOrderListPDVO> selectFsInquiryOrderListPDVO(FsInquiryOrderListPDParam param) {
        return fsInquiryOrderMapper.selectFsInquiryOrderListPDVO(param);
    }

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


        Class<? extends FsInquiryOrderParam> 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 String selectFsInquiryOrderSnByOrderId(long orderId) {
        return fsInquiryOrderMapper.selectFsInquiryOrderSnByOrderId(orderId);
    }
    @Override
    public Long selectFsInquiryOrderExcelListVOCount(FsInquiryOrderParam fsInquiryOrder) {

        return fsInquiryOrderMapper.selectFsInquiryOrderExcelListVOCount(fsInquiryOrder);
    }

    @Override
    public Long selectFsInquiryFeedbackExportListVOCount(FsInquiryOrderParam fsInquiryOrder) {
        return fsInquiryOrderMapper.selectFsInquiryFeedbackExportListVOCount(fsInquiryOrder);
    }
    @Autowired
    FsExportTaskMapper fsExportTaskMapper;
    @Async
    @Override
    public void exportData(FsInquiryOrderParam fsInquiryOrder) {
        List<FsInquiryOrderExeclListVO> list = fsInquiryOrderMapper.selectFsInquiryOrderExcelListVO(fsInquiryOrder);

        ExcelUtil<FsInquiryOrderExeclListVO> util = new ExcelUtil<FsInquiryOrderExeclListVO>(FsInquiryOrderExeclListVO.class);
        AjaxResult result = util.exportExcel(list, "问诊订单数据");


        FsExportTask task = fsExportTaskMapper.selectFsExportTaskByTaskId(fsInquiryOrder.getTaskId());
        task.setFinishTime(new Date());
        task.setStatus(1);
        task.setFileUrl(result.get("msg").toString());
        fsExportTaskMapper.updateFsExportTask(task);
    }

    @Override
    public void exportFeedbackData(FsInquiryOrderParam fsInquiryOrder) {
                List<FsInquiryFeedbackExportListVO> list = fsInquiryOrderMapper.selectFsInquiryFeedbackExportListVO(fsInquiryOrder);
        for (FsInquiryFeedbackExportListVO vo : list){
            vo.setFeedbackContent("复诊");
            if (vo.getPatientTel()!=null){
                vo.setPatientTel(vo.getPatientTel().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }
            vo.setFeedbackTime(vo.getStartTime());
        }

        ExcelUtil<FsInquiryFeedbackExportListVO> util = new ExcelUtil<FsInquiryFeedbackExportListVO>(FsInquiryFeedbackExportListVO.class);
        AjaxResult result =  util.exportExcel(list, "问诊信息反馈单数据");



        FsExportTask task = fsExportTaskMapper.selectFsExportTaskByTaskId(fsInquiryOrder.getTaskId());
        task.setFinishTime(new Date());
        task.setStatus(1);
        task.setFileUrl(result.get("msg").toString());
        fsExportTaskMapper.updateFsExportTask(task);
    }
}
