package com.ywt.mg.services;

import com.ywt.mg.core.SqlHelper;
import com.ywt.mg.core.utils.Checker;
import com.ywt.mg.core.utils.DateUtil;
import com.ywt.mg.core.utils.ExcelHelper;
import com.ywt.mg.core.utils.FormatUtil;
import com.ywt.mg.domain.entities.*;
import com.ywt.mg.domain.models.ConstantDef;
import com.ywt.mg.domain.models.ExcelDataMap;
import com.ywt.mg.domain.models.enums.*;
import com.ywt.mg.domain.models.pojo.ExcelCollectPojo;
import com.ywt.mg.params.registeredOrder.RegisteredOrderListRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class RegisteredOrderService {
    private static Logger logger = LoggerFactory.getLogger(RegisteredOrderService.class);


    @Autowired
    private SqlHelper sqlHelper;

    @Autowired
    private OrderPaymentService orderPaymentService;

    @Autowired
    private MedicalCardRepository medicalCardRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private DownloadRecordService downloadRecordService;

    @Autowired
    private RefundLogService refundLogService;


    public List<RegisteredOrder> queryRegisteredOrderList(RegisteredOrderListRequest request) {
        List<Object> paramList = new ArrayList<>();
        String whereSql = " ( 1=1 )";
        try {
            String orderno = request.getOrderno();
            if (!Checker.isNull(orderno)) {
                whereSql += " and ( order_no like ?)";
                paramList.add("%" + orderno.trim() + "%");
            }

            String patientname = request.getPatientname();
            if (!Checker.isNull(patientname)) {
                whereSql += " and ( patient_name like ?)";
                paramList.add("%" + patientname.trim() + "%");
            }

            String patientmobile = request.getPatientmobile();
            if (!Checker.isNull(patientmobile)) {
                List<MedicalCard> medicalCardList = medicalCardRepository.getCardByMobile(patientmobile);
                if (!Checker.isNone(medicalCardList)) {
                    whereSql += " and ( medical_card_id = -1 ";
                    for (MedicalCard medicalCard : medicalCardList) {
                        whereSql += " or medical_card_id = ? ";
                        paramList.add(medicalCard.getId());
                    }
                    whereSql += " ) ";
                } else {
                    whereSql += " and (medical_card_id = -1) ";
                }

            }

            String doctorname = request.getDoctorname();
            if (!Checker.isNull(doctorname)) {
                whereSql += " and ( doctor_name like ?)";
                paramList.add("%" + doctorname.trim() + "%");
            }

            String deptname = request.getDeptname();
            if (!Checker.isNull(deptname)) {
                whereSql += " and ( dept_name like ?)";
                paramList.add("%" + deptname.trim() + "%");
            }

            //支付状态（0-待支付，1-支付处理中，2-支付成功，3-支付失败）
            String paymentstatus = request.getPaymentstatus();
            if (!Checker.isNull(paymentstatus)) {
                whereSql += " and ( payment_status =  ?  )";
                paramList.add(Integer.parseInt(paymentstatus));
            }

            //订单来源（ 1-患者端-安卓，2-患者端-苹果，3-微信小程序，4-微信公众号）
            String source = request.getSource();
            if (!Checker.isNull(source)) {
                int sourceInt = Integer.parseInt(source);
                if (sourceInt == TerminalEnum.TaiheWxOfficial.getValue() || sourceInt == TerminalEnum.NF_HOSPITAL_BY_PATIENT_MINI_PROGRAM.getValue()) {
                    whereSql += " and ( registered_status > 0 )";
                }
                whereSql += " and ( source = ? )";
                paramList.add(sourceInt);

            }
            //订单类型（ 1-普通预约，2-加号预约）
            String type = request.getType();
            if (!Checker.isNull(type)) {
                int typeInt = Integer.parseInt(type);
                if (typeInt == 2) {
                    whereSql += " and ( registered_type =  ?)";
                    paramList.add(RegisteredTypeEnum.ADDITIONAL.getValue());
                } else {
                    // 当类型为普通预约时，还有部分数据的值为空
                    whereSql += " and ( registered_type =  ?  or registered_type is null )";
                    paramList.add(RegisteredTypeEnum.GENERAL.getValue());
                }
            }

            String Format_Date = "yyyy-MM-dd";
            SimpleDateFormat format = new SimpleDateFormat(Format_Date);

            //就诊时间
            String registeredEndTime = request.getRegisteredEndTime();
            if (!Checker.isNull(registeredEndTime)) {
                whereSql += " and ( registered_date < ? )";
                Date date = format.parse(registeredEndTime);

                // 把日期往后增加一天.整数往后推,负数往前移动
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(calendar.DATE, 1);
                // 这个时间就是日期往后推一天的结果
                date = calendar.getTime();

                paramList.add(date);
            }

            String registeredStartTime = request.getRegisteredStartTime();
            if (!Checker.isNull(registeredStartTime)) {
                whereSql += " and ( registered_date >= ?)";
                Date date = format.parse(registeredStartTime);
                paramList.add(date);
            }

            //下单时间
            String createEndTime = request.getCreateEndTime();
            if (!Checker.isNull(createEndTime)) {
                whereSql += " and ( create_time < ? )";
                Date date = format.parse(createEndTime);

                // 把日期往后增加一天.整数往后推,负数往前移动
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(calendar.DATE, 1);
                // 这个时间就是日期往后推一天的结果
                date = calendar.getTime();

                paramList.add(date);
            }

            String createStartTime = request.getCreateStartTime();
            if (!Checker.isNull(createStartTime)) {
                whereSql += " and ( create_time >= ?)";
                Date date = format.parse(createStartTime);
                paramList.add(date);
            }

            // 医院ID不为空，registered_status 根据hospitalID代表不同的值
            // 南方医院挂号：0-待支付、1-待就诊、2-已完成、3-已取消
            // 太和医院挂号：1-待就诊、2-已完成、3-已取消、4-已退款
            // 南方医科大学南方医院白云分院挂号：1-待就诊、2-已完成、3-已取消、4-已退款
            String registeredstatus = request.getRegisteredstatus();
            int hospitalId = Checker.getIntegerValue(request.getHospitalId());
            if (request.getHospitalId() > 0) {
                if (hospitalId == ConstantDef.NF_HOSPITAL_ID) {
                    // 医院过滤
                    whereSql += " and ( hospital_id = ?) ";
                    paramList.add(hospitalId);
                    if (!Checker.isNull(registeredstatus)) {
                        int status = Integer.parseInt(registeredstatus);
                        //  0-待支付 registered_status = 0 
                        if (status == 0) {
                            whereSql += " and (registered_status = 0 and ( registered_type =  ?  or registered_type is null ) )";
                            paramList.add(RegisteredTypeEnum.GENERAL.getValue());
                        }
                        // 1-待就诊：registered_status=1，以及时间判断
                        if (status == 1) {
                            whereSql += "  and ( str_to_date(CONCAT(registered_date,\" \",end_time), '%Y-%m-%d %H:%i') >= now() )";
                            whereSql += " and ( registered_status & ? = 0 and registered_status & ? = 0 and registered_status > 0 ) ";
                            paramList.add(RegisteredStatusEnum.Cancel.getValue());
                            paramList.add(RegisteredStatusEnum.Back.getValue());
                        }
                        // 2- 已完成：registered_status=1，4 以及时间判断 
                        if (status == 2) {
                            whereSql += " and ( str_to_date(CONCAT(registered_date,\" \",end_time), '%Y-%m-%d %H:%i') < now() )";
                            whereSql += " and ( registered_status & ? = 0 and registered_status & ? = 0 and registered_status > 0 ) ";
                            paramList.add(RegisteredStatusEnum.Cancel.getValue());
                            paramList.add(RegisteredStatusEnum.Back.getValue());
                        }
                        // 3-已取消：registered_status=2
                        if (status == 3) {
                            status = RegisteredStatusEnum.Cancel.getValue();
                            whereSql += " and ( registered_status & ? > 0 or registered_status & ? > 0)";
                            paramList.add(status);
                            paramList.add(RegisteredStatusEnum.Back.getValue());
                        }
                        if (status == 4) {
                            whereSql += " and ( registered_status = -1 )";
                        }
                    }
                }

                // 太和医院的不显示出来位支付的订单
                if (hospitalId == ConstantDef.TAIHE_HOSPITAL_ID || hospitalId == ConstantDef.NFBY_HOSPITAL_ID) {
                    // 太和医院挂号订单过滤掉未支付的
                    whereSql += " and ( (registered_status > 0 and payment_status = ? ) or (refund_status = ?) ) and ( hospital_id = ?)  ";
                    paramList.add(PaymentStatusEnum.Success.getValue());
                    paramList.add(RefundStatusEnum.SUCCESS.getValue());
                    paramList.add(hospitalId);

                    // 太和医院挂号：1-待就诊、2-已完成、3-已取消、4-已退款
                    if (!Checker.isNull(registeredstatus)) {
                        int status = Integer.parseInt(registeredstatus);
                        if (status == 0) {
                            // 因为不显示带支付的，所以如果搜索待支付的，直接给显示空
                            whereSql += " and ( registered_status = -1 )";
                        }
                        //  1-待就诊、2-已完成、3-已取消、4-已退款
                        // 1-待就诊：payment_status = 1, registered_status=1，以及时间判断
                        if (status == 1) {
                            status = RegisteredStatusEnum.Booked.getValue();
                            int tookStatus = RegisteredStatusEnum.Took.getValue();
                            whereSql += " and (( registered_status & ?  > 0 and registered_status < ? ) or  (registered_status & ?  > 0 and registered_status < ?) )";
                            whereSql += " and (payment_status = ?) ";
                            whereSql += " and ( str_to_date(CONCAT(registered_date,\" \",end_time), '%Y-%m-%d %H:%i') >= now() )";
                            paramList.add(status);
                            paramList.add(2 * status);
                            paramList.add(tookStatus);
                            paramList.add(2 * tookStatus);
                            paramList.add(PaymentStatusEnum.Success.getValue());
                        }
                        if (status == 2) {
                            //2-已完成：payment_status = 1, registered_status=1，4 以及时间判断
                            status = RegisteredStatusEnum.Booked.getValue();
                            int tookStatus = RegisteredStatusEnum.Took.getValue();
                            whereSql += " and ( (registered_status & ?  > 0 and registered_status < ?) or  (registered_status & ?  > 0 and registered_status < ?) )";
                            whereSql += " and (payment_status = ?) ";
                            whereSql += " and ( str_to_date(CONCAT(registered_date,\" \",end_time), '%Y-%m-%d %H:%i') < now() )";
                            paramList.add(status);
                            paramList.add(2 * status);
                            paramList.add(tookStatus);
                            paramList.add(2 * tookStatus);
                            paramList.add(PaymentStatusEnum.Success.getValue());
                        }
                        if (status == 3) {
                            // 3-已取消：registered_status=2
                            status = RegisteredStatusEnum.Cancel.getValue();
                            whereSql += " and ( registered_status & ?  > 0 )";
                            paramList.add(status);
                        }
                        if (status == 4) {
                            // 4-已退款：refund_status=1
                            whereSql += " and ( refund_status = ? or (registered_status & ?  > 0 and registered_status < ?) )";
                            paramList.add(RefundStatusEnum.SUCCESS.getValue());
                            int backStatus = RegisteredStatusEnum.Back.getValue();
                            paramList.add(backStatus);
                            paramList.add(2 * backStatus);
                        }
                    }
                }
            }

            //对账时间
            String billEndTime = request.getBillEndTime();
            if (!Checker.isNull(billEndTime)) {
                whereSql += " and ( payment_time < ? or refund_time < ? )";
                Date date = format.parse(billEndTime);

                // 把日期往后增加一天.整数往后推,负数往前移动
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(calendar.DATE, 1);
                // 这个时间就是日期往后推一天的结果
                date = calendar.getTime();
                paramList.add(date);
                paramList.add(date);
            }

            String billStartTime = request.getBillStartTime();
            if (!Checker.isNull(billStartTime)) {
                whereSql += " and ( payment_time >= ? or refund_time >= ?)";
                Date date = format.parse(billStartTime);
                paramList.add(date);
                paramList.add(date);
            }
            // 处理交易流水号，考虑到性能，直接采用全匹配到方式
            String transactionId = request.getTransactionId();
            if (!Checker.isNull(transactionId)) {
                OrderPayment orderPayment = orderPaymentService.getOrderPaymentByTransactionId(transactionId);
                if (!Checker.isNone(orderPayment)) {
                    whereSql += " and ( order_id = ? )";
                    paramList.add(orderPayment.getOrderId());
                } else {
                    whereSql += " and ( order_id = -1 )";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("queryRegisteredOrderList:{},{}", e.getMessage(), e);
        }
        return sqlHelper.getDownLoadList("*", whereSql, "create_time desc", RegisteredOrder.class, paramList.toArray());
    }

    public void downloadRegisteredOrderList(int downloadRecordId, String fileName, RegisteredOrderListRequest request) {
        try {
            int hosp = Checker.getIntegerValue(request.getHosp());
//            String[] titleStr = {"订单号", "支付流水号", "交易流水号", "患者姓名", "患者手机号", "诊疗卡",
//                    "医生姓名", "科室", "金额", "就诊时间", "来源", "类型",
//                    "订单状态", "支付状态", "下单时间", "备注"};
            // 单元格
            String col0 = "订单号";
            String col1 = "支付流水号";
            String col2 = "交易流水号";
            String col3 = "患者姓名";
            String col4 = "患者手机号";
            String col5 = "诊疗卡";
            String col6 = "医生姓名";
            String col7 = "科室";
            String col8 = "金额";
            String col9 = "就诊时间";
            String col10 = "来源";
            String col11 = "类型";
            String col12 = "订单状态";
            String col13 = "支付状态";
            String col14 = "下单时间";
            String col15 = "备注";

            String[] columns = new String[]{col0, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10,
                    col11, col12, col13, col14, col15};
            if (hosp > 0) {
                columns = new String[]{col0, col1, col3, col4, col5, col6, col7, col8, col9, col10,
                        col11};
            }
            List<RegisteredOrder> registeredOrderList = queryRegisteredOrderList(request);
            List<RegisteredOrder> valueList = new ArrayList();
            int payTotal = 0, refundTotal = 0;
            ExcelDataMap map = new ExcelDataMap(columns);
            if (!Checker.isNone(registeredOrderList)) {
//                valueList.addAll(registeredOrderList.getItems());
//                int size = registeredOrderList.getTotalPage();
//                List<RegisteredOrder> lst = registeredOrderList.getItems();
                List<MedicalCard> medicalCardList = getMedicalCardListByRegisteredOrderList(registeredOrderList);
                List<OrderPayment> orderPaymentList = orderPaymentService.getOrderPaymentListByRegisteredOrderList(registeredOrderList);
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                for (RegisteredOrder p : registeredOrderList) {
                    // 金额
                    String totalStr = FormatUtil.intShrink100ToStr(p.getTotal());
                    // 就诊时间
                    String registeredTime = sdf2.format(p.getRegisteredDate()) + "  " + p.getStartTime() + "~" + p.getEndTime();
                    // 来源
                    String source = TerminalEnum.valueOf(p.getSource()).getDisplayName();
                    // 类型
                    int typeInt = Checker.getIntegerValue(p.getRegisteredType());
                    String typeName = RegisteredTypeEnum.valueOf(typeInt).getDisplayName();
                    // 订单状态
                    int value = RegisteredStatusEnum.getValue(p.getRegisteredStatus());
                    String registeredStatus = getRegisteredStatusName(value, p);
                    // 支付状态
                    String paymentStatus = PaymentStatusEnum.getPaymentStatus(p.getPaymentStatus()).getDisplayName();
                    // 下单时间
                    String createTime = FormatUtil.createTimeFormatList(p.getCreateTime());
                    // 备注
                    String cancelRemark = Checker.getStringValue(p.getCancelRemark());

                    String patientMobile = "", cardNo = "";
                    MedicalCard medicalCard = medicalCardList.stream().filter(m -> m.getId().intValue() == p.getMedicalCardId()).findFirst().orElse(null);
                    if (!Checker.isNone(medicalCard)) {
                        patientMobile = Checker.getStringValue(medicalCard.getMobile());
                        cardNo = Checker.getStringValue(medicalCard.getCardNo());
                    }
                    String transactionId = orderPaymentService.getTransactionIdByOrderId(orderPaymentList, Checker.getIntegerValue(p.getOrderId()));
//                    String[] bodyStr = {p.getOrderNo(), p.getPaymentNo(), transactionId, p.getPatientName(), patientMobile, cardNo,
//                            p.getDoctorName(), p.getDeptName(), totalStr, registeredTime, source,
//                            typeName, registeredStatus, paymentStatus, createTime, cancelRemark};
                    if (Checker.getIntegerValue(p.getPaymentStatus()) == PaymentStatusEnum.Success.getValue()) {
                        payTotal += Checker.getIntegerValue(p.getTotal());
                    }
                    if (Checker.getIntegerValue(p.getRefundStatus()) == RefundStatusEnum.SUCCESS.getValue()) {
                        refundTotal += Checker.getIntegerValue(p.getTotal());
                    }
                    if (hosp > 0) {
                        map.getStringListSafely(col0).add(p.getOrderNo());
                        map.getStringListSafely(col1).add(p.getPaymentNo());
//                        map.getStringListSafely(col2).add(transactionId);
                        map.getStringListSafely(col3).add(p.getPatientName());
                        map.getStringListSafely(col4).add(patientMobile);
                        map.getStringListSafely(col5).add(cardNo);
                        map.getStringListSafely(col6).add(p.getDoctorName());
                        map.getStringListSafely(col7).add(p.getDeptName());
                        map.getStringListSafely(col8).add(totalStr);
                        map.getStringListSafely(col9).add(registeredTime);
                        map.getStringListSafely(col10).add(source);
                        map.getStringListSafely(col11).add(typeName);
                        map.getStringListSafely(col12).add(registeredStatus);
                        map.getStringListSafely(col13).add(paymentStatus);
                        map.getStringListSafely(col14).add(createTime);
                        map.getStringListSafely(col15).add(cancelRemark);
                    } else {
                        map.getStringListSafely(col0).add(p.getOrderNo());
                        map.getStringListSafely(col1).add(p.getPaymentNo());
                        map.getStringListSafely(col2).add(transactionId);
                        map.getStringListSafely(col3).add(p.getPatientName());
                        map.getStringListSafely(col4).add(patientMobile);
                        map.getStringListSafely(col5).add(cardNo);
                        map.getStringListSafely(col6).add(p.getDoctorName());
                        map.getStringListSafely(col7).add(p.getDeptName());
                        map.getStringListSafely(col8).add(totalStr);
                        map.getStringListSafely(col9).add(registeredTime);
                        map.getStringListSafely(col10).add(source);
                        map.getStringListSafely(col11).add(typeName);
                        map.getStringListSafely(col12).add(registeredStatus);
                        map.getStringListSafely(col13).add(paymentStatus);
                        map.getStringListSafely(col14).add(createTime);
                        map.getStringListSafely(col15).add(cancelRemark);
                    }
                }
            }
            int size = registeredOrderList.size();
            List<ExcelCollectPojo> itemList = getStatisticsData(size, payTotal, refundTotal);
            downloadRecordService.createFileAndUploadOssAndSaveToDataBase(fileName, downloadRecordId, map, itemList);

        } catch (Exception e) {
            logger.error("/registeredOrder/downloadRegisteredOrderList: {}", e.getMessage(), e);
            e.printStackTrace();
        }
    }

    public List<MedicalCard> getMedicalCardListByRegisteredOrderList(List<RegisteredOrder> registeredOrderList) {
        List<Integer> medIds = getMedicalCardIdListByRegisteredOrderList(registeredOrderList);
        String medIdsStr = FormatUtil.listToIds(medIds);
        String sql = "select * from medical_card where id in (-1" + medIdsStr + "-1) ;";
        List<MedicalCard> medicalCardList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(MedicalCard.class));
        return medicalCardList;
    }


    private List<Integer> getMedicalCardIdListByRegisteredOrderList(List<RegisteredOrder> items) {
        ArrayList<Integer> medIds = new ArrayList<>();
        for (RegisteredOrder item : items) {
            medIds.add(item.getMedicalCardId());
        }
        return medIds;
    }

    /**
     * 普通挂号 -- 太和医院挂号后台显示状态：待就诊、已完成、已取消、已退款
     * 普通挂号 -- 南方医院挂号后台显示状态：待支付、待就诊、已完成、已取消
     * 加号预约状态：待就诊、已完成、已取消
     *
     * @param dealtRegisteredValue 处理过后的预约挂号订单状态值
     * @return
     */
    public String getRegisteredStatusName(int dealtRegisteredValue, RegisteredOrder registeredOrder) {
        if (!Checker.isNone(registeredOrder)) {
            // type: 2-加号预约 1或其他-普通预约
            int type = Checker.getIntegerValue(registeredOrder.getRegisteredType());
            int payStatus = Checker.getIntegerValue(registeredOrder.getPaymentStatus());
            int registeredStatus = Checker.getIntegerValue(registeredOrder.getRegisteredStatus());

            // 加号预约 ：待就诊、已完成、已取消
            if (type == RegisteredTypeEnum.ADDITIONAL.getValue()) {
                // 已取消：registered_status=2
                if ((registeredStatus & RegisteredStatusEnum.Cancel.getValue()) > 0) {
                    return RegisteredStatusEnum.Cancel.getDisplayName();
                }
                // 待就诊：registered_status=1，以及时间判断 
                // 已完成：registered_status=1，4，以及时间判断 
                // 得到就诊时间的最大时间段
                Date date = getStringToDate(registeredOrder.getRegisteredDate(), registeredOrder.getEndTime());
                Date currentDate = new Date();
                if (currentDate.after(date)) {
                    return "已完成";
                } else {
                    return "待就诊";
                }
            }
            // 普通挂号，根据医院来
            int hospitalId = Checker.getIntegerValue(registeredOrder.getHospitalId());
            // 1 - 南方医院， 12 -太和医院, 41-南方医科大学白云分院
            if (hospitalId == ConstantDef.NF_HOSPITAL_ID) {
                // 已取消
                if (dealtRegisteredValue == RegisteredStatusEnum.Back.getValue()
                        || dealtRegisteredValue == RegisteredStatusEnum.Cancel.getValue()) {
                    return RegisteredStatusEnum.Cancel.getDisplayName();
                }
                if (dealtRegisteredValue == RegisteredStatusEnum.Booked.getValue() || dealtRegisteredValue == RegisteredStatusEnum.Took.getValue()) {
                    // 得到就诊时间的最大时间段
                    Date date = getStringToDate(registeredOrder.getRegisteredDate(), registeredOrder.getEndTime());
                    Date currentDate = new Date();
                    if (currentDate.after(date)) {
                        return "已完成";
                    } else {
                        return "待就诊";
                    }
                }
                return "待支付";
            }
            if (hospitalId == ConstantDef.TAIHE_HOSPITAL_ID || hospitalId == ConstantDef.NFBY_HOSPITAL_ID) {
                int refundStatus = Checker.getIntegerValue(registeredOrder.getRefundStatus());
                // 已退款
                if (refundStatus == RefundStatusEnum.SUCCESS.getValue() || dealtRegisteredValue == RegisteredStatusEnum.Back.getValue()) {
                    return "已退款";
                }
                // 已取消
                if (dealtRegisteredValue == RegisteredStatusEnum.Cancel.getValue()) {
                    return RegisteredStatusEnum.Cancel.getDisplayName();
                }
                if (payStatus == PaymentStatusEnum.Success.getValue() &&
                        (dealtRegisteredValue == RegisteredStatusEnum.Booked.getValue() || dealtRegisteredValue == RegisteredStatusEnum.Took.getValue())) {
                    // 得到就诊时间的最大时间段
                    Date date = getStringToDate(registeredOrder.getRegisteredDate(), registeredOrder.getEndTime());
                    Date currentDate = new Date();
                    if (currentDate.after(date)) {
                        return "已完成";
                    } else {
                        return "待就诊";
                    }
                }
            }
            return "";
        }
        return "";
    }

    private Date getStringToDate(Date date, String endTime) {
        String dateStr = DateUtil.convertToString(date, "yyyy-MM-dd");
        dateStr = dateStr + " " + endTime + ":00";
        Date backDate = DateUtil.stringToDate(dateStr);
        return backDate;
    }

    private List<ExcelCollectPojo> getStatisticsData(int size, int payTotal, int refundTotal) {
        int startRows = size + 3;
        int startColumn = 3;

        List<ExcelCollectPojo> customExcelItemList = new ArrayList<>();
        customExcelItemList.add(new ExcelCollectPojo(startColumn + 1, startRows + 1, new String[]{"支付总额", FormatUtil.intShrink100ToStr(payTotal)}));
        customExcelItemList.add(new ExcelCollectPojo(startColumn + 1, startRows + 2, new String[]{"退款总额", FormatUtil.intShrink100ToStr(refundTotal)}));
        customExcelItemList.add(new ExcelCollectPojo(startColumn + 1, startRows + 3, new String[]{"实际支付金额", FormatUtil.intShrink100ToStr(payTotal - refundTotal)}));
        return customExcelItemList;
    }


    public void downloadRegisteredOrderBillsList(int downloadRecordId, String fileName, RegisteredOrderListRequest request) {
//        String[] titleStr = {"交易类型*", "系统参考号*", "交易金额*", "交易日期*", "订单号", "类型"};
        try {
            String col0 = "交易类型*";
            String col1 = "系统参考号*";
            String col2 = "交易金额*";
            String col3 = "交易日期*";
            String col4 = "订单号";
            String col5 = "类型";
            String[] columns = new String[]{col0, col1, col2, col3, col4, col5};

            List<RegisteredOrder> registeredOrderList = queryRegisteredOrderList(request);
            ExcelDataMap map = new ExcelDataMap(columns);
            if(!Checker.isNone(registeredOrderList)){
                List<OrderPayment> orderPaymentList = orderPaymentService.getOrderPaymentListByRegisteredOrderList(registeredOrderList);
                // 得到退款的记录日志（需要从 refund_log 获取 refund_id 字段）
                List<RefundLog> refundLogList = refundLogService.getRefundLogListByRegisteredOrderList(registeredOrderList);
                List<RegisteredOrder> refundRegisteredOrderList = new ArrayList<>(getRefundRegisteredOrderList(registeredOrderList));
                Date billStartTime = DateUtil.stringToDate(request.getBillStartTime() + ConstantDef.BILL_TIME_START_FORMAT);
                Date billEndTime = DateUtil.stringToDate(request.getBillEndTime() + ConstantDef.BILL_TIME_END_FORMAT);
                for (RegisteredOrder p : registeredOrderList) {
                    if (!Checker.isNone(p) && Checker.getIntegerValue(p.getPaymentStatus()) == PaymentStatusEnum.Success.getValue()
                            && Checker.getIntegerValue(p.getTotal()) > 0
                            && !Checker.isNone(p.getPaymentTime())) {
                        // "交易类型*", "系统参考号*", "交易金额*", "交易日期*", "订单号", "类型"
                        Date paymentTime = Checker.getDateValue(p.getPaymentTime());
                        if (!Checker.isNone(paymentTime) && paymentTime.after(billStartTime) && paymentTime.before(billEndTime)) {
                            String type = ConstantDef.BILL_PAYMENT_STR;
                            // 交易流水号
                            String transactionId = orderPaymentService.getTransactionIdByOrderId(orderPaymentList, Checker.getIntegerValue(p.getOrderId()));
                            // 交易金额
                            String totalStr = FormatUtil.intShrink100ToStr(p.getTotal());
                            // 交易时间
                            String paymentTimeStr = FormatUtil.createTimeFormatDetail(p.getPaymentTime());
                            // 订单号
                            String orderNo = Checker.getStringValue(p.getOrderNo());
                            // 类型
                            int typeInt = Checker.getIntegerValue(p.getRegisteredType());
                            String typeName = RegisteredTypeEnum.valueOf(typeInt).getDisplayName();

//                            String[] bodyStr = {type, transactionId, totalStr, paymentTimeStr, orderNo, typeName};

                            map.getStringListSafely(col0).add(type);
                            map.getStringListSafely(col1).add(transactionId);
                            map.getStringListSafely(col2).add(totalStr);
                            map.getStringListSafely(col3).add(paymentTimeStr);
                            map.getStringListSafely(col4).add(orderNo);
                            map.getStringListSafely(col5).add(typeName);

                        }
                    }
                }
                for (RegisteredOrder p : refundRegisteredOrderList) {
                    if (!Checker.isNone(p) && Checker.getIntegerValue(p.getRefundStatus()) == RefundStatusEnum.SUCCESS.getValue()) {
                        // "交易类型*", "系统参考号*", "交易金额*", "交易日期*", "订单号", "类型"
                        Date refundTime = Checker.getDateValue(p.getRefundTime());
                        if (!Checker.isNone(refundTime) && refundTime.after(billStartTime) && refundTime.before(billEndTime)) {
                            String type = ConstantDef.BILL_REFUND_STR;
                            // 交易流水号
                            String transactionId = refundLogService.getRefundIdByRefundNo(refundLogList, p.getRefundNo());
                            // 交易金额
                            String totalStr = FormatUtil.intShrink100ToStr(p.getTotal());
                            // 交易时间
                            String refundTimeStr = FormatUtil.createTimeFormatDetail(p.getRefundTime());
                            // 订单号
                            String orderNo = Checker.getStringValue(p.getOrderNo());
                            // 类型
                            int typeInt = Checker.getIntegerValue(p.getRegisteredType());
                            String typeName = RegisteredTypeEnum.valueOf(typeInt).getDisplayName();
                            map.getStringListSafely(col0).add(type);
                            map.getStringListSafely(col1).add(transactionId);
                            map.getStringListSafely(col2).add(totalStr);
                            map.getStringListSafely(col3).add(refundTimeStr);
                            map.getStringListSafely(col4).add(orderNo);
                            map.getStringListSafely(col5).add(typeName);


                        }
                    }
                }

            }
            List<ExcelCollectPojo> itemList = new ArrayList<>();
            downloadRecordService.createFileAndUploadOssAndSaveToDataBase(fileName, downloadRecordId, map, itemList);

        } catch (Exception e) {
            logger.error("/registeredOrder/downloadRegisteredOrderBillsList: {}", e.getMessage(), e);
            e.printStackTrace();
        }
    }

    private List<RegisteredOrder> getRefundRegisteredOrderList(List<RegisteredOrder> items) {
        if (!Checker.isNone(items)) {
            return items.stream().filter(p -> Checker.getIntegerValue(p.getRefundStatus()) == RefundStatusEnum.SUCCESS.getValue()).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }
}
