package com.ywt.mg.services;

import com.ywt.mg.configs.ParameterConfigurer;
import com.ywt.mg.core.PagedList;
import com.ywt.mg.core.SqlHelper;
import com.ywt.mg.core.utils.Checker;
import com.ywt.mg.core.utils.StringHelper;
import com.ywt.mg.domain.entities.*;
import com.ywt.mg.domain.models.ConstantDef;
import com.ywt.mg.domain.models.enums.PaymentStatusEnum;
import com.ywt.mg.domain.models.enums.RefundStatusEnum;
import com.ywt.mg.domain.models.enums.SettlementStatusEnum;
import com.ywt.mg.web.BaseResponse;
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;

/**
 * 会诊订单相关方法
 *
 * @author daiyihua
 */
@Service
public class OfflineService {

    private static Logger logger = LoggerFactory.getLogger(OfflineService.class);

    @Autowired
    private SqlHelper sqlHelper;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private TreatmentRepository treatmentRepository;

    @Autowired
    private TreatmentOrderViewMgRepository treatmentOrderViewMgRepository;

    @Autowired
    private OrderPaymentRepository orderPaymentRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ParameterConfigurer parameterConfigurer;

    @Autowired
    private AuthService authService;

    @Autowired
    private OfflineConsultationRepository offlineConsultationRepository;


    @Autowired
    private OrderPaymentService orderPaymentService;

    @Autowired
    private RefundLogService refundLogService;

    /**
     * 查询线下就诊列表
     *
     * @param orderNo          订单号
     * @param patientName      患者姓名
     * @param patientMobile    患者手机号
     * @param paymentStatus    支付状态 {@link PaymentStatusEnum}
     * @param status           订单状态
     * @param doctorName       医生姓名
     * @param searchHospitalId 医院id
     * @param payTimeStart     支付查询开始时间
     * @param payTimeEnd       支付查询结束时间
     * @param pageIndex        当前页数
     * @param pageSize         每页大小
     * @return {@link BaseResponse}
     */
    public PagedList<OfflineConsultation> queryOfflineList(String orderNo, String patientName, String patientMobile, String paymentStatus, String status,
                                                           String doctorName, int searchHospitalId, String hisClinicCode, String payTimeStart, String payTimeEnd,
                                                           String refundTimeStart, String refundTimeEnd, int hospitalId,
                                                           int pageIndex, int pageSize, String source) {
        Map map = queryOfflineListCommon(orderNo, patientName, patientMobile, paymentStatus, status,
                doctorName, searchHospitalId, hisClinicCode, payTimeStart, payTimeEnd, refundTimeStart,
                refundTimeEnd, hospitalId, source);
        String whereSql = (String) map.get(ConstantDef.KEY_WHERE_SQL);
        List paramList = (List) map.get(ConstantDef.KEY_PARAM_LIST);
        return sqlHelper.getPagedList(pageIndex, pageSize, "*", whereSql, "create_time desc", OfflineConsultation.class, paramList.toArray());
    }

    public List<OfflineConsultation> queryDownloadOfflineList(String orderNo, String patientName, String patientMobile, String paymentStatus, String status,
                                                              String doctorName, int searchHospitalId, String hisClinicCode, String payTimeStart, String payTimeEnd,
                                                              String refundTimeStart, String refundTimeEnd, int hospitalId, String source) {
        Map map = queryOfflineListCommon(orderNo, patientName, patientMobile, paymentStatus, status,
                doctorName, searchHospitalId, hisClinicCode, payTimeStart, payTimeEnd, refundTimeStart,
                refundTimeEnd, hospitalId, source);
        String whereSql = (String) map.get(ConstantDef.KEY_WHERE_SQL);
        List paramList = (List) map.get(ConstantDef.KEY_PARAM_LIST);
        String sqlBuilder = "select * from offline_consultation where " + whereSql + "order by create_time desc";
        return jdbcTemplate.query(sqlBuilder, paramList.toArray(), new BeanPropertyRowMapper<>(OfflineConsultation.class));
    }


    public Map queryOfflineListCommon(String orderNo, String patientName, String patientMobile, String paymentStatus, String status,
                                      String doctorName, int searchHospitalId, String hisClinicCode, String payTimeStart, String payTimeEnd,
                                      String refundTimeStart, String refundTimeEnd, int hospitalId, String source) {
        Map map = new HashMap();
        List<Object> paramList = new ArrayList<>();
        String whereSql = " ( 1=1 )";
        try {
            // 添加测试账号过滤
            String testAdminIds = parameterConfigurer.getTestAdminIds();
            String testDoctorIds = parameterConfigurer.getTestDoctorIds();
            String adminStr = "," + authService.getCurrentAdminId() + ",";
            String testAdminIdsStr = "," + testAdminIds + ",";

            // 不是测试账号
            if (!(testAdminIdsStr.contains(adminStr))) {
                String[] testDoctorIdsArr = testDoctorIds.split(",");
                if (!Checker.isNone(testDoctorIdsArr)) {
                    String sqlSubFrom = "";
                    for (String doctorId : testDoctorIdsArr) {
                        sqlSubFrom += "doctor_id != " + doctorId + " and ";
                    }
                    sqlSubFrom = sqlSubFrom.substring(0, sqlSubFrom.lastIndexOf("and"));
                    whereSql += String.format(" and ((%s) or doctor_id is null)", sqlSubFrom);
                }
            }

            if (!Checker.isNull(orderNo)) {
                whereSql += " and ( order_no like ?)";
                paramList.add("%" + orderNo.trim() + "%");
            }

            if (!Checker.isNull(patientName)) {
                whereSql += " and ( real_name like ?)";
                paramList.add("%" + patientName.trim() + "%");
            }

            if (!Checker.isNull(patientMobile)) {
                whereSql += " and ( mobile like ?)";
                paramList.add("%" + patientMobile + "%");
            }

            //status	1-已支付、2-已退费,3-已结算
            if (!Checker.isNull(status)) {
                int orderStatusInt = Integer.parseInt(status);
                if (orderStatusInt == 1) {
                    whereSql += " and ( payment_status = ? and (refund_status <> ? or refund_status is null) and (settlement_status <> ? or settlement_status is null) )";
                    paramList.add(PaymentStatusEnum.Success.getValue());
                    paramList.add(RefundStatusEnum.SUCCESS.getValue());
                    paramList.add(SettlementStatusEnum.SETTLED.getValue());
                } else if (orderStatusInt == 2) {
                    whereSql += " and ( refund_status = ?)";
                    paramList.add(RefundStatusEnum.SUCCESS.getValue());
                } else if (orderStatusInt == 3) {
                    whereSql += " and ( settlement_status = ? and (refund_status <> ? or refund_status is null))";
                    paramList.add(SettlementStatusEnum.SETTLED.getValue());
                    paramList.add(RefundStatusEnum.SUCCESS.getValue());
                }
            }
            //payment_status	tinyint	3	支付状态（0-待支付,1-支付处理中，2-支付成功，3-支付失败）
            if (!Checker.isNull(paymentStatus)) {
                whereSql += " and ( payment_status = ?)";
                paramList.add(Integer.parseInt(paymentStatus));
            }

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

            if (searchHospitalId > -1) {
                whereSql += " and ( hospital_id = ?  )";
                paramList.add(searchHospitalId);
            }

            if (!Checker.isNull(hisClinicCode)) {
                whereSql += " and ( his_clinic_code like ?  )";
                paramList.add("%" + hisClinicCode.trim() + "%");
            }

//            if (hospitalId != -1) {
//                whereSql += " and ( hospital_id = ?  )";
//                paramList.add(hospitalId);
//            }

            String formatDate = "yyyy-MM-dd";

            SimpleDateFormat format = new SimpleDateFormat(formatDate);
            if (!Checker.isNull(payTimeEnd)) {
                whereSql += " and ( pay_time < ?)";
                Date date = format.parse(payTimeEnd);

                //把日期往后增加一天.整数往后推,负数往前移动
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(Calendar.DATE, 1);
                //这个时间就是日期往后推一天的结果
                date = calendar.getTime();
                paramList.add(date);
            }
            if (!Checker.isNull(payTimeStart)) {
                whereSql += " and ( pay_time >= ?)";
                Date date = format.parse(payTimeStart);
                paramList.add(date);
            }
            if (!Checker.isNull(refundTimeEnd)) {
                whereSql += " and ( refund_time < ?)";
                Date date = format.parse(refundTimeEnd);

                //把日期往后增加一天.整数往后推,负数往前移动
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(Calendar.DATE, 1);
                //这个时间就是日期往后推一天的结果
                date = calendar.getTime();
                paramList.add(date);
            }
            if (!Checker.isNull(refundTimeStart)) {
                whereSql += " and ( refund_time >= ?)";
                Date date = format.parse(refundTimeStart);
                paramList.add(date);
            }
            if (!StringHelper.isNullOrWhiteSpace(source)) {
                whereSql += " and ( source = ?)";
                paramList.add(Integer.parseInt(source));
            }

            // 过滤掉删除和待支付的
            whereSql += " and ( deleted = 0  ) and (payment_status > ?) ";
            paramList.add(PaymentStatusEnum.Pending.getValue());

        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put(ConstantDef.KEY_WHERE_SQL, whereSql);
        map.put(ConstantDef.KEY_PARAM_LIST, paramList);
        return map;
    }

    /**
     * 得到线下就诊状态
     *
     * @param off {@link OfflineConsultation}
     * @return statusStr
     */
    public String getOfflineStatusStr(OfflineConsultation off) {
        if (!Checker.isNone(off)) {
            int refundStatus = Checker.getIntegerValue(off.getRefundStatus());
            if (refundStatus == RefundStatusEnum.SUCCESS.getValue()) {
                return "已退款";
            }
            int settlementStatus = Checker.getIntegerValue(off.getSettlementStatus());
            if (settlementStatus == SettlementStatusEnum.SETTLED.getValue()) {
                return SettlementStatusEnum.SETTLED.getDisplayName();
            }
            int payStatus = Checker.getIntegerValue(off.getPaymentStatus());
            if (payStatus == PaymentStatusEnum.Success.getValue()) {
                return "已支付";
            }

        }
        return "";
    }






    public String getUserIdsByList(List<OfflineConsultation> offList) {
        String userIds = "";
        if (!Checker.isNone(offList)) {
            for (OfflineConsultation off : offList) {
                userIds += off.getUserId() + ",";
            }
            userIds = userIds.substring(0, userIds.length() - 1);
        }
        return userIds;
    }


    public List<User> getUserListByOffList(List<OfflineConsultation> offList, int size) {
        String userIds = getUserIdsByList(offList);
        if (!Checker.isNone(userIds)) {
            String sql = "select * from user where id in (" + userIds + ") and is_deleted = 0 limit " + size + ";";
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
        }
        return null;
    }

    public String getUserMobile(List<User> userList, int userId) {
        if (!Checker.isNone(userList)) {
            User user = userList.stream().filter(p -> p.getId().equals(userId)).findFirst().orElse(null);
            if (!Checker.isNone(user)) {
                return Checker.getStringValue(user.getMobile());
            }
        }
        return "";
    }




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

}
