package com.fs.app.controller;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fs.app.annotation.Login;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.CloudHostUtils;
import com.fs.common.utils.ParseUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.ip.IpUtils;
import com.fs.company.service.ICompanyService;
import com.fs.core.config.WxPayProperties;
import com.fs.core.utils.OrderCodeUtils;
import com.fs.his.domain.*;
import com.fs.his.dto.FsInquiryOrderPatientDTO;
import com.fs.his.dto.PayConfigDTO;
import com.fs.his.enums.FsInquiryOrderStatusEnum;
import com.fs.his.mapper.FsUserWxMapper;
import com.fs.his.param.*;
import com.fs.his.service.*;
import com.fs.his.utils.PhoneUtil;
import com.fs.his.vo.FsInquiryOrderListUVO;
import com.fs.his.vo.FsInquiryOrderPingListUVO;
import com.fs.his.vo.FsInquiryOrderReportUVO;
import com.fs.huifuPay.domain.HuiFuCreateOrder;
import com.fs.huifuPay.domain.HuifuCreateOrderResult;
import com.fs.huifuPay.service.HuiFuService;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.tzBankPay.doman.PayType;
import com.fs.ybPay.domain.CreateWxOrderResult;
import com.fs.ybPay.dto.WxJspayDTO;
import com.fs.ybPay.service.IPayService;
import com.fs.system.service.ISysConfigService;
import com.fs.tzBankPay.TzBankService.TzBankService;
import com.fs.tzBankPay.doman.PayCreateOrder;
import com.fs.tzBankPay.doman.PayCreateOrderResult;
import com.fs.tzBankPay.doman.TzBankResult;
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.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.core.LogEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;


@Api("订单接口")
@RestController
@RequestMapping(value="/app/inquiryOrder")
public class InquiryOrderController extends  AppBaseController {
    @Autowired
    IPayService payService;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private WxPayProperties wxPayProperties;
    @Autowired
    private IFsInquiryOrderService inquiryOrderService;
    @Autowired
    private IFsDoctorService doctorService;
    @Autowired
    private IFsInquiryOrderPingService inquiryOrderPingService;
    @Autowired
    private IFsHospitalService hospitalService;
    @Autowired
    private IFsDepartmentService departmentService;
    @Autowired
    private IFsUserService userService;
    @Autowired
    private IFsUserCouponService userCouponService;
    @Autowired
    private IFsCouponService couponService;
    @Autowired
    private IFsInquiryTempService inquiryTempService;
    @Autowired
    private IFsInquiryOrderReportService orderReportService;
    @Autowired
    private IFsInquiryOrderLogsService fsInquiryOrderLogsService;
    @Autowired
    private IFsStorePaymentService storePaymentService;
    @Autowired
    private TzBankService tzBankService;
    @Autowired
    private HuiFuService huiFuService;
    @Autowired
    SysConfigMapper sysConfigMapper;
    Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private FsUserWxMapper fsUserWxMapper;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IFsUserWxService userWxService;
    @Login
    @ApiOperation("确认订单")
    @PostMapping("/confirm")
    public R confirm(@Validated @RequestBody FsInquiryOrderConfirmParam param, HttpServletRequest request){
        param.setUserId(Long.parseLong(getUserId()));
        return inquiryOrderService.confirmOrder(param);
    }
    @Login
    @ApiOperation("创建订单")
    @PostMapping("/create")
    public R create(@Validated @RequestBody FsInquiryOrderCreateParam param, HttpServletRequest request){
        param.setUserId(Long.parseLong(getUserId()));
        return inquiryOrderService.createOrder(param);
    }
    @Login
    @ApiOperation("计算订单")
    @PostMapping("/compute")
    public R compute(@Validated @RequestBody FsInquiryOrderComputeParam param, HttpServletRequest request){
        FsInquiryOrder order=inquiryOrderService.selectFsInquiryOrderByOrderId(param.getOrderId());
        if(order==null){
            return R.error("订单不存在");
        }
        if(order.getStatus()!= FsInquiryOrderStatusEnum.STATUS_1.getValue()){
            return R.error("订单状态不正确");
        }

        FsUser user=userService.selectFsUserByUserId(order.getUserId());
        if (Objects.isNull(user)) {
            return R.error("用户不存在");
        }

        if (param.getType() == 1) {
//            if (StringUtils.isBlank(user.getMaOpenId()) && !CloudHostUtils.hasCloudHostName("弘德堂")) {
//                return R.error("用户OPENID不存在");
//            }
//            if (!CloudHostUtils.hasCloudHostName("弘德堂")) {
//                return R.error("用户OPENID不存在");
//            }
            if (StringUtils.isBlank(user.getMaOpenId()) && !CloudHostUtils.hasCloudHostName("弘德堂", "金牛明医", "木易华康")) {
                return R.error("用户OPENID不存在");
            }

            return inquiryOrderService.computeOrder(param, order, user);
        } else if (param.getType() == 2) {
            return inquiryOrderService.computeOrder(param, order, user);
        } else {
            return R.error("无效的类型参数");
        }
    }

    @Login
    @ApiOperation("支付")
    @PostMapping("/pay")
    @Transactional
    public R pay(
            HttpServletRequest request,
            @Validated @RequestBody FsInquiryOrderPayParam param
    )
    {
        logger.info("支付"+param.getOrderId()+":"+param.getAppId());
        String json=configService.selectConfigByKey("his.pay");
        PayConfigDTO payConfigDTO= JSONUtil.toBean(json, PayConfigDTO.class);

        FsInquiryOrder order=inquiryOrderService.selectFsInquiryOrderByOrderId(param.getOrderId());
        if(order==null){
            return R.error("订单不存在");
        }
        if(order.getStatus()!= FsInquiryOrderStatusEnum.STATUS_1.getValue()){
            return R.error("订单状态不正确");
        }
        logger.info("当前登录用户userid:{}",getUserId());
        FsUser user=userService.selectFsUserByUserId(Long.parseLong(getUserId()));
        if(user!=null){

//            // 红德堂特殊处理
//            if (!CloudHostUtils.hasCloudHostName("弘德堂")) {
//                return R.error("用户OPENID不存在");
//            }

            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.getMoney())==1){
                        return R.error("此优惠券不可用");
                    }
                    if(coupon.getPrice().compareTo(order.getMoney())>=0){
                        order.setPayMoney(new BigDecimal(0));
                        order.setDiscountMoney(order.getMoney());

                    }
                    else{
                        order.setPayMoney((order.getMoney().subtract(coupon.getPrice())));
                        order.setDiscountMoney(coupon.getPrice());

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

                }
                order.setUserCouponId(userCoupon.getId());
                userCoupon.setUseTime(new Date());
                userCoupon.setBusinessId(order.getOrderId());
                userCoupon.setBusinessType(1);
                userCoupon.setStatus(1);
                userCouponService.updateFsUserCoupon(userCoupon);
            }
            else{
                order.setPayMoney(order.getMoney());
                order.setDiscountMoney(new BigDecimal(0));
            }
            inquiryOrderService.updateFsInquiryOrder(order);
            return R.ok();


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

    }


    @Login
    @ApiOperation("支付")
    @PostMapping("/payment")
    public R payment(HttpServletRequest request, @Validated @RequestBody FsInquiryOrderDoPayParam param)
    {
        Long userId = Long.parseLong(getUserId());
        param.setUserId(userId);
        FsUser user = userService.selectFsUserByUserId(userId);
        //在线支付
        String json = configService.selectConfigByKey("his.pay");
        PayConfigDTO payConfigDTO = JSONUtil.toBean(json, PayConfigDTO.class);
//        String openId = "";
//        if (StringUtils.isNotEmpty(param.getAppId())) {
//            FsUserWx fsUserWx = userWxService.selectByAppIdAndUserId(param.getAppId(), param.getUserId(), 1);
//            if (fsUserWx != null) {
//                openId = fsUserWx.getOpenId();
//            }
//        } else {
//            openId = Objects.isNull(user) ? "" : user.getMaOpenId();
//            if (StringUtils.isBlank(openId)){
//                Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
//                        .eq(FsUserWx::getFsUserId, param.getUserId())
//                        .eq(FsUserWx::getAppId, payConfigDTO.getAppId());
//                FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
//                if (Objects.nonNull(fsUserWx)){
//                    openId = fsUserWx.getOpenId();
//                }
//            }
//        }

        String openId = null;
        String appId = param.getAppId();
        if (StringUtils.isNotBlank(appId)) {
            //查询fs_user_wx的openId
            Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
                    .eq(FsUserWx::getFsUserId, param.getUserId())
                    .eq(FsUserWx::getAppId, appId);
            FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
            if (fsUserWx != null) {
                openId = fsUserWx.getOpenId();
            }
        } else {
            appId = payConfigDTO.getAppId();
            openId = Objects.isNull(user) ? "" : user.getMaOpenId();
            if (StringUtils.isBlank(openId)){
                Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
                        .eq(FsUserWx::getFsUserId, param.getUserId())
                        .eq(FsUserWx::getAppId, appId);
                FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
                if (Objects.nonNull(fsUserWx)){
                    openId = fsUserWx.getOpenId();
                }
            }
        }
        //String json=configService.selectConfigByKey("his.pay");
        //PayConfigDTO payConfigDTO= JSONUtil.toBean(json, PayConfigDTO.class);

        FsInquiryOrder order=inquiryOrderService.selectFsInquiryOrderByOrderId(param.getOrderId());

        //FsUser user=userService.selectFsUserByUserId(Long.parseLong(getUserId()));

//        String openId = Objects.isNull(user) ? "" : user.getMaOpenId();
//        if (StringUtils.isBlank(openId)){
//            Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
//                    .eq(FsUserWx::getFsUserId, Long.parseLong(getUserId()))
//                    .eq(FsUserWx::getAppId, payConfigDTO.getAppId());
//            FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
//            if (Objects.nonNull(fsUserWx)){
//                openId = fsUserWx.getOpenId();
//            }
//        }

        if (StringUtils.isBlank(openId)){
            return R.error("用户OPENID不存在");
        }

        if(order.getPayMoney().compareTo(new BigDecimal(0))==0){
            inquiryOrderService.payConfirm(order.getOrderSn(),"","","",2,null,null);
            return R.ok().put("isPay",1);
        }
        else{
            String payCode =  OrderCodeUtils.getOrderSn();
            if(StringUtils.isEmpty(payCode)){
                return R.error("订单生成失败，请重试");
            }
            FsStorePayment storePayment=new FsStorePayment();
            storePayment.setStatus(0);
            storePayment.setPayMode(payConfigDTO.getType());
            storePayment.setPayCode(payCode);
            storePayment.setCompanyId(order.getCompanyId());
            storePayment.setCompanyUserId(order.getCompanyUserId());
            storePayment.setBusinessCode(order.getOrderSn());
            storePayment.setPayMoney(order.getPayMoney());
            storePayment.setCreateTime(new Date());
            storePayment.setPayTypeCode("weixin");
            storePayment.setBusinessType(1);
            storePayment.setRemark("问诊订单支付");
            storePayment.setOpenId(openId);
            storePayment.setUserId(user.getUserId());
            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(appId);
                    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(openId);//公众号支付提供用户openid
                    orderRequest.setBody("问诊订单支付");
                    orderRequest.setOutTradeNo("inquiry-"+storePayment.getPayCode());
                    orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(storePayment.getPayMoney().toString()));//测试
                    //orderRequest.setTotalFee(WxPayUnifiedOrderRequest.yuanToFen(money));//测试
                    orderRequest.setTradeType("JSAPI");
                    orderRequest.setSpbillCreateIp(IpUtils.getIpAddr(request));
                    //调用统一下单接口，获取"预支付交易会话标识"
                    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("inquiry-"+storePayment.getPayCode());
                    p.setBody("问诊订单支付");
                    p.setIsMinipg("1");
                    p.setOpenId(openId);
                    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());
                        storePaymentService.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("inquiry"+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(openId);
                    o.setOrderType(1);
                    o.setOrderId(order.getOrderId().toString());
                    TzBankResult<PayCreateOrderResult> result = tzBankService.createOrder(o);
                    FsStorePayment mt=new FsStorePayment();
                    mt.setPaymentId(storePayment.getPaymentId());
                    mt.setTradeNo(result.getBody().getOrderFlowNo());
                    storePaymentService.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(openId);
                    o.setAppId(appId);
                    o.setReqSeqId("inquiry-"+storePayment.getPayCode());
                    o.setTransAmt(storePayment.getPayMoney().toString());
                    o.setAppId(param.getAppId());
                    o.setGoodsDesc("问诊订单支付");
                    HuifuCreateOrderResult result = huiFuService.createOrder(o);
                    FsStorePayment mt=new FsStorePayment();
                    mt.setPaymentId(storePayment.getPaymentId());
                    mt.setTradeNo(result.getHf_seq_id());
                    mt.setAppId(appId);
                    storePaymentService.updateFsStorePayment(mt);
                    return R.ok().put("isPay",0).put("data",result).put("type","hf");
                }
            }
            else{
                throw new CustomException("支付失败");
            }

        }
        return R.error();
    }

    @Login
    @ApiOperation("支付宝支付")
    @PostMapping("/zfbPayment")
    public R zfbPayment(HttpServletRequest request, @Validated @RequestBody FsInquiryOrderDoPayParam param)
    {
        param.setUserId(Long.parseLong(getUserId()));
        FsInquiryOrder order=inquiryOrderService.selectFsInquiryOrderByOrderId(param.getOrderId());
        FsUser user=userService.selectFsUserByUserId(Long.parseLong(getUserId()));

        String json = configService.selectConfigByKey("his.pay");
        PayConfigDTO payConfigDTO = JSONUtil.toBean(json, PayConfigDTO.class);

        String openId = null;
        String appId = param.getAppId();
        if (StringUtils.isNotBlank(appId)) {
            //查询fs_user_wx的openId
            Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
                    .eq(FsUserWx::getFsUserId, param.getUserId())
                    .eq(FsUserWx::getAppId, appId);
            FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
            if (fsUserWx != null) {
                openId = fsUserWx.getOpenId();
            }
        } else {
            appId = payConfigDTO.getAppId();
            openId = Objects.isNull(user) ? "" : user.getMaOpenId();
            if (StringUtils.isBlank(openId)){
                Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
                        .eq(FsUserWx::getFsUserId, param.getUserId())
                        .eq(FsUserWx::getAppId, appId);
                FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
                if (Objects.nonNull(fsUserWx)){
                    openId = fsUserWx.getOpenId();
                }
            }
        }

        if(order.getPayMoney().compareTo(new BigDecimal(0))==0){
            inquiryOrderService.payConfirm(order.getOrderSn(),"","","",2,null,null);
            return R.ok().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.setPayMode(payConfigDTO.getType());
            storePayment.setPayCode(payCode);
            storePayment.setCompanyId(order.getCompanyId());
            storePayment.setCompanyUserId(order.getCompanyUserId());
            storePayment.setBusinessCode(order.getOrderSn());
            storePayment.setPayMoney(order.getPayMoney());
            storePayment.setCreateTime(new Date());
            storePayment.setPayTypeCode("支付宝");
            storePayment.setBusinessType(1);
            storePayment.setRemark("问诊订单支付");
            storePayment.setOpenId(openId);
            storePayment.setUserId(user.getUserId());
            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("inquiry" + 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.ALIPAY_BARCODE_PAYMENT.getCode()));
                    TzBankResult<PayCreateOrderResult> result = tzBankService.createOrder(o);
                    FsStorePayment mt=new FsStorePayment();
                    mt.setPaymentId(storePayment.getPaymentId());
                    mt.setTradeNo(result.getBody().getOrderFlowNo());
                    storePaymentService.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(openId);
                    o.setReqSeqId("inquiry-"+storePayment.getPayCode());
                    o.setTransAmt(storePayment.getPayMoney().toString());
                    o.setGoodsDesc("问诊订单支付");
                    o.setAppId(appId);
                    if (o.getAppId()!=null&& !o.getAppId().isEmpty()){
                        Wrapper<FsUserWx> queryWrapper = Wrappers.<FsUserWx>lambdaQuery()
                                .eq(FsUserWx::getFsUserId, Long.parseLong(getUserId()))
                                .eq(FsUserWx::getAppId, payConfigDTO.getAppId());
                        FsUserWx fsUserWx = fsUserWxMapper.selectOne(queryWrapper);
                        if (fsUserWx!=null){
                            o.setOpenid(fsUserWx.getOpenId());
                        }
                    }
                    HuifuCreateOrderResult result = huiFuService.createOrder(o);
                    FsStorePayment mt=new FsStorePayment();
                    mt.setPaymentId(storePayment.getPaymentId());
                    mt.setTradeNo(result.getHf_seq_id());
                    mt.setAppId(appId);
                    storePaymentService.updateFsStorePayment(mt);
                    return R.ok().put("isPay",0).put("data",result).put("type","hf");
                }

            }
            else{
                throw new CustomException("支付失败");
            }

        }
        return R.error();

    }
    @Login
    @RepeatSubmit
    @ApiOperation("取消订单")
    @PostMapping("/cancel")
    @Transactional
    public R cancelOrder(@Validated @RequestBody FsInquiryOrderCancelParam param, HttpServletRequest request){
        param.setType(1);
        logger.info("取消问诊订单:"+param.getOrderId()+":操作人:用户");
        return inquiryOrderService.cancelOrder(param);
    }



    @Login
    @GetMapping("/getMyInquiryOrderList")
    public R getMyInquiryOrderList(FsInquiryOrderListUParam param)
    {

        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setUserId(Long.parseLong(getUserId()));
        List<FsInquiryOrderListUVO> list=inquiryOrderService.selectFsInquiryOrderListUVO(param);
        PageInfo<FsInquiryOrderListUVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }
    @Login
    @GetMapping("/getInquiryOrderById")
    public R getInquiryOrderById(@RequestParam("orderId")Long orderId)
    {
        FsInquiryOrder order=inquiryOrderService.selectFsInquiryOrderByOrderId(orderId);
//        if(!order.getUserId().equals(Long.parseLong(getUserId()))){
//            return R.error("非法操作");
//        }
        if(order!=null&&StringUtils.isNotEmpty(order.getPatientJson())){
            FsInquiryOrderPatientDTO dto=JSONUtil.toBean(order.getPatientJson(),FsInquiryOrderPatientDTO.class);
            dto.setMobile(ParseUtils.parsePhone(dto.getMobile()));
            dto.setIdCard(ParseUtils.parseIdCard(dto.getIdCard()));
            order.setPatientJson(JSONUtil.toJsonStr(dto));

        }
        return R.ok().put("data",order);
    }

    @Login
    @GetMapping("/getMyInquiryOrderById")
    public R getMyInquiryOrderById(@RequestParam("orderId")Long orderId)
    {
        Map<String,Object> maps=new HashMap<>();
        FsInquiryOrder order=inquiryOrderService.selectFsInquiryOrderByOrderId(orderId);
//        if(!order.getUserId().equals(Long.parseLong(getUserId()))){
//            return R.error("非法操作");
//        }
        if(order!=null&&StringUtils.isNotEmpty(order.getPatientJson())){
            FsInquiryOrderPatientDTO dto=JSONUtil.toBean(order.getPatientJson(),FsInquiryOrderPatientDTO.class);
            dto.setMobile(ParseUtils.parsePhone(dto.getMobile()));
            dto.setIdCard(ParseUtils.parseIdCard(dto.getIdCard()));
            order.setPatientJson(JSONUtil.toJsonStr(dto));

        }
        maps.put("order",order);
        if(order.getDoctorId()!=null){
            FsDoctor doctor=doctorService.selectFsDoctorByDoctorId(order.getDoctorId());
            if(doctor!=null){
                FsHospital hospital=hospitalService.selectFsHospitalByHospitalId(doctor.getHospitalId());
                FsDepartment department=departmentService.selectFsDepartmentByDeptId(doctor.getDeptId());
                maps.put("hospital",hospital);
                maps.put("department",department);
            }
            maps.put("doctor",doctor);
        }
        FsInquiryOrderReport report=orderReportService.selectFsInquiryOrderReportByOrderId(orderId);
        if(report!=null&&report.getStatus().equals(2)){
            if(StringUtils.isNotEmpty(report.getPatientJson())){
                FsInquiryOrderPatientDTO dto=JSONUtil.toBean(order.getPatientJson(),FsInquiryOrderPatientDTO.class);
                dto.setMobile(ParseUtils.parsePhone(dto.getMobile()));
                dto.setIdCard(ParseUtils.parseIdCard(dto.getIdCard()));
                report.setPatientJson(JSONUtil.toJsonStr(dto));

            }
            maps.put("report",report);
        }

        return R.ok().put("data",maps);
    }




    @Login
    @GetMapping("/getMyInquiryOrderPingList")
    public R getMyInquiryOrderPingList(FsInquiryOrderPingListUParam param)
    {

        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setUserId(Long.parseLong(getUserId()));
        List<FsInquiryOrderPingListUVO> list=inquiryOrderPingService.selectFsInquiryOrderPingListUVO(param);
        PageInfo<FsInquiryOrderPingListUVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }


    @Login
    @ApiOperation("评价订单")
    @PostMapping("/pingOrder")
    public R pingOrder(@Validated @RequestBody FsInquiryOrderPingParam param, HttpServletRequest request){
        param.setUserId(Long.parseLong(getUserId()));
        return inquiryOrderService.pingOrder(param);
    }


    @GetMapping("/getInquiryTemp")
    public R getInquiryTemp( )
    {
        FsInquiryTemp map=new FsInquiryTemp();
        List<FsInquiryTemp> list=inquiryTempService.selectFsInquiryTempList(map);
        return R.ok().put("data",list);
    }

    @Login
    @ApiOperation("获取诊断报告")
    @GetMapping("/getInquiryOrderReport")
    public R getInquiryOrderReport(@RequestParam("orderId")Long orderId)
    {
        FsInquiryOrderReportUVO report=orderReportService.selectFsInquiryOrderReportUVOByOrderId(orderId);
//        if(!report.getUserId().equals(Long.parseLong(getUserId()))){
//            return R.error("非法操作");
//        }
        if(report!=null&&StringUtils.isNotEmpty(report.getPatientJson())){
            FsInquiryOrderPatientDTO dto=JSONUtil.toBean(report.getPatientJson(),FsInquiryOrderPatientDTO.class);
            dto.setMobile(ParseUtils.parsePhone(dto.getMobile()));
            dto.setIdCard(ParseUtils.parseIdCard(dto.getIdCard()));
            report.setPatientJson(JSONUtil.toJsonStr(dto));
        }

        return R.ok().put("data",report);
    }


    @Login
    @ApiOperation("获取销售订单列表")
    @GetMapping("/getCompanyUserInquiryOrderList")
    public R getCompanyUserInquiryOrderList(FsInquiryOrderListUParam param)
    {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setCompanyUserId(getCompanyUserId());
        List<FsInquiryOrderListUVO> list=inquiryOrderService.selectFsInquiryOrderListUVO(param);
        PageInfo<FsInquiryOrderListUVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }
    @Login
    @GetMapping("/getCompanyUserInquiryOrderById")
    public R getCompanyUserInquiryOrderById(@RequestParam("orderId")Long orderId)
    {
        FsInquiryOrder order=inquiryOrderService.selectFsInquiryOrderByOrderId(orderId);
//        if(!order.getCompanyUserId().equals(getCompanyUserId())){
//            return R.error("非法操作");
//        }
        if(order!=null&&StringUtils.isNotEmpty(order.getPatientJson())){
            FsInquiryOrderPatientDTO dto=JSONUtil.toBean(order.getPatientJson(),FsInquiryOrderPatientDTO.class);
            dto.setMobile(ParseUtils.parsePhone(dto.getMobile()));
            dto.setIdCard(ParseUtils.parseIdCard(dto.getIdCard()));
            order.setPatientJson(JSONUtil.toJsonStr(dto));
        }
        Map<String,Object> maps=new HashMap<>();
        maps.put("order",order);
        if(order.getDoctorId()!=null){
            FsDoctor doctor=doctorService.selectFsDoctorByDoctorId(order.getDoctorId());
            if(doctor!=null){
                FsHospital hospital=hospitalService.selectFsHospitalByHospitalId(doctor.getHospitalId());
                FsDepartment department=departmentService.selectFsDepartmentByDeptId(doctor.getDeptId());
                maps.put("hospital",hospital);
                maps.put("department",department);
            }
            maps.put("doctor",doctor);
        }
        FsInquiryOrderReport report=orderReportService.selectFsInquiryOrderReportByOrderId(orderId);
        if(report!=null&&report.getStatus().equals(2)){
            if(StringUtils.isNotEmpty(report.getPatientJson())){
                FsInquiryOrderPatientDTO dto=JSONUtil.toBean(order.getPatientJson(),FsInquiryOrderPatientDTO.class);
                dto.setMobile(ParseUtils.parsePhone(dto.getMobile()));
                dto.setIdCard(ParseUtils.parseIdCard(dto.getIdCard()));
                report.setPatientJson(JSONUtil.toJsonStr(dto));

            }
            maps.put("report",report);
        }
        return R.ok().put("data",maps);
    }

}
