package com.ywt.outpatient.rpc.provider;

import com.ywt.biz.common.constant.YwtCommonRespCode;
import com.ywt.biz.common.enums.PaymentStatusEnum;
import com.ywt.biz.common.enums.RefundStatusEnum;
import com.ywt.biz.common.enums.TerminalEnum;
import com.ywt.biz.common.exception.YwtCommonException;
import com.ywt.biz.common.util.Checker;
import com.ywt.biz.common.util.DateUtil;
import com.ywt.biz.common.util.StringHelper;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.ordercenter.OrderCenterService;
import com.ywt.gapi.third.cloudfilm.*;
import com.ywt.outpatient.core.BaseResponse;
import com.ywt.outpatient.domain.entity.center.*;
import com.ywt.outpatient.domain.models.config.CloudFilmConfig;
import com.ywt.outpatient.domain.models.enums.CheckResultOrderEnum;
import com.ywt.outpatient.domain.models.enums.CloudFilmOrderStatusEnum;
import com.ywt.outpatient.service.rpc.ConfigServiceProvider;
import com.ywt.outpatient.service.rpc.IdGenerator;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;

import java.sql.Types;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @author daiyihua
 * @create 2020-09-15 11:19
 * @program rpc
 * @description 影像报告相关接口
 **/
@DubboService
public class CloudfilmProvider extends DubboCloudfilmServiceTriple.CloudfilmServiceImplBase {

    private final Logger logger = LoggerFactory.getLogger(CloudfilmProvider.class);
    @Autowired
    private CheckResultOrderRepository checkResultOrderRepository;
    @Autowired
    private MedicalCardRepository medicalCardRepository;
    @DubboReference
    private OrderCenterService orderCenterServiceBlockingStub;
    @Autowired
    private ConfigServiceProvider configServiceProvider;
    @Autowired
    private InspectionReportRepository inspectionReportRepository;
    @DubboReference
    private DubboCloudfilm2DServiceTriple.Cloudfilm2DServiceStub cloudfilm2DServiceBlockingStub;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private IdGenerator idGenerator;
    // 云胶片订单业务编号前缀
    public static final String CLOUD_FILM_ORDER_NO_PREFIX = "CF";

    /**
     * 获取3D重构待处理订单列表
     */
    @Override
    public GetOrderListResponse getOrderList(GetOrderListRequest request) {
        List<GetOrderListResponse.orderInfo> list = new ArrayList<>();
        List<CheckResultOrder> orderList = checkResultOrderRepository.getPaymentAndNoUrlList(request.getHospitalId());
        if (!Checker.isNone(orderList)) {
            orderList.forEach(p -> {
                list.add(GetOrderListResponse.orderInfo.newBuilder()
                        .setAccessionNumber(Checker.getStringValue(p.getAccessionNumber()))
                        .setPatientId(Checker.getStringValue(p.getPatientId()))
                        .setPatientName(Checker.getStringValue(p.getPatientName()))
                        .setNote(Checker.getStringValue(p.getNote()))
                        .build());
            });
        }
        return GetOrderListResponse.newBuilder()
                .setCode(ResultCode.SUCCEED_VALUE)
                .setInfo(CloudFilmConfig.Constants.RESPONSE_INFO_SUCCEED)
                .addAllList(list)
                .build();
    }


    /**
     * 接收3D已完成结果
     */
    @Override
    public SetCompleteResultResponse setCompleteResult(SetCompleteResultRequest request) {
        SetCompleteResultResponse.Builder builder = SetCompleteResultResponse.newBuilder();

        int hospitalId = request.getHospitalId();
        String accessionNumber = request.getAccessionNumber();
        String pacsViewUrl = request.getPacsViewUrl();
        // 状态 status:（1-待支付，2-已支付，3-已回写，4-已退费）
        String sql = "update check_result_order set hospital_id = ?, pacs_view_url = ?, status = 3 where accession_number = ? and deleted = 0;";
        Object[] args = new Object[]{hospitalId, pacsViewUrl, accessionNumber};
        int[] types = new int[]{Types.INTEGER, Types.VARCHAR, Types.VARCHAR};
        jdbcTemplate.update(sql, args, types);
        builder.setCode(ResultCode.SUCCEED_VALUE).setInfo(CloudFilmConfig.Constants.RESPONSE_INFO_SUCCEED);
        return builder.build();
    }

    @Override
    public CreateOrderResponse createOrder(CreateOrderRequest request) {
        String checkResultId = request.getCheckResultId();
        int medicalCardId = request.getMedicalCardId();
        CreateOrderResponse.Builder builder = CreateOrderResponse.newBuilder();
        try {
            if (StringHelper.isNullOrEmpty(checkResultId))
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "检查结果 ID 不能为空");
            if (medicalCardId <= 0) throw new YwtCommonException(YwtCommonRespCode.P_ERR, "诊疗卡 id 有误");
            MedicalCard medicalCard = medicalCardRepository.findById(medicalCardId).orElse(null);
            if (medicalCard == null) throw new YwtCommonException(YwtCommonRespCode.P_ERR, "该诊疗卡不存在");
            int hospitalId = Checker.getIntegerValue(medicalCard.getHospitalId());
            InspectionReport report = inspectionReportRepository.getByReportIdAndHospitalId(checkResultId, hospitalId);
            if (report == null) throw new YwtCommonException(YwtCommonRespCode.P_ERR, "该检查报告不存在");
            CloudFilmConfig config = configServiceProvider.getCloudFilmConfig(hospitalId);
            if (config == null) throw new YwtCommonException(YwtCommonRespCode.P_ERR, "配置有误，请联系管理员");
            List<String> threeDWhiteList = config.getThreeDWhiteList();
            if (Checker.isNone(threeDWhiteList))
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "3D 白名单配置有误，请联系管理员");
            int amount = Checker.getIntegerValue(config.getCheckResultFee());
            if (amount < 0) throw new YwtCommonException(YwtCommonRespCode.P_ERR, "价格配置有误，请联系管理员");
            // 小程序的支付代码
            String payCode = Checker.getStringValue(config.getPayCode());
            // 微信公众号的支付代码
            String payCode4Wx = Checker.getStringValue(config.getPayCode4Wx());
            String payBody = Checker.getStringValue(config.getPayBody());
            if (StringHelper.isNullOrEmpty(payBody))
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "支付配置有误，请联系管理员");
            String reportType = request.getReportType();
            if (StringHelper.isNullOrEmpty(reportType))
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "检查类型不能为空");
            if (!threeDWhiteList.contains(reportType))
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, String.format("检查类型: %s 不支持创建 3D 订单", reportType));
            String reportNum = request.getReportNum();
            if (StringHelper.isNullOrEmpty(reportNum))
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "检查单号不能为空");
            String pc = "";
            int terminal = request.getTerminal();
            switch (TerminalEnum.valueOf(terminal)) {
                case PatientWxOfficial:
                case TaiheWxOfficial:
                    pc = payCode4Wx;
                    break;
                case TAI_HE_INTERNET_HOSPITAL_PATIENT_MINI_PROGRAM:
                    pc = payCode;
                    break;
                default:
                    break;
            }
            if (StringHelper.isNullOrEmpty(pc))
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, String.format("支付代码配置有误(%d)，请联系管理员", terminal));
            int userId = medicalCard.getUserId();
            // 生成订单
            CheckResultOrder order = new CheckResultOrder();
            // 从诊疗卡读取
            order.setCheckResultId(checkResultId);
            order.setPatientId(Checker.getStringValue(medicalCard.getHisPatientId()));
            order.setPatientNo(Checker.getStringValue(medicalCard.getCardNo()));
            order.setMobile(Checker.getStringValue(medicalCard.getMobile()));
            order.setHospitalId(Checker.getIntegerValue(medicalCard.getHospitalId()));
            order.setStatus(CloudFilmOrderStatusEnum.UNPAID.getValue());
            order.setTotalPrice(amount);
            order.setCreateTime(new Date());
            order.setUserId(userId);
            // 保存患者姓名
            order.setPatientName(Checker.getStringValue(medicalCard.getPatientName()));
            // 检查有可能没入库，统一由前端回传
            order.setAccessionNumber(reportNum);
            order.setReportType(reportType);
            // 业务编码
            String bizNo = idGenerator.generateOrderNo(CLOUD_FILM_ORDER_NO_PREFIX);
            order.setBizNo(bizNo);
            order.setDeleted(false);
            CheckResultOrder ord = checkResultOrderRepository.save(order);
            if (amount > 0) {
                com.ywt.gapi.ordercenter.CreateOrderRequest coRequest = com.ywt.gapi.ordercenter.CreateOrderRequest.newBuilder()
                        .setAmount(amount)
                        .setUserId(userId)
                        .setOrderType(0)
                        .setBizId(ord.getId())
                        .setDoctorId(0)
                        .setPayCode(pc)
                        .setPayBody(payBody)
                        .setPaymentCallbackMethod("/com.ywt.gapi.third.cloudfilm.CloudfilmService/payCallback")
                        .build();
                com.ywt.gapi.ordercenter.CreateOrderResponse response = orderCenterServiceBlockingStub.createOrder(coRequest);
                if (response.getCode() == BaseResponse.SUCCEED) {
                    int orderId = response.getOrderId();
                    String orderNo = response.getOrderNo();
                    ord.setOrderId(orderId);
                    ord.setOrderNo(orderNo);
                    checkResultOrderRepository.save(ord);
                    builder.setCode(ResultCode.SUCCEED_VALUE);
                    builder.setOrderId(orderId);
                    builder.setOrderNo(orderNo);
                } else {
                    // 下单失败
                    builder.setCode(ResultCode.APP_ERROR_VALUE);
                    builder.setMsg(response.getInfo());
                }
            } else {
                // 价格设置为 0 元，直接支付成功
                ord.setStatus(CloudFilmOrderStatusEnum.PAID.getValue());
                ord.setPayTime(new Date());
                ord.setPaymentStatus(PaymentStatusEnum.Success.getValue());
                // 0 元订单也要写入 orderId, orderNo, 此时的 orderId 为 check_result_order 表主键
                ord.setOrderId(ord.getId());
                // 暂用 bizNo 作为 orderNo
                ord.setOrderNo(bizNo);
                checkResultOrderRepository.save(ord);
                builder.setCode(ResultCode.SUCCEED_VALUE);
                builder.setIsPaid(true);
            }
            return builder.build();
        } catch (YwtCommonException e) {
            builder.setCode(ResultCode.APP_ERROR_VALUE);
            builder.setMsg(e.getMessage());
        } catch (Exception e) {
            logger.error("CloudfilmServiceImpl#createOrder(request={} ):\n {}", request, e.getMessage(), e);
            builder.setCode(ResultCode.APP_ERROR_VALUE).setMsg(e.getMessage());
        }
        return builder.build();
    }

    @Override
    public PayCallbackResponse payCallback(PayCallbackRequest request) {
        PayCallbackResponse.Builder builder = PayCallbackResponse.newBuilder();
        int bizId = request.getBizId();
        try {
            CheckResultOrder order = checkResultOrderRepository.findById(bizId).orElse(null);
            if (order == null) {
                builder.setCode(ResultCode.APP_ERROR_VALUE);
                builder.setInfo("找不到该订单的信息");
            } else {
                order.setStatus(CloudFilmOrderStatusEnum.PAID.getValue());
                order.setPayTime(new Date());
                order.setPaymentStatus(PaymentStatusEnum.Success.getValue());
                order.setPaymentNo(request.getPaymentNo());
                order.setPaymentChannel(request.getPaymentChannel());
                checkResultOrderRepository.save(order);
                builder.setCode(ResultCode.SUCCEED_VALUE);
            }
            return builder.build();
        } catch (Exception e) {
            logger.error("CloudfilmServiceImpl#payCallback(request={} ):\n {}", request, e.getMessage(), e);
            return builder.setCode(BaseResponse.APP_ERROR).setInfo(e.getMessage()).build();
        }
    }

    @Override
    public GetConfigResponse getConfig(GetConfigRequest request) {
        GetConfigResponse.Builder builder = GetConfigResponse.newBuilder();
        try {
            CloudFilmConfig config = configServiceProvider.getCloudFilmConfig(request.getHospitalId());
            if (config == null) {
                builder.setCode(ResultCode.APP_ERROR_VALUE);
                builder.setInfo("配置有误，请联系管理员");
            } else {
                builder.setCode(ResultCode.SUCCEED_VALUE);
                builder.setCheckResultFee(Checker.getIntegerValue(config.getCheckResultFee()));
                builder.setEstWaitTime(Checker.getIntegerValue(config.getEstWaitTimeInMin()));
            }
            return builder.build();
        } catch (Exception e) {
            logger.error("CloudfilmServiceImpl#getConfig(request={} ):\n {}", request, e.getMessage(), e);
            return builder.setCode(BaseResponse.APP_ERROR).setInfo(e.getMessage()).build();
        }
    }

    @Override
    public GetReportInfoResponse getReportInfo(GetReportInfoRequest request) {
        String reportId = request.getReportId();
        int medicalCardId = request.getMedicalCardId();
        String reportNum = request.getReportNum();
        String reportDate = request.getReportDate();
        String reportType = request.getReportType();
        GetReportInfoResponse.Builder builder = GetReportInfoResponse.newBuilder();
        try {
            if (StringHelper.isNullOrEmpty(reportId))
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "检查结果 ID 不能为空");
            if (StringHelper.isNullOrEmpty(reportType))
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "检查类型不能为空");
            if (medicalCardId <= 0) throw new YwtCommonException(YwtCommonRespCode.P_ERR, "诊疗卡 id 有误");
            MedicalCard medicalCard = medicalCardRepository.findById(medicalCardId).orElse(null);
            if (medicalCard == null) throw new YwtCommonException(YwtCommonRespCode.P_ERR, "该诊疗卡不存在");
            int hospitalId = Checker.getIntegerValue(medicalCard.getHospitalId());
            CloudFilmConfig config = configServiceProvider.getCloudFilmConfig(hospitalId);
            if (config == null) throw new YwtCommonException(YwtCommonRespCode.P_ERR, "配置有误，请联系管理员");
            List<String> twoDWhiteList = config.getTwoDWhiteList();
            if (Checker.isNone(twoDWhiteList))
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "2D 白名单配置有误，请联系管理员");
            List<String> threeDWhiteList = config.getThreeDWhiteList();
            if (Checker.isNone(threeDWhiteList))
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "3D 白名单配置有误，请联系管理员");
            if (StringHelper.isNullOrEmpty(reportNum))
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "检查单号不能为空");
            if (StringHelper.isNullOrEmpty(reportDate))
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "检查报告审核日期不能为空");
            Date rptDate = DateUtil.parseDate(reportDate, "yyyy-MM-dd");
            if (rptDate == null) throw new YwtCommonException(YwtCommonRespCode.P_ERR, "检查报告审核日期格式不正确");
            int orderId = 0;
            String url2D = "";
            String url3D = "";
            boolean visible2D = false;
            boolean visible3D = false;
            String patientName = medicalCard.getPatientName();
            if (threeDWhiteList.contains(reportType)) {
                visible3D = true;
                // 查看是否已支付，已支付返回 orderId
                CheckResultOrder checkResultOrder = checkResultOrderRepository.findOnePaidOrderByReportIdAndHospitalId(reportId, hospitalId);
                if (checkResultOrder != null) {
                    orderId = Checker.getIntegerValue(checkResultOrder.getOrderId());
                    if (checkResultOrder.getStatus() == CloudFilmOrderStatusEnum.WRITE_BACK.getValue()) {
                        // 已回写的才获取 3D url
                        url3D = Checker.getStringValue(checkResultOrder.getPacsViewUrl());
                    }
                }
            }
            if (twoDWhiteList.contains(reportType)) {
                visible2D = true;
                // 根据配置的时间判断是否获取 2D url
                long monthPassed = ChronoUnit.MONTHS.between(DateUtil.convertToLocalDate(rptDate), LocalDate.now());
                if (monthPassed <= Checker.getIntegerValue(config.getTwoDExpTimeInMonth())) {
                    Get2DCloudfilmUrlRequest get2DCloudfilmUrlRequest = Get2DCloudfilmUrlRequest.newBuilder()
                            .setPatientId(Checker.getStringValue(medicalCard.getHisPatientId()))
                            .setHospitalId(hospitalId)
                            .setAccessionNumber(reportNum)
                            .setPatientName(patientName)
                            .build();
                    Get2DCloudfilmUrlResponse get2DCloudfilmUrlResponse = cloudfilm2DServiceBlockingStub.get2DCloudfilmUrl(get2DCloudfilmUrlRequest);
                    if (get2DCloudfilmUrlResponse.getCode() == ResultCode.SUCCEED_VALUE) {
                        url2D = get2DCloudfilmUrlResponse.getPacsViewUrl();
                    } else {
                        logger.error("CloudfilmServiceImpl#getReportInfo(): get2DCloudfilmUrl: {}", get2DCloudfilmUrlResponse.getMsg());
                    }
                }
            }
            builder.setOrderId(orderId);
            builder.setUrl2D(url2D);
            builder.setUrl3D(url3D);
            builder.setVisible2D(visible2D);
            builder.setVisible3D(visible3D);
            builder.setCode(ResultCode.SUCCEED_VALUE);
            return builder.build();
        } catch (YwtCommonException e) {
            builder.setCode(ResultCode.APP_ERROR_VALUE);
            builder.setInfo(e.getMessage());
            return builder.build();
        } catch (Exception e) {
            logger.error("CloudfilmServiceImpl#getReportInfo(request={}):\n {}", request, e.getMessage(), e);
            return builder.setCode(BaseResponse.APP_ERROR).setInfo(e.getMessage()).build();
        }
    }


    @Override
    public GetOrderBillResponse getOrderBill(GetOrderBillRequest request) {
        GetOrderBillResponse.Builder respBuilder = GetOrderBillResponse.newBuilder();
        try {
            if (Checker.isNone(request.getBillDate()) || request.getBillDate().trim().length() != 8) {
                throw new YwtCommonException(YwtCommonRespCode.P_ERR, "账单日期参数不正确");
            }
            int hospitalId = request.getHospitalId();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH:mm:ss");
            Date startDate = sdf.parse(request.getBillDate() + "00:00:00");
            Date endDate = sdf.parse(request.getBillDate() + "23:59:59");
            String startDateStr = DateUtil.convertToString(startDate, "yyyy-MM-dd HH:mm:ss");
            String endDateStr = DateUtil.convertToString(endDate, "yyyy-MM-dd HH:mm:ss");

            List paramList = new ArrayList();
            List<Integer> argTypesList = new ArrayList();

            StringBuilder sql = new StringBuilder("  Select `biz_no`,`order_no`,`total_price`,`payment_no`,`payment_channel`,`refund_status`,\n" +
                    " `refund_no`,`refund_time`,`remark`,`create_time`,`pay_time`,`report_type`\n" +
                    "  from `check_result_order` where `pay_time` >= ? and \n" +
                    " `pay_time` <= ? and hospital_id = ? and `payment_status` = 2 and `total_price` > 0 and `deleted` = 0 order by `pay_time` asc;");
            paramList.add(startDateStr);
            argTypesList.add(Types.VARCHAR);

            paramList.add(endDateStr);
            argTypesList.add(Types.VARCHAR);

            paramList.add(hospitalId);
            argTypesList.add(Types.INTEGER);


            int size = argTypesList.size();
            int[] argTypes = new int[size];
            for (int i = 0; i < size; i++) {
                argTypes[i] = argTypesList.get(i);
            }

            SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet(sql.toString(), paramList.toArray(), argTypes);

            String[] fileHeader = new String[]{
                    "业务编码", "订单号", "支付流水号", "业务类型", "金额", "支付渠道标识", "支付渠道说明", "下单时间", "支付时间", "退款金额", "退款时间", "退款流水号", "附属信息", "备注"
            };

//            WeChat("微信", 1),
//                    AliPay("支付宝", 2),
//                    Cash("现金", 3),          //现场支付
//                    MedicalCard("诊疗卡", 4),
//                    POS("pos机", 5),
//                    FREE("无须支付", 6),
//                    MedicalInsurance("医保", 7);

            Map<Integer, String> chMap = new HashMap<>();
            chMap.put(1, "微信");
            chMap.put(2, "支付宝");
            chMap.put(3, "现金");
            chMap.put(4, "诊疗卡");
            chMap.put(5, "pos机");
            chMap.put(6, "无须支付");
            chMap.put(7, "医保");

            StringBuffer stringBuffer = new StringBuffer();
            CSVPrinter csvPrinter = new CSVPrinter(stringBuffer, CSVFormat.DEFAULT.withHeader(fileHeader));

            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            while (sqlRowSet.next()) {
                int payCh = sqlRowSet.getInt("payment_channel");
                String payChName = chMap.getOrDefault(payCh, "");
                csvPrinter.printRecord(sqlRowSet.getString("biz_no"), sqlRowSet.getString("order_no"), sqlRowSet.getString("payment_no"),
                        sqlRowSet.getString("report_type"), sqlRowSet.getInt("total_price"),
                        payCh, payChName, sdf2.format(sqlRowSet.getDate("create_time")),
                        sdf2.format(sqlRowSet.getDate("pay_time")), 0, "", "", "", sqlRowSet.getString("remark"));
            }

            //退款账单
            sql = new StringBuilder("  Select `biz_no`,`order_no`,`total_price`,`payment_no`,`payment_channel`,`refund_status`,\n" +
                    " `refund_no`,`refund_time`,`remark`,`create_time`,`pay_time`,`report_type`\n" +
                    "  from `check_result_order` where `refund_time` >= ? and \n" +
                    " `refund_time` <= ? and hospital_id = ? and `payment_status` = 2  and refund_status = 1 and \n" +
                    " `total_price` > 0 and `deleted` = 0 order by `refund_time` asc;");
            sqlRowSet = jdbcTemplate.queryForRowSet(sql.toString(), paramList.toArray(), argTypes);

            while (sqlRowSet.next()) {
                int payCh = sqlRowSet.getInt("payment_channel");
                String payChName = chMap.getOrDefault(payCh, "");
                csvPrinter.printRecord(sqlRowSet.getString("biz_no"), sqlRowSet.getString("order_no"), sqlRowSet.getString("payment_no"),
                        sqlRowSet.getString("report_type"), 0, payCh, payChName, sdf2.format(sqlRowSet.getDate("create_time")),
                        sdf2.format(sqlRowSet.getDate("pay_time")), sqlRowSet.getInt("total_price"), sdf2.format(sqlRowSet.getDate("refund_time")),
                        sqlRowSet.getString("refund_no"), "", sqlRowSet.getString("remark"));
            }

            csvPrinter.flush();

            respBuilder.setCode(0).setData(stringBuffer.toString());
            return respBuilder.build();
        } catch (YwtCommonException e) {
            respBuilder.setCode(ResultCode.APP_ERROR_VALUE).setInfo(e.getMessage());
            return respBuilder.build();
        } catch (Exception e) {
            logger.error("getOrderBill(): {}", e.getMessage(), e);
            return respBuilder.setCode(BaseResponse.APP_ERROR).setInfo(e.getMessage()).build();
        }
    }


    //影像报告订单退款回调
    @Override
    public RefundCheckResultOrderCallbackResponse refundCheckResultOrderCallback(RefundCheckResultOrderCallbackRequest request) {
        logger.info("refundCheckResultOrderCallback(): {}", request);
        RefundCheckResultOrderCallbackResponse response;
        try {
            String sql =
                    "update check_result_order set " +
                            "refund_status = ?, " +
                            "status = ?, " +
                            "refund_time = now() " +
                            "where refund_no = ? and refund_status = ?;";
            Object[] args = new Object[]{
                    request.getRefundStatus(),
                    CheckResultOrderEnum.Refunded.getValue(),
                    request.getRefundNo(),
                    RefundStatusEnum.PENDING.getValue()
            };
            int[] types = new int[]{
                    Types.INTEGER,
                    Types.INTEGER,
                    Types.VARCHAR,
                    Types.INTEGER
            };
            int count = jdbcTemplate.update(sql, args, types);

            if (count > 0) {
                response = RefundCheckResultOrderCallbackResponse.newBuilder()
                        .setCode(ResultCode.SUCCEED_VALUE)
                        .build();
            } else {
                response = RefundCheckResultOrderCallbackResponse.newBuilder()
                        .setCode(ResultCode.APP_ERROR_VALUE)
                        .setMsg("流水号不存在或重复回调")
                        .build();
            }
            return response;
        } catch (Exception e) {
            logger.error("#CloudfilmServiceImpl#refundCheckResultOrderCallback:{},{}", e.getMessage(), e);
            return RefundCheckResultOrderCallbackResponse.newBuilder()
                    .setCode(ResultCode.APP_ERROR_VALUE)
                    .setMsg(e.getMessage())
                    .build();
        }
    }


}
