package com.ywt.alipaympapi.service.impl;

import com.ywt.alipaympapi.core.ConstantDef;
import com.ywt.alipaympapi.core.utils.*;
import com.ywt.alipaympapi.models.enums.*;
import com.ywt.alipaympapi.models.union_reg.HospitalCustomInfo;
import com.ywt.alipaympapi.service.IsvRegisterService;
import com.ywt.alipaympapi.service.services.DoctorSrv;
import com.ywt.alipaympapi.service.services.SystemSrv;
import com.ywt.core.exception.AppMessageException;
import com.ywt.gapi.Result;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.order.*;
import com.ywt.gapi.system.Dept;
import com.ywt.gapi.system.*;
import com.ywt.gapi.taihe.register.*;
import com.ywt.gapi.taihe.register.RegisteredOrder;
import com.ywt.gapi.third.taihe.*;
import com.ywt.gapi.user.*;
import com.ywt.model.PageVO;
import com.ywt.model.Pagination;
import com.ywt.request.queue.QueryQueueListRequest;
import com.ywt.request.register.*;
import com.ywt.request.register.CancelOrderRequest;
import com.ywt.response.queue.QueryQueueListResponse;
import com.ywt.response.register.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCommands;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class IsvRegisterServiceImpl implements IsvRegisterService {

    @Autowired
    private TaiheRegisterServiceGrpc.TaiheRegisterServiceBlockingStub taiheRegisterServiceBlockingStub;
    @Autowired
    private SystemServiceGrpc.SystemServiceBlockingStub systemServiceBlockingStub;
    @Autowired
    private TaiheServiceGrpc.TaiheServiceBlockingStub taiheServiceBlockingStub;
    @Autowired
    private SystemSrv systemSrv;
    @Autowired
    private JedisCommands jedisCommands;
    @Autowired
    private DoctorSrv doctorSrv;
    @Autowired
    private DoctorServiceGrpc.DoctorServiceBlockingStub doctorServiceBlockingStub;
    @Autowired
    private OrderServiceGrpc.OrderServiceBlockingStub orderServiceBlockingStub;

    @Override
    public List<QueryDepartmentListResponseData> queryDepartmentList(QueryDepartmentListRequest request) throws Exception {
        log.info("IsvRegisterServiceImpl#queryDepartmentList--QueryDepartmentListRequest：{}", JsonSerializer.toJson(request));
        int hospitalId = BizUtil.getCurrentHospitalId();
        String hospitalDistrictId = request.getHospitalDistrictId();
        int subHospitalId = 0;
        if (!Checker.isNone(hospitalDistrictId)) {
            subHospitalId = Integer.parseInt(hospitalDistrictId);
        }
        List<HospitalDept> deptList = null;
        HospitalDeptListRequest req = HospitalDeptListRequest.newBuilder()
                .setHospitalId(hospitalId)
                .setSubHospitalId(subHospitalId)
                .build();
        HospitalDeptListResponse res = systemServiceBlockingStub.getHospitalDeptList(req);
        if (res.getResult().getCode() != ResultCode.SUCCEED) {
            throw new AppMessageException(res.getResult().getInfo());
        }
        Result result = res.getResult();
        if (result.getCode() == ResultCode.SUCCEED) {
            deptList = res.getHospitalDeptListList();
        }
        if (deptList == null) {
            throw new AppMessageException("科室不存在");
        }
        String parentId = request.getParentId();
        int deptParentId = 0;
        if (!Checker.isNone(parentId)) {
            deptParentId = Integer.parseInt(parentId);
        }
        List<QueryDepartmentListResponseData> lst = new LinkedList<>();
        for (HospitalDept d : deptList) {
            if (deptParentId == 0) {
                QueryDepartmentListResponseData map = new QueryDepartmentListResponseData();
                map.setDepartmentId(d.getDeptId() + "");
                map.setDepartmentCode(d.getDeptCode());
                map.setName(d.getDeptName());
                map.setHasChildren(d.getDeptListList().size() > 0);
                map.setRemain(0);
                //院区id
                map.setHospitalDistrictId(hospitalDistrictId);
                map.setHospitalId(hospitalId);
                lst.add(map);
            } else {
                if (deptParentId == d.getDeptId()) {
                    for (Dept secDept : d.getDeptListList()) {
                        QueryDepartmentListResponseData map = new QueryDepartmentListResponseData();
                        map.setDepartmentId(secDept.getDeptId() + "");
                        map.setDepartmentCode(secDept.getDeptCode());
                        map.setName(secDept.getDeptName());
                        map.setHasChildren(false);
                        map.setRemain(0);
                        map.setHospitalDistrictId(hospitalDistrictId);
                        map.setHospitalId(hospitalId);
                        lst.add(map);
                    }
                }
            }
        }
        return lst;
    }

    @Override
    public List<QueryDepOrderSourceRemainResponseData> queryDepOrderSourceRemain(QueryDepOrderSourceRemainRequest request) throws Exception {
        int hospitalId = BizUtil.getCurrentHospitalId();
        String deptCode = Checker.getStringValue(request.getDepCode());
        String doctorCode = "";
        String serviceDate = "";
        String serviceCode = "";
        Map<String, Object> dataMap = getScheduleListCommon(hospitalId, deptCode, doctorCode, serviceCode, serviceDate, -1, -1);
        List<QueryDepOrderSourceRemainResponseData> dataList = new ArrayList<>();
        if (!Checker.isNone(dataMap.get("hasSchedulingList"))) {
            dataList = (List<QueryDepOrderSourceRemainResponseData>) dataMap.get("hasSchedulingList");
        }
        return dataList;
    }

    @Override
    public PageVO<QueryDepDoctorListResponseData> queryDepDoctorList(QueryDepDoctorListRequest request) throws Exception {
        int hospitalId = BizUtil.getCurrentHospitalId();
        String deptCode = Checker.getStringValue(request.getDepCode());
        String doctorCode = Checker.getStringValue(request.getDoctorCode());
        String serviceDate = Checker.getStringValue(request.getDate());
        String serviceCode = Checker.getStringValue(request.getServiceCode());
        Map<String, Object> dataMap = getScheduleListCommon(hospitalId, deptCode, doctorCode, serviceCode, serviceDate, -1, -1);
        List<QueryDepDoctorListResponseData> dataList = new ArrayList<>();
        if (!Checker.isNone(dataMap.get("groupByDoctorList"))) {
            dataList = (List<QueryDepDoctorListResponseData>) dataMap.get("groupByDoctorList");
        }
        Pagination pagination = new Pagination(1, dataList.size(), dataList.size());
        PageVO<QueryDepDoctorListResponseData> res = new PageVO<>(pagination, dataList);
        return res;
    }

    /**
     * 原来的获取科室排班列表方法抽离
     *
     * @param startOffset 开始日期 offset, 值取 0 表示当天；
     * @param endOffset   结束日期 offset, 值取 0 表示当天；
     * @param serviceDate 指定时间，具体某一天：yyyy-MM-dd
     *                    <p>
     *                    startOffset 和 endOffset 其中一个为负值时，表示不指定日期范围，默认按照“太和查未来 8 天，不包括当天；白云查未来 6 天，包括当天”的规则查询。
     *                    都不为负值时，按照传入的 offset 计算开始结束日期。
     */
    private Map<String, Object> getScheduleListCommon(int hospitalId, String deptCode, String doctorCode,
                                                      String serviceCode, String serviceDate, int startOffset, int endOffset) throws AppMessageException {
        String redisKeyPattern = "ALI_SCHEDULE_LIST_%s_%s_%d_%s_%s";
        String key = String.format(redisKeyPattern, deptCode, doctorCode, hospitalId, serviceCode, serviceDate);
        if (startOffset >= 0 && endOffset >= 0) {
            redisKeyPattern = "ALI_SCHEDULE_LIST_%s_%s_%d_%s_%s_%d_%d";
            key = String.format(redisKeyPattern, deptCode, doctorCode, hospitalId, serviceCode, serviceDate, startOffset, endOffset);
        }
        String value = jedisCommands.get(key);
        if (!StringHelper.isNullOrWhiteSpace(value)) {
            Map<String, Object> cacheMap = JsonSerializer.from(value, Map.class);
            if (cacheMap != null) {
                return cacheMap;
            }
        }

        List<Dept> deptList = systemSrv.getDeptListByHospitalId(hospitalId);
        if (deptList == null || deptList.size() == 0) {
            throw new AppMessageException(String.format("无法获取科室数据(%d)", hospitalId));
        }
        List<Dept> tmpDeptList = deptList.stream().filter(p -> p.getDeptCode().equals(deptCode)).collect(Collectors.toList());
        if (tmpDeptList.size() == 0) {
            log.error(String.format("deptCode 不存在(%d-%s-%s)", hospitalId, deptCode, doctorCode));
            throw new AppMessageException("暂无出诊信息");
        }
        Dept secDept = tmpDeptList.get(0);
        tmpDeptList = deptList.stream().filter(p -> p.getDeptId() == secDept.getParentId()).collect(Collectors.toList());
        if (tmpDeptList.size() == 0) {
            log.error(String.format("deptCode 不合法(%d-%s-%s)", hospitalId, deptCode, doctorCode));
            throw new AppMessageException("暂无出诊信息");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("hospitalId", hospitalId);
        map.put("hospitalName", BizUtil.getHospitalNameByIdSimply(hospitalId));
        map.put("deptCode", deptCode);
        map.put("deptName", secDept.getDeptName());

        // 批量日期查询 HIS 接口
        boolean isTaihe = hospitalId == ConstantDef.TAIHE_HOSPITAL_ID;
        if (startOffset < 0 || endOffset < 0) {
            startOffset = isTaihe ? 1 : 0;
            endOffset = isTaihe ? 9 : 7;
        }
        Calendar calendar = Calendar.getInstance();
        if (startOffset > 0) {
            calendar.add(Calendar.DATE, startOffset);
        }
        String startDate = DateUtil.formatDate(calendar.getTime(), "yyyy-MM-dd"); //日期
        calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, endOffset);
        String endDate = DateUtil.formatDate(calendar.getTime(), "yyyy-MM-dd"); //日期

        // 如果传了具体的日期，那之查这一天的
        if (!Checker.isNone(serviceDate)) {
            startDate = serviceDate;
            endDate = serviceDate;
        }

        GetScheduleListRequest getScheduleListRequest = GetScheduleListRequest.newBuilder()
                .setDeptCode(deptCode)
                .setDoctorCode(doctorCode)
                .setServiceDate(startDate)
                .setServiceEndDate(endDate)
                .setHospitalId(hospitalId)
                .setServiceCode(serviceCode)
                .build();
        GetScheduleListResponse getScheduleListResponse = taiheServiceBlockingStub.getScheduleList(getScheduleListRequest);
        List<Schedule> scheduleList;
        if (getScheduleListResponse.getCode() == ResultCode.SUCCEED_VALUE) {
            scheduleList = getScheduleListResponse.getSchedulesList();
        } else {
            log.error("NfyyByfyRegisterController#getConvertedScheduleList(): HIS 获取排班接口出错：{}", getScheduleListResponse.getMsg());
            scheduleList = new LinkedList<>();
        }

        List<QueryDepDoctorListResponseData> groupByDoctorList = convertToScheduleListGroupByDoctor(scheduleList, hospitalId);
        map.put("groupByDoctorList", groupByDoctorList);
        List<QueryDepOrderSourceRemainResponseData> hasSchedulingList = checkHasSchedulingGroupByDate(scheduleList, startOffset, endOffset);
        map.put("hasSchedulingList", hasSchedulingList);
        jedisCommands.set(key, JsonSerializer.toJson(map));
        jedisCommands.expire(key, 3 * 60);
        return map;
    }

    /**
     * 排班记录转为List(按医生分组)
     */
    private List<QueryDepDoctorListResponseData> convertToScheduleListGroupByDoctor(List<Schedule> scheduleList, int hospitalId) {
        Map<Integer, QueryDepDoctorListResponseData> doctorSet = new HashMap<>();

        GetDoctorByHisCodeResponse getDoctorByHisCodeResponse;
        String avatar;

        int doctorId;
        for (Schedule s : scheduleList) {
            doctorId = 0;
            avatar = ConstantDef.DOCTOR_AVATAR_URL;
            getDoctorByHisCodeResponse = getDoctorByHisCode(s.getDoctorCode(), hospitalId);

            if (getDoctorByHisCodeResponse.getResult().getCode() == ResultCode.SUCCEED) {
                if (!StringHelper.isNullOrWhiteSpace(getDoctorByHisCodeResponse.getAvatar())) {
                    avatar = getDoctorByHisCodeResponse.getAvatar();
                }

                doctorId = getDoctorByHisCodeResponse.getDoctorId();
            }
            if (doctorId <= 0) {
                continue;
            }

            if (s.getScheduleStatus() != 1) {
                continue;
            }
            QueryDepDoctorListResponseData item = doctorSet.get(doctorId);
            if (Checker.isNone(item)) {
                item = new QueryDepDoctorListResponseData();
                item.setDoctorId(doctorId + "");
                item.setHospitalId(hospitalId);
                item.setName(s.getDoctorName());
                item.setDesc(s.getDoctorSpec());
                item.setPicUrl(avatar);
                // 这个数后面再统计
                item.setRemain(0);
                // 目前系统里面并没有专家号和普通号的区分，目前统一用普通号
                item.setType("normal");
                item.setLevel(s.getDoctorTitle());
                item.setDoctorCode(s.getDoctorCode());
                item.setDeptCode(s.getDeptCode());
                item.setDistrictName(HospitalNameEnum.getDisplayName(hospitalId));
            }
            List<OrderSource> orderSourceList = item.getOrderSources();
            if (Checker.isNone(orderSourceList)) {
                orderSourceList = new ArrayList<>();
            }
            OrderSource os = new OrderSource();
            //号源id
            os.setOrderSourceId(s.getScheduleItemCode());
            //号源开始时间段
            os.setStartTime("");
            //号源截止时间段
            os.setEndTime("");
            //挂号费用
            os.setCost(String.format("%.2f", s.getFee() / 100d));
//            os.setCost(BizUtil.cent2Yuan(s.getFee()) + "");
            //剩余数量
            os.setRemain(Checker.getIntegerValue(s.getAvailableLeftNum()));
            //true：确认挂号时支付，false：就诊时支付
            os.setOnlinePay(true);
            os.setDatePeriod(s.getDatePeriod());
            os.setDatePeriodName(s.getDatePeriodName());
            os.setServiceDate(s.getServiceDate());
            orderSourceList.add(os);
            item.setOrderSources(orderSourceList);

            doctorSet.put(doctorId, item);
        }
        List<QueryDepDoctorListResponseData> dataList = new ArrayList<>();
        Set<Integer> doctorIdSet = doctorSet.keySet();
        for (Integer doctorIdInt : doctorIdSet) {
            QueryDepDoctorListResponseData data = doctorSet.get(doctorIdInt);
            List<OrderSource> sourceList = data.getOrderSources();
            if (!Checker.isNone(sourceList)) {
                int remain = sourceList.stream().mapToInt(OrderSource::getRemain).sum();
                data.setRemain(remain);
            }
            dataList.add(data);
        }
        // 过滤掉没有号的医生数据
        dataList = dataList.stream().filter(p -> p.getRemain() > 0).collect(Collectors.toList());
        return dataList;
    }

    /**
     * 排班记录转为List(按日期判断是否有医生排班)
     */
    private List<QueryDepOrderSourceRemainResponseData> checkHasSchedulingGroupByDate(List<Schedule> scheduleList, int startOffset, int endOffset) {
        List<QueryDepOrderSourceRemainResponseData> remainResponseList = new ArrayList<>();
        if (endOffset > startOffset && !Checker.isNone(scheduleList)) {
            for (int offset = startOffset; offset < endOffset; offset++) {
                Calendar c = Calendar.getInstance();
                if (offset > 0) {
                    c.add(Calendar.DATE, offset);
                }
                String strDate = DateUtil.formatDate(c.getTime(), "yyyy-MM-dd"); //日期
                List<Schedule> itemScheduleList = scheduleList.stream().filter(s -> strDate.equals(s.getServiceDate())).collect(Collectors.toList());
                QueryDepOrderSourceRemainResponseData data = new QueryDepOrderSourceRemainResponseData();
                int remain = 0;    //当期日期是否有排班
                if (!Checker.isNone(itemScheduleList)) {
                    remain = itemScheduleList.stream().mapToInt(Schedule::getAvailableLeftNum).sum();
                }
                data.setDate(strDate);
                data.setRemain(remain);
                remainResponseList.add(data);
            }
        }
        return remainResponseList;
    }

    private GetDoctorByHisCodeResponse getDoctorByHisCode(String doctorCode, int hospitalId) {
        GetDoctorByHisCodeRequest getDoctorByHisCodeRequest = GetDoctorByHisCodeRequest.newBuilder()
                .setHospitalId(hospitalId)
                .setHisCode(doctorCode)
                .build();
        return doctorServiceBlockingStub.getDoctorByHisCode(getDoctorByHisCodeRequest);
    }

    @Override
    public List<QueryDoctorOrderSourceListResponseData> queryDoctorOrderSourceList(QueryDoctorOrderSourceListRequest request) throws Exception {

        return null;
    }

    // 挂号确认
    @Override
    public OrderConfirmResponseData orderConfirm(OrderConfirmRequest request) throws Exception {
        log.info("IsvRegisterServiceImpl#orderConfirm--OrderConfirmRequest：{}", JsonSerializer.toJson(request));
        int userId = ContextHelper.getCurrentUserIdWrapped();
        int hospitalId = BizUtil.getCurrentHospitalId();
        String deptCode = Checker.getStringValue(request.getDeptCode());
        String deptName = Checker.getStringValue(request.getDeptName());
        String doctorCode = Checker.getStringValue(request.getDoctorCode());
        String doctorName = Checker.getStringValue(request.getDoctorName());
        double registeredFee = request.getRegisteredFee();
        double medicalFee = request.getMedicalFee();
        String registeredDate = Checker.getStringValue(request.getRegisteredDate());
        int period = request.getPeriod();
        String startTime = Checker.getStringValue(request.getStartTime());
        String endTime = Checker.getStringValue(request.getEndTime());
        int medicalCardId = request.getMedicalCardId();
        String scheduleItemCode = Checker.getStringValue(request.getScheduleItemCode());
        int deptId = request.getDeptId();
        String lockQueueNo = Checker.getStringValue(request.getLockQueueNo());
        String availableNumStr = Checker.getStringValue(request.getAvailableNumStr());

        if (hospitalId < 1) {
            throw new AppMessageException("医院不存在");
        }
        if (StringHelper.isNullOrWhiteSpace(deptCode) || StringHelper.isNullOrWhiteSpace(deptName)) {
            throw new AppMessageException("科室不存在");
        }
        if (StringHelper.isNullOrWhiteSpace(doctorCode) || StringHelper.isNullOrWhiteSpace(doctorName)) {
            throw new AppMessageException("医生不存在");
        }
        if (StringHelper.isNullOrWhiteSpace(registeredDate)) {
            throw new AppMessageException("请选择挂号日期");
        }

        Date date = DateUtil.parseDate(registeredDate, "yyyy-MM-dd");
        if (date == null) {
            throw new AppMessageException("预约日期格式不正确");
        }
        DatePeriodEnum datePeriodEnum = DatePeriodEnum.valueOf(period);
        if (datePeriodEnum == null) {
            throw new AppMessageException("预约时段不存在");
        }
        if (StringHelper.isNullOrWhiteSpace(startTime)) {
            throw new AppMessageException("预约开始时间不存在");
        }
        if (StringHelper.isNullOrWhiteSpace(endTime)) {
            throw new AppMessageException("预约结束时间不存在");
        }
        if (medicalCardId < 1) {
            throw new AppMessageException("请选择就诊人");
        }
        if (StringHelper.isNullOrWhiteSpace(scheduleItemCode)) {
            throw new AppMessageException("门诊排班项记录标识不能为空");
        }
        if (userId == 0) {
            throw new AppMessageException("请先登录");
        }

        int registeredFeeInt = (int) (registeredFee * 100);
        int medicalFeeInt = (int) (medicalFee * 100);
        int total = (int) ((registeredFee + medicalFee) * 100);
        int paymentChannel = total > 0
                ? PaymentChannelEnum.ALI_PAY.getValue()
                : PaymentChannelEnum.FREE.getValue();
        int source;
        int terminal = BizUtil.getCurrentTerminalWrapped();
        switch (TerminalEnum.valueOf(terminal)) {
            case TAI_HE_OFFICIAL:
                source = TerminalEnum.TAI_HE_OFFICIAL.getValue();
                break;
            case NFYYBYFY_WXAPP:
                source = TerminalEnum.NFYYBYFY_WXAPP.getValue();
                break;
            case NFYYBYFY_ALIPAY_MP:
                source = TerminalEnum.NFYYBYFY_ALIPAY_MP.getValue();
                break;
            default:
                source = TerminalEnum.TaiheWxOfficial.getValue();
                break;
        }

        CreateRegisteredRequest req = CreateRegisteredRequest.newBuilder()
                .setDeptCode(deptCode)
                .setDeptName(deptName)
                .setDoctorCode(doctorCode)
                .setDoctorName(doctorName)
                .setTotal(total)
                .setRegisteredFee(registeredFeeInt)
                .setMedicalFee(medicalFeeInt)
                .setRegisteredDate(date.getTime())
                .setStartTime(startTime)
                .setEndTime(endTime)
                .setUserId(userId)
                .setMedicalCardId(medicalCardId)
                .setScheduleItemCode(scheduleItemCode)
                .setPaymentChannel(paymentChannel)
                .setSource(source)
                .setPeriod(period)
                .setDoctorTitle("")
                .setDeptId(Checker.getIntegerValue(deptId))
                .setLockQueueNo(lockQueueNo)
                .setAvailableNumStr(availableNumStr)
                .setHospitalId(hospitalId)
                .build();
        CreateRegisteredResponse res = taiheRegisterServiceBlockingStub.createRegistered(req);
        if (res.getCode() != ResultCode.SUCCEED_VALUE) {
            //预约失败
            throw new AppMessageException(res.getMsg());
        }
        if (!systemSrv.checkIsNetDept(deptCode, hospitalId)) {
            //非互联网医院名医诊区挂号
            OrderConfirmResponseData responseData = new OrderConfirmResponseData();
            responseData.setOrderId(res.getOrderId() + "");
            responseData.setOrderType(res.getOrderType());
            responseData.setAmount(String.format("%.2f", (registeredFee + medicalFee)));
            responseData.setStatus(res.getStatus());
            return responseData;
        }
        return null;
    }

    // 预约单详情
    @Override
    public QueryOrderDetailResponseData queryOrderDetail(QueryOrderDetailRequest request) throws Exception {
        if (Checker.isNone(request.getOrderId())) {
            throw new AppMessageException("没有挂号详情");
        }
        int orderId = Integer.parseInt(request.getOrderId());
        int userId = ContextHelper.getCurrentUserIdWrapped();
        int pageIndex = 1;
        int pageSize = 1;
        GetRegisteredOrderListRequest req = GetRegisteredOrderListRequest.newBuilder()
                .setPageIndex(pageIndex)
                .setPageSize(pageSize)
                .setUserId(userId)
                .setOrderId(orderId)
                .build();
        GetRegisteredOrderListResponse res = orderServiceBlockingStub.getRegisteredOrderList(req);
        if (res.getResult().getCode() == ResultCode.SUCCEED) {
            if (!Checker.isNone(res.getOrdersList())) {
                com.ywt.gapi.order.RegisteredOrder item = res.getOrdersList().get(0);

                String deptCode = item.getDeptCode();
                double amount = item.getTotal() / 100d;
                QueryOrderDetailResponseData data = new QueryOrderDetailResponseData();
                data.setOrderId(Integer.toString(orderId));
                data.setOrderNo(item.getOrderNo());
                data.setUserName(item.getPatientName());
                data.setDoctorName(item.getDoctorName());
                data.setDepName(item.getDeptName());
                data.setDeptCode(item.getDeptCode());
                data.setDistrictName(item.getHospitalName());
                data.setHisPatientId(item.getHisPatientId());
                String amountStr = String.format("%.2f", amount);
                data.setAmount(amountStr);
                data.setTimeRange(item.getStartTime() + "~" + item.getEndTime());
                data.setQrCode("");
                // 预约单状态 (0-待支付, 1-预约成功, 2-叫号中,7-已就诊,8-预期未就诊,9-取消预约)
                int orderStatus = item.getRegisteredStatus();
                String statusName = "";
                if ((item.getRegisteredStatus() & RegisteredStatusEnum.Cancel.getValue()) == RegisteredStatusEnum.Cancel.getValue()
                ) {
                    statusName = "取消预约";
                    orderStatus = 9;
                } else if (item.getRegisteredStatus() == RegisteredStatusEnum.Refunded.getValue()) {
                    statusName = "已退款";
                    orderStatus = 9;
                } else if (item.getPaymentStatus() == PaymentStatusEnum.Pending.getValue()) {
                    statusName = "待支付";
                    orderStatus = 0;
                } else if (item.getPaymentStatus() == PaymentStatusEnum.Success.getValue()) {
                    GetCommonOrderListRequest reqTwo = GetCommonOrderListRequest.newBuilder()
                            .setPageIndex(1)
                            .setPageSize(999)
                            .setUserId(userId)
                            .build();
                    GetCommonOrderListResponse resTwo = taiheRegisterServiceBlockingStub.getCommonOrderList(reqTwo);
                    if (resTwo.getCode() == ResultCode.SUCCEED_VALUE) {
                        for (CommonOrder itemTwo : resTwo.getOrderList()) {
                            if (orderId == itemTwo.getOrderId()) {
                                statusName = itemTwo.getStatusName();
                                orderStatus = getStatus(itemTwo.getStatusName());
                            }
                        }
                    }
                }
                data.setStatus(orderStatus);
                data.setStatusStr(statusName);
                data.setSystemTime(DateUtil.convertTimestampToDateString(item.getCreateTime()));
                data.setCreateTime(DateUtil.convertTimestampToDateString(item.getCreateTime()));
                data.setCancelTime("");
                data.setLevel("");
                data.setPayType("");
                data.setAge("");
                data.setExpireTime("");
                data.setQueueNum("");
                data.setSex(SexEnum.getSexDisplayName(Checker.getIntegerValue(item.getSex())));
                data.setStartTime(Checker.getStringValue(item.getStartTime()));
                data.setEndTime(Checker.getStringValue(item.getEndTime()));
                data.setRegisteredDate(DateUtil.convertTimestampToDateString(item.getRegisteredDate(), "yyyy-MM-dd"));
                data.setCardNum(Checker.getStringValue(item.getMedicalCardNo()));
                return data;
            }
        }
        throw new AppMessageException("没有挂号详情");
    }

    @Override
    public PageVO<QueryOrderListResponseData> queryOrderList(QueryOrderListRequest request) throws Exception {
        if (request.getPageIndex() < 1) {
            throw new AppMessageException("页码错误");

        }
        if (request.getPageSize() < 1) {
            throw new AppMessageException("页大小错误");
        }
        List<QueryOrderListResponseData> list = new ArrayList<>();
        int total = 0;
        int userId = ContextHelper.getCurrentUserIdWrapped();
        GetCommonOrderListRequest req = GetCommonOrderListRequest.newBuilder()
                .setPageIndex(request.getPageIndex())
                .setPageSize(request.getPageSize())
                .setUserId(userId)
                .build();
        GetCommonOrderListResponse res = taiheRegisterServiceBlockingStub.getCommonOrderList(req);
        if (res.getCode() == ResultCode.SUCCEED_VALUE) {
            total = res.getOrderList().size();
            for (CommonOrder item : res.getOrderList()) {
                String deptCode = item.getDeptCode();
                double amount = item.getAmount() / 100d;
                QueryOrderListResponseData data = new QueryOrderListResponseData();
                int orderId = Checker.getIntegerValue(item.getOrderId());
                data.setOrderId(Integer.toString(orderId));
                data.setOrderNo(item.getOrderNo());
                data.setUserName(item.getPatientName());
                data.setDoctorName(item.getDoctorName());
                data.setDepName(item.getDeptName());
                data.setDeptCode(item.getDeptCode());
                data.setDistrictName(item.getHospitalName());
                data.setTimeRange(item.getStartTime() + "~" + item.getEndTime());
                String amountStr = String.format("%.2f", amount);
                data.setAmount(amountStr);
                data.setStatus(getStatus(item.getStatusName()));
                data.setCreateTime(Checker.getStringValue(item.getStartTime()));
                data.setEndTime(Checker.getStringValue(item.getEndTime()));
                data.setRegisteredDate(item.getRegisteredDate());
                list.add(data);
            }
        }
        Pagination pagination = new Pagination(request.getPageIndex(), request.getPageSize(), total);
        PageVO<QueryOrderListResponseData> resp = new PageVO<>(pagination, list);
        return resp;
    }

    @Override
    public CancelOrderResponseData cancelOrder(CancelOrderRequest request) throws Exception {
        CancelOrderResponseData responseData = new CancelOrderResponseData();
        String orderIdStr = request.getOrderId();
        if (Checker.isNone(orderIdStr) || Integer.parseInt(orderIdStr) <= 0) {
            throw new AppMessageException("订单不存在");
        }
        int orderId = Integer.parseInt(orderIdStr);
        int userId = ContextHelper.getCurrentUserIdWrapped();
        int hospitalId = BizUtil.getCurrentHospitalId();
        CancelRegisteredRequest req = CancelRegisteredRequest.newBuilder()
                .setOrderId(orderId)
                .setUserId(userId)
                .setHospitalId(hospitalId)
                .build();
        CancelRegisteredResponse res = taiheRegisterServiceBlockingStub.cancelRegistered(req);
        responseData.setIsSuccess(false);
        if (res.getCode() == ResultCode.SUCCEED_VALUE) {
            responseData.setIsSuccess(true);
        }
        return responseData;
    }

    @Override
    public List<QueryHospitalDistrictListResponseData> queryHospitalDistrictList(QueryHospitalDistrictListRequest
                                                                                         request) throws Exception {
        int hospitalId = BizUtil.getCurrentHospitalId();
        List<Integer> hospitalIds = new ArrayList<>();
        hospitalIds.add(hospitalId);
        GetHospitalByHospitalIdsRequest req = GetHospitalByHospitalIdsRequest.newBuilder()
                .addAllHospitalId(hospitalIds)
                .build();
        GetHospitalByHospitalIdsResponse res = systemServiceBlockingStub.getHospitalByHospitalIds(req);
        if (res.getCode() != ResultCode.SUCCEED.getNumber()) {
            throw new AppMessageException(res.getMessage());
        }
        List<Map<String, Object>> list = new LinkedList<>();
        List<Hospital> hospitalList = res.getHospitalList();
        List<Hospital> subHospList = hospitalList.stream().filter(h -> Checker.getIntegerValue(h.getParentId()) > 0).collect(Collectors.toList());
        Set<Integer> parentHospitalIds = subHospList.stream().map(h -> Checker.getIntegerValue(h.getParentId())).collect(Collectors.toSet());
        List<Hospital> filteredParentHospitalList = hospitalList.stream().filter(h -> Checker.getIntegerValue(h.getParentId()) == 0 && !parentHospitalIds.contains(h.getHospitalId())).collect(Collectors.toList());

        List<QueryHospitalDistrictListResponseData> responseDataList = new ArrayList<>();
        for (Hospital h : subHospList) {
            QueryHospitalDistrictListResponseData item = new QueryHospitalDistrictListResponseData();
            item.setHospitalDistrictId(h.getHospitalId() + "");
            item.setName(h.getHospitalName());
            item.setAddress(h.getAddress());
            item.setDescription("");
            Map<String, String> map = new HashMap<>();
            map.put("hospitalId", h.getParentId() + "");
            map.put("subHospitalId", h.getHospitalId() + "");
            map.put("hospitalLogo", h.getLogo());
            HospitalCustomInfo p = BizUtil.getHospitalCustomInfo(h.getHospitalId());
            if (p != null) {
                map.put("alias", p.getAlias());
                map.put("areaName", p.getAreaName());
            }
            item.setExtInfo(map);
            responseDataList.add(item);
        }
        for (Hospital h : filteredParentHospitalList) {
            QueryHospitalDistrictListResponseData item = new QueryHospitalDistrictListResponseData();
            item.setHospitalDistrictId(h.getHospitalId() + "");
            item.setName(h.getHospitalName());
            item.setAddress(h.getAddress());
            item.setDescription("");
            Map<String, String> map = new HashMap<>();
            map.put("hospitalId", h.getHospitalId() + "");
            map.put("subHospitalId", "0");
            map.put("hospitalLogo", h.getLogo());
            HospitalCustomInfo p = BizUtil.getHospitalCustomInfo(h.getHospitalId());
            if (p != null) {
                map.put("alias", p.getAlias());
                map.put("areaName", p.getAreaName());
            }
            item.setExtInfo(map);
            responseDataList.add(item);
        }
        return responseDataList;
    }

    @Override
    public List<QueryQueueListResponse> queryQueueList(QueryQueueListRequest request) throws Exception {
        log.info("IsvRegisterServiceImpl#queryQueueList--QueryQueueListRequest：{}", JsonSerializer.toJson(request));
        int hospitalId = BizUtil.getCurrentHospitalId();
        //用户唯一识别号
        int userId = ContextHelper.getCurrentUserIdWrapped();

        List<QueryQueueListResponse> list = new LinkedList<>();

        com.ywt.gapi.taihe.register.GetQueueListRequest req = com.ywt.gapi.taihe.register.GetQueueListRequest.newBuilder()
                .setUserId(userId)
                .setHospitalId(hospitalId)
                .build();
        com.ywt.gapi.taihe.register.GetQueueListResponse res = taiheRegisterServiceBlockingStub.getQueueList(req);

        if (res.getCode() != ResultCode.SUCCEED_VALUE) {
            throw new AppMessageException(res.getMsg());
        }

        List<com.ywt.gapi.taihe.register.RegisteredOrder> queueList = res.getOrderList();

        LocalDate now = LocalDate.now();
        for (com.ywt.gapi.taihe.register.RegisteredOrder order : queueList) {
            QueryQueueListResponse reportItem = new QueryQueueListResponse();
            int cancel = 0; //是否显示退号按钮，1-是，0-否
            LocalDate regDate = DateUtil.convertToLocalDate(new Date(order.getRegisteredDate()));//预约日期
            if (now.isBefore(regDate)) {
                cancel = 1;
            }
            String statusName = order.getStatusName();
            int status = order.getStatus();

            if (order.getStatus() == 1) {
                //已预约
                statusName = "未取号";

                if (DateUtil.convertTimestampToDateString(order.getRegisteredDate(), "yyyy-MM-dd").equals(
                        DateUtil.formatDate(new Date(), "yyyy-MM-dd"))) {

                } else {
                    status = 0;
                }
            }
            reportItem.setCardNum(order.getMedicalCardId() + "");//就诊卡卡号
            reportItem.setName(order.getPatientName());//就诊人姓名
            reportItem.setSex(SexEnum.getSexDisplayName(order.getSex()));//性别
            reportItem.setAge("");//年龄
            reportItem.setTitle(statusName);//排队标题
            reportItem.setDepName(order.getDeptName());//科室
            reportItem.setDoctorName(order.getDoctorName());//医生姓名
            reportItem.setDoctorDesc("");//医生描述
            reportItem.setAddress(order.getAddress());//就诊地点

            int queueNum = 0, leftOver = 0;
            GetQueueInfoRequest getQueueInfoRequest = GetQueueInfoRequest.newBuilder()
                    .setRegistrationId(order.getHisSeqCode())
                    .setHospitalId(hospitalId)
                    .build();
            GetQueueInfoResponse getQueueInfoResponse = taiheServiceBlockingStub.getQueueInfo(getQueueInfoRequest);
            if (getQueueInfoResponse.getCode() == ResultCode.SUCCEED_VALUE) {
                QueueInfo data = getQueueInfoResponse.getQueueInfo();
                queueNum = data.getWaitingNumber();
            }
            reportItem.setQueueNum(queueNum + "");//排队编号
            reportItem.setLeftover("0");//前面排队剩余人数
            reportItem.setStatus(statusName);//状态,expired：已过号，queuing：排队中，ringing：叫号中，completed：已完成
            reportItem.setContext(order.getRemark());//排队结束显示内容
            list.add(reportItem);
        }
        return list;
    }

    @Override
    public QueryDoctorInfoResponseData queryDoctorInfo(QueryDoctorInfoRequest request) throws Exception {
        int doctorId = Integer.parseInt(Checker.getStringValue(request.getDoctorId(), "0"));
        int hospitalId = BizUtil.getCurrentHospitalId();
        if (doctorId < 1) {
            throw new AppMessageException("invalid doctorId");
        }
        QueryDoctorInfoResponseData responseData = new QueryDoctorInfoResponseData();

        GetDoctorRequest req = GetDoctorRequest.newBuilder().setDoctorId(doctorId).build();
        GetDoctorResponse resp = doctorServiceBlockingStub.getDoctor(req);
        Result result = resp.getResult();

        if (result.getCode() != ResultCode.SUCCEED) {
            throw new AppMessageException(result.getInfo());
        }
        DoctorInfo info = resp.getDoctorInfo();
        responseData.setDoctorId(info.getDoctorid() + "");//医生id
        responseData.setName(info.getName());//医生姓名
        responseData.setLevel(info.getTitle());//医生职级
        responseData.setPicUrl(info.getAvatar());//医生头像地址
        responseData.setDescription(info.getBriefIntro());//医生简介
        responseData.setSpecialty(info.getSpecialty());//擅长领域
        responseData.setDistrictName(systemSrv.getHospitalNameById(hospitalId));//院区名称

        List<Department> departmentList = new ArrayList<>();
        Department department = new Department();
        department.setName(info.getDept());
        department.setDepartmentId(info.getDeptIds());
        departmentList.add(department);
        responseData.setDepartments(departmentList);
        return responseData;
    }


    @Override
    public PageVO<QueryDoctorListResponseData> queryDoctorList(QueryDoctorListRequest request) throws Exception {
        log.info("IsvRegisterServiceImpl#queryDoctorList--QueryDoctorListRequest：{}", JsonSerializer.toJson(request));
        int pageIndex = request.getPageIndex();
        int pageSize = request.getPageSize();
        String deptCode = request.getDeptCode();
        String doctorName = request.getDoctorName();
        int hospitalId = BizUtil.getCurrentHospitalId();
        GetDoctorListRequest getDoctorListRequest = GetDoctorListRequest.newBuilder()
                .setDeptCode(deptCode)
                .setDoctorName(doctorName)
                .setHospitalId(hospitalId)
                .build();
        GetDoctorListResponse getDoctorListResponse = taiheServiceBlockingStub.getDoctorList(getDoctorListRequest);
        int total = 0;
        List<QueryDoctorListResponseData> doctorList = new LinkedList<>();
        if (getDoctorListResponse.getCode() == ResultCode.SUCCEED_VALUE) {
            List<com.ywt.gapi.third.taihe.Doctor> doctorsList = getDoctorListResponse.getDoctorsList();

            total = doctorsList.size();
            for (com.ywt.gapi.third.taihe.Doctor doctor : doctorsList) {

                QueryDoctorListResponseData doctorItem = new QueryDoctorListResponseData();
                //医生id
                doctorItem.setDoctorId(doctor.getDoctorCode());
                //医生姓名
                doctorItem.setName(doctor.getDoctorName());
                //医生简介
                doctorItem.setDesc(doctor.getDoctorIntro());
                //医生头像地址
                doctorItem.setPicUrl("");
                //职级，医生职级
                doctorItem.setLevel(doctor.getDoctorTitle());
                //医生所在科室
                Department department = new Department();
                department.setDepartmentId(doctor.getDoctorDeptCode());
                department.setName(doctor.getDoctorDept());
                List<Department> deptList = new ArrayList();
                deptList.add(department);
                doctorItem.setDepartments(deptList);

                doctorList.add(doctorItem);
            }
        }
        Pagination pagination = new Pagination(pageIndex, pageSize, total);
        PageVO<QueryDoctorListResponseData> res = new PageVO<>(pagination, doctorList);
        return res;
    }


    private int getStatus(String statusName) {
        if ("已完成".equals(statusName)) {
            return 1;
        }
        if ("待支付".equals(statusName)) {
            return 0;
        }
        if ("已取消".equals(statusName)) {
            return 9;
        }
        if ("待就诊".equals(statusName)) {
            return 2;
        }
        if ("已退款".equals(statusName)) {
            return 11;
        }
        return 0;
    }
}
