package com.ywt.outpatient.controllers.taihe;

import com.ywt.biz.common.enums.PaymentChannelEnum;
import com.ywt.biz.common.enums.TerminalEnum;
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.Result;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.ResultInt;
import com.ywt.gapi.nfyy.*;
import com.ywt.gapi.nfyy.Doctor;
import com.ywt.gapi.order.*;
import com.ywt.gapi.user.UserService;
import com.ywt.outpatient.core.BaseResponse;
import com.ywt.outpatient.core.annotations.UserLogin;
import com.ywt.outpatient.core.Constant;
import com.ywt.outpatient.domain.models.enums.DatePeriodEnum;
import com.ywt.outpatient.service.web.taihe.TaiheSystemService;
import com.ywt.outpatient.service.web.taihe.TaiheUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 针对南方医院的加号预约
 */
@RestController("/taihe/nfyy/add/register")
@RequestMapping({"/taihe/nfyy/add/register"})
public class NfyyAddRegisterController {
    private static Logger logger = LoggerFactory.getLogger(NfyyAddRegisterController.class);

    @DubboReference
    private NfyyService nfyyServiceBlockingStub;

    @DubboReference
    private OrderService orderServiceBlockingStub;

    @DubboReference
    private UserService userServiceBlockingStub;

    @Autowired
    private TaiheSystemService systemService;

    @Autowired
    private TaiheUserService userService;

    /**
     * 日期列表
     *
     * @return
     */
    @UserLogin(need = false)
    @RequestMapping({"/datelist"})
    public @ResponseBody
    BaseResponse getDateList() {
        BaseResponse response = new BaseResponse();
        List<Map<String, Object>> lst = new LinkedList<>();
        Calendar calendar = Calendar.getInstance();

        for (int offset = 0; offset < 8; offset++) {
            if (offset > 0) {
                calendar.add(Calendar.DATE, 1);
            }

            Date date = calendar.getTime();
            Map<String, Object> map = new HashMap<>();

            map.put("offset", offset);
            map.put("date", DateUtil.formatDate(date, "yyyy-MM-dd"));
            map.put("strDate", DateUtil.formatDate(date, "yyyy年MM月dd日"));
            map.put("week", DateUtil.getDayOfWeek(calendar));

            lst.add(map);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("list", lst);

        return response.succeed("处理成功", data);
    }

    /**
     * 医生列表
     *
     * @param hospitalId
     * @param deptCode
     * @param doctorName
     * @return
     */
    @UserLogin(need = false)
    @RequestMapping({"/doctorlist"})
    public @ResponseBody
    BaseResponse getDoctorList(@RequestParam(name = "hospitalId") int hospitalId,
                               @RequestParam(name = "deptCode", required = false) String deptCode,
                               @RequestParam(name = "doctorName", required = false) String doctorName) {
        BaseResponse response = new BaseResponse();

        if (hospitalId != 1) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "医院不存在");
        }

        if (StringHelper.isNullOrWhiteSpace(deptCode)) {
            deptCode = "";
        }

        if (StringHelper.isNullOrWhiteSpace(doctorName)) {
            doctorName = "";
        }

        try {
            GetDoctorListRequest getDoctorListRequest = GetDoctorListRequest.newBuilder()
                    .setDepartmentCode(deptCode)
                    .setDoctorName(doctorName)
                    .setType(2)
                    .build();
            GetDoctorListResponse getDoctorListResponse = nfyyServiceBlockingStub.getDoctorList(getDoctorListRequest);

            if (getDoctorListResponse.getCode() == ResultCode.SUCCEED_VALUE) {
                Map<String, String> deptMap = systemService.getDeptMap(hospitalId);
                List<Map<String, Object>> groupList = new LinkedList<>();
                List<DoctorGroup> groups = getDoctorListResponse.getDoctorGroupList();

                for (DoctorGroup group : groups) {
                    List<Map<String, Object>> doctorList = new LinkedList<>();

                    for (Doctor doctor : group.getDoctorsList()) {
                        String departmentName = deptMap.get(doctor.getDepartmentCode());

                        if (!StringHelper.isNullOrWhiteSpace(departmentName)) {
                            Map<String, Object> doctorMap = new LinkedHashMap<>();
                            doctorMap.put("doctorCode", doctor.getDoctorCode());
                            doctorMap.put("doctorName", doctor.getDoctorName());
//                            doctorMap.put("doctorTitle", doctor.getDoctorTitle());
//                            doctorMap.put("doctorBriefIntro", doctor.getDoctorBriefIntro());
//                            doctorMap.put("doctorSpec", doctor.getDoctorSpec());
//                            doctorMap.put("avatar", doctor.getImageUrl());
                            doctorMap.put("deptCode", doctor.getDepartmentCode());
                            doctorMap.put("deptName", departmentName);
                            doctorMap.put("firstLetter", doctor.getFirstLetter());
                            doctorMap.put("letters", doctor.getLetters());

                            doctorList.add(doctorMap);
                        }
                    }

                    Map<String, Object> groupMap = new HashMap<>();
                    groupMap.put("letter", group.getLetter());
                    groupMap.put("doctors", doctorList);

                    groupList.add(groupMap);
                }

                Map<String, Object> map = new LinkedHashMap<>();
                map.put("hospitalId", hospitalId);
                map.put("count", getDoctorListResponse.getTotal());
                map.put("list", groupList);

                return response.succeed("处理成功", map);
            }

            return response.failed(BaseResponse.APP_ERROR, getDoctorListResponse.getMsg());
        } catch (Exception e) {
            logger.error("getDoctorList():{}", e.getMessage());
            return response.failed(BaseResponse.APP_EXCEPTION, Constant.ERROR_PROMPT);
        }
    }

    @UserLogin(need = false)
    @RequestMapping({"/schedule"})
    public @ResponseBody
    BaseResponse getScheduleList(@RequestParam(name = "hospitalId") int hospitalId,
                                 @RequestParam(name = "deptCode") String deptCode,
                                 @RequestParam(name = "doctorCode", required = false) String doctorCode,
                                 @RequestParam(name = "serviceDate", required = false) String serviceDate) {
        BaseResponse response = new BaseResponse();

        if (hospitalId != 1) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "医院不存在");
        }

        if (StringHelper.isNullOrWhiteSpace(deptCode)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "科室不存在");
        }

        if (StringHelper.isNullOrWhiteSpace(doctorCode)) {
            doctorCode = "";
        }

        try {
            List<Map<String, Object>> lst = new LinkedList<>();
            Calendar calendar = Calendar.getInstance();
            Calendar currentCalendar = Calendar.getInstance();
            String strCurrentDate = DateUtil.formatDate(currentCalendar.getTime(), "yyyy-MM-dd");

            for (int offset = 0; offset < 8; offset++) {
                if (offset > 0) {
                    calendar.add(Calendar.DATE, 1);
                }

                String strDate = DateUtil.formatDate(calendar.getTime(), "yyyy-MM-dd"); //日期

                Map<String, Object> groupMap = new HashMap<>();
                groupMap.put("serviceDate", strDate);
                groupMap.put("offset", offset);
                groupMap.put("week", DateUtil.getDayOfWeekShort(calendar));

                GetScheduleListRequest getScheduleListRequest = GetScheduleListRequest.newBuilder()
                        .setDepartmentCode(deptCode)
                        .setEndDate(strDate)
                        .setStartDate(strDate)
                        .setDoctorCode(doctorCode)
                        .setRBASSessionCode("")
                        .setType(2)
                        .build();
                GetScheduleListResponse getScheduleListResponse = nfyyServiceBlockingStub.getScheduleList(getScheduleListRequest);

                if (getScheduleListResponse.getCode() == ResultCode.SUCCEED_VALUE) {
                    List<Schedule> scheduleList = getScheduleListResponse.getSchedulesList();
                    boolean hasScheduling = scheduleList.size() > 0;    //当期日期是否有排班

                    List<Map<String, Object>> forenoonList = new LinkedList<>();
                    List<Map<String, Object>> afternoonList = new LinkedList<>();
                    List<Map<String, Object>> nightList = new LinkedList<>();

                    for (Schedule s : scheduleList) {
                        Map<String, Object> scheduleMap = new HashMap<>();
                        scheduleMap.put("scheduleItemCode", s.getScheduleItemCode());
                        scheduleMap.put("serviceDate", s.getServiceDate());
//                        scheduleMap.put("weekDay", s.getWeekDay());
                        scheduleMap.put("sessionCode", s.getSessionCode());
                        scheduleMap.put("sessionName", s.getSessionName());
                        scheduleMap.put("deptCode", s.getDepartmentCode());
                        scheduleMap.put("deptName", s.getDepartmentName());
//                        scheduleMap.put("clinicRoomCode", s.getClinicRoomCode());
//                        scheduleMap.put("clinicRoomName", s.getClinicRoomName());
                        scheduleMap.put("doctorCode", s.getDoctorCode());
                        scheduleMap.put("doctorName", s.getDoctorName());
                        scheduleMap.put("avatar", s.getImageUrl());
//                        scheduleMap.put("doctorTitleCode", s.getDoctorTitleCode());
                        scheduleMap.put("doctorTitle", s.getDoctorTitle());
                        scheduleMap.put("doctorSpec", s.getDoctorSpec());
//                        scheduleMap.put("doctorSessTypeCode", s.getDoctorSessTypeCode());
//                        scheduleMap.put("doctorSessType", s.getDoctorSessType());
//                        scheduleMap.put("serviceCode", s.getServiceCode());
//                        scheduleMap.put("serviceName", s.getServiceName());
                        scheduleMap.put("fee", Checker.parseDouble(s.getFee()));
                        scheduleMap.put("regFee", Checker.parseDouble(s.getRegFee()));
                        scheduleMap.put("checkupFee", Checker.parseDouble(s.getCheckupFee()));
                        scheduleMap.put("serviceFee", Checker.parseDouble(s.getServiceFee()));
                        scheduleMap.put("otherFee", Checker.parseDouble(s.getOtherFee()));
//                        scheduleMap.put("availableNumStr", s.getAvailableNumStr());
//                        scheduleMap.put("admitAddress", s.getAdmitAddress());
//                        scheduleMap.put("admitTimeRange", s.getAdmitTimeRange());
//                        scheduleMap.put("note", s.getNote());
//                        scheduleMap.put("startTime", s.getStartTime());
//                        scheduleMap.put("endTime", s.getEndTime());
//                        scheduleMap.put("timeRangeFlag", s.getTimeRangeFlag());
//                        scheduleMap.put("scheduleStatus", s.getScheduleStatus());
//                        scheduleMap.put("availableTotalNum", Checker.parseInt(s.getAvailableTotalNum()));
//                        scheduleMap.put("availableLeftNum", Checker.parseInt(s.getAvailableLeftNum()));

                        boolean isStop = false;    //是否停诊

                        if (s.getServiceDate().equals(strCurrentDate) && currentCalendar.get(Calendar.HOUR) > 17) {
                            isStop = true;
                        }

                        int availableLeftNum = Checker.parseInt(s.getAvailableLeftNum());
                        int status = 0;
                        String statusName = "";


                        switch (s.getScheduleStatus()) {
                            case "N":   //正常
                            case "A":   //加诊
                                if (isStop) {
                                    status = 1;
                                    statusName = "停诊";
                                } else if (availableLeftNum > 0) {
                                    status = 0;
                                    statusName = "可预约";
                                } else {
                                    status = 8;
                                    statusName = "已满";
                                }
                                break;
//                            case "S":
//                                status = 1;
//                                statusName = "停诊";
//                                break;
//                            case "R":
//                                status = 2;
//                                statusName = "替诊";
//                                break;
//                            case "TR":
//                                status = 3;
//                                statusName = "被替诊";
//                                break;
//                            case "F":
//                                status = 4;
//                                statusName = "锁定";
//                                break;
//                            case "AR":
//                                status = 6;
//                                statusName = "补诊";
//                                break;
//                            case "PS":
//                                status = 7;
//                                statusName = "中途停诊";
//                                break;
                            default:
                                status = 1;
                                statusName = "停诊";
                                break;
                        }

                        scheduleMap.put("status", status);
                        scheduleMap.put("statusName", statusName);

                        switch (s.getSessionCode()) {
                            case "S":
                                forenoonList.add(scheduleMap);
                                break;
                            case "X":
                                afternoonList.add(scheduleMap);
                                break;
                            case "W":
                                nightList.add(scheduleMap);
                                break;
                        }
                    }

                    groupMap.put("hasScheduling", hasScheduling ? 1 : 0);   //当期日期是否有排班
                    groupMap.put("forenoonSchedules", forenoonList);        //上午排班记录
                    groupMap.put("afternoonSchedules", afternoonList);      //下午排班记录
                    groupMap.put("nightSchedules", nightList);              //晚上排班记录
                }

                lst.add(groupMap);
            }

            Map<String, Object> map = new HashMap<>();
            map.put("hospitalId", hospitalId);
            map.put("deptCode", deptCode);
            map.put("hospitalName", "南方医科大学南方医院");
            map.put("deptName", deptCode);
            map.put("list", lst);

            response.setData(map);
            return response.succeed("处理成功");

        } catch (Exception e) {
            logger.error("getScheduleList(){}", e.getMessage());
            return response.failed(BaseResponse.APP_EXCEPTION, Constant.ERROR_PROMPT);
        }
    }

    /**
     * 查询医生排班分时信息
     *
     * @param hospitalId
     * @param deptCode
     * @param doctorCode
     * @param serviceDate
     * @param period
     * @return
     */
    @UserLogin(need = false)
    @RequestMapping({"/doctorschedule"})
    public @ResponseBody
    BaseResponse getDoctorScheduleList(@RequestParam(name = "hospitalId") int hospitalId,
                                       @RequestParam(name = "deptCode") String deptCode,
                                       @RequestParam(name = "doctorCode") String doctorCode,
                                       @RequestParam(name = "serviceDate", required = false) String serviceDate,
                                       @RequestParam(name = "period", required = false) Integer period) {
        BaseResponse response = new BaseResponse();

        if (hospitalId != 1) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "医院不存在");
        }

        if (StringHelper.isNullOrWhiteSpace(deptCode)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "科室不存在");
        }

        if (StringHelper.isNullOrWhiteSpace(doctorCode)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "医生不存在");
        }

        List<Map<String, Object>> dataList = new LinkedList<>();

        if (!StringHelper.isNullOrWhiteSpace(serviceDate)) {
            //查询医生某一天的排班分时信息
            if (period == null) {
                return response.failed(BaseResponse.PARAMETER_ERROR, "请选择时段");
            }

            if (period != DatePeriodEnum.MORNING.getValue() && period != DatePeriodEnum.AFTERNOON.getValue()) {
                return response.failed(BaseResponse.PARAMETER_ERROR, "时段不存在");
            }

            Map<String, Object> map = getScheduleTimeInfoResponse(deptCode, doctorCode, serviceDate, period);

            if (map != null) {
                dataList.add(map);
            }
        } else {
            //取医生8天排班的分时信息
            int[] periods = {DatePeriodEnum.MORNING.getValue(), DatePeriodEnum.AFTERNOON.getValue()};
            Calendar calendar = Calendar.getInstance();

            for (int offset = 0; offset < 8; offset++) {
                if (offset > 0) {
                    calendar.add(Calendar.DATE, 1);
                }

                String strDate = DateUtil.formatDate(calendar.getTime(), "yyyy-MM-dd");

                for (int p : periods) {
                    Map<String, Object> map = getScheduleTimeInfoResponse(deptCode, doctorCode, strDate, p);

                    if (map != null) {
                        dataList.add(map);
                    }
                }
            }
        }

        String deptName = "";
        String doctorName = "";
        String avatar = "";
        String doctorTitle = "";
        String doctorSpec = "";
        double fee = 0d;
        double regFee = 0d;
        double treatFee = 0d;

        if (dataList.size() > 0) {
            Map<String, Object> map = dataList.get(0);
            String strDate = map.get("serviceDate").toString();
            GetScheduleListRequest getScheduleListRequest = GetScheduleListRequest.newBuilder()
                    .setDepartmentCode(deptCode)
                    .setEndDate(strDate)
                    .setStartDate(strDate)
                    .setDoctorCode(doctorCode)
                    .setRBASSessionCode("")
                    .setType(2)
                    .build();
            GetScheduleListResponse getScheduleListResponse = nfyyServiceBlockingStub.getScheduleList(getScheduleListRequest);

            if (getScheduleListResponse.getCode() == ResultCode.SUCCEED_VALUE) {
                List<Schedule> scheduleList = getScheduleListResponse.getSchedulesList();
                if (scheduleList.size() > 0) {
                    Schedule schedule = scheduleList.get(0);
                    deptName = schedule.getDepartmentName();
                    doctorName = schedule.getDoctorName();
                    avatar = schedule.getImageUrl();
                    doctorTitle = schedule.getDoctorTitle();
                    doctorSpec = schedule.getDoctorSpec();
                    fee = Checker.parseDouble(schedule.getFee());
                    regFee = Checker.parseDouble(schedule.getRegFee());
                    treatFee = Checker.parseDouble(schedule.getCheckupFee());
                }
            }
        }

        Map<String, Object> data = new HashMap<>();
        data.put("list", dataList);
        data.put("hospitalName", "南方医科大学南方医院");
        data.put("deptCode", deptCode);
        data.put("deptName", deptName);
        data.put("doctorCode", doctorCode);
        data.put("doctorName", doctorName);
        data.put("avatar", avatar);
        data.put("doctorTitle", doctorTitle);
        data.put("doctorSpec", doctorSpec);
        data.put("fee", fee);
        data.put("regFee", regFee);
        data.put("treatFee", treatFee);

        return response.succeed("处理成功", data);
    }


    private Map<String, Object> getScheduleTimeInfoResponse(String deptCode, String doctorCode, String serviceDate, int period) {
        List<Map<String, Object>> lst = new LinkedList<>();

        String RBASSessionCode = period == DatePeriodEnum.AFTERNOON.getValue() ? "X" : "S";
        GetScheduleTimeInfoRequest getScheduleTimeInfoRequest = GetScheduleTimeInfoRequest.newBuilder()
                .setDepartmentCode(deptCode)
                .setDoctorCode(doctorCode)
                .setServiceDate(serviceDate)
                .setRBASSessionCode(RBASSessionCode)
                .build();
        GetScheduleTimeInfoResponse getScheduleTimeInfoResponse = nfyyServiceBlockingStub.getScheduleTimeInfo(getScheduleTimeInfoRequest);

        if (getScheduleTimeInfoResponse.getCode() == ResultCode.SUCCEED_VALUE) {
            List<ScheduleTimeInfo> scheduleTimeInfoList = getScheduleTimeInfoResponse.getScheduleTimeInfosList();

            for (ScheduleTimeInfo scheduleTimeInfo : scheduleTimeInfoList) {
                String availableFlag = "N";

                for (TimeInfo timeInfo : scheduleTimeInfo.getTimeInfosList()) {
                    availableFlag = timeInfo.getAvailableFlag();
                }

                Map<String, Object> map = new HashMap<>();
                map.put("scheduleItemCode", scheduleTimeInfo.getScheduleItemCode());
                map.put("startTime", scheduleTimeInfo.getStartTime());
                map.put("endTime", scheduleTimeInfo.getEndTime());
                map.put("availableTotalNum", scheduleTimeInfo.getAvailableTotalNum());
                map.put("availableLeftNum", scheduleTimeInfo.getAvailableLeftNum());
                map.put("availableFlag", availableFlag);

                lst.add(map);
            }
        }

        if (lst.size() > 0) {
            Map<String, Object> dateMap = new HashMap<>();
            dateMap.put("serviceDate", serviceDate);
            dateMap.put("period", period);
            dateMap.put("datePeriod", DatePeriodEnum.valueOf(period).getDisplayName());
            dateMap.put("schedule", lst);

            return dateMap;
        }

        return null;
    }

    /**
     * 创建加号预约挂号订单
     *
     * @param hospitalId       医院Id
     * @param deptCode         科室Code
     * @param deptName         科室名称
     * @param doctorCode       医生Code
     * @param doctorName       医生名称
     * @param registeredFee    挂号费
     * @param medicalFee       诊查费
     * @param registeredDate   预约日期
     * @param period           预约时间段
     * @param startTime        预约开始时间：HH:MI
     * @param endTime          预约结束时间：HH:MI
     * @param medicalCardId    就诊人Id
     * @param scheduleItemCode 门诊排班项记录标识
     * @return
     */
    @RequestMapping({"/createregisteredorder"})
    public @ResponseBody
    BaseResponse createRegisteredOrder(
            @RequestParam(name = "hospitalId") int hospitalId,
            @RequestParam(name = "deptCode") String deptCode,
            @RequestParam(name = "deptName") String deptName,
            @RequestParam(name = "doctorCode") String doctorCode,
            @RequestParam(name = "doctorName") String doctorName,
            @RequestParam(name = "registeredFee") double registeredFee,
            @RequestParam(name = "medicalFee") double medicalFee,
            @RequestParam(name = "registeredDate") String registeredDate,
            @RequestParam(name = "period") int period,
            @RequestParam(name = "startTime") String startTime,
            @RequestParam(name = "endTime") String endTime,
            @RequestParam(name = "medicalCardId") int medicalCardId,
            @RequestParam(name = "scheduleItemCode") String scheduleItemCode) {
        BaseResponse response = new BaseResponse();

        if (hospitalId < 1) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "医院不存在");
        }

        if (StringHelper.isNullOrWhiteSpace(deptCode) || StringHelper.isNullOrWhiteSpace(deptName)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "科室不存在");
        }

        if (StringHelper.isNullOrWhiteSpace(doctorCode) || StringHelper.isNullOrWhiteSpace(doctorName)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "医生不存在");
        }

        if (StringHelper.isNullOrWhiteSpace(registeredDate)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "请选择挂号日期");
        }

        Date date = DateUtil.parseDate(registeredDate, "yyyy-MM-dd");

        if (date == null) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "日期格式不正确");
        }

        if (period != DatePeriodEnum.MORNING.getValue() && period != DatePeriodEnum.AFTERNOON.getValue()) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "预约时段不存在");
        }

        if (StringHelper.isNullOrWhiteSpace(startTime)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "预约开始时间不存在");
        }

        if (StringHelper.isNullOrWhiteSpace(endTime)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "预约结束时间不存在");
        }

        if (medicalCardId < 1) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "请选择就诊人");
        }

        if (StringHelper.isNullOrWhiteSpace(scheduleItemCode)) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "门诊排班项记录标识不能为空");
        }

        int source = TerminalEnum.TaiheWxOfficial.getValue();

        try {
            CreateRegisteredOrderRequest createRegisteredOrderRequest = CreateRegisteredOrderRequest.newBuilder()
                    .setHospitalId(hospitalId)
                    .setDeptCode(deptCode)
                    .setDeptName(deptName)
                    .setDoctorCode(doctorCode)
                    .setDoctorName(doctorName)
                    .setTotal((int) ((registeredFee + medicalFee) * 100))
                    .setRegisteredFee((int) (registeredFee * 100))
                    .setMedicalFee((int) (medicalFee * 100))
                    .setRegisteredDate(date.getTime())
                    .setPeriod(period)
                    .setStartTime(startTime)
                    .setEndTime(endTime)
                    .setUserId(userService.getCurrentUserIdWrapped())
                    .setMedicalCardId(medicalCardId)
                    .setScheduleItemCode(scheduleItemCode)
                    .setPaymentChannel(PaymentChannelEnum.Cash.getValue())
                    .setType(2)
                    .setSource(source)
                    .build();
            CreateRegisteredOrderResponse createRegisteredOrderResponse = orderServiceBlockingStub.createRegisteredOrder(createRegisteredOrderRequest);
            Result result = createRegisteredOrderResponse.getResult();

            if (result.getCode() == ResultCode.SUCCEED) {
                Map<String, Object> map = new HashMap<>();
                map.put("orderId", createRegisteredOrderResponse.getOrderId());
                map.put("orderType", createRegisteredOrderResponse.getOrderType());
                map.put("status", createRegisteredOrderResponse.getStatus());

                return response.succeed("处理成功", map);
            }

            return response.failed(BaseResponse.APP_ERROR, result.getInfo());
        } catch (Exception e) {
            logger.error("createRegisteredOrder():", e);
            return response.failed(BaseResponse.APP_EXCEPTION, e.getMessage());
        }
    }

    /**
     * 预约挂号订单支付
     *
     * @param orderId
     * @return
     */
    @RequestMapping({"/pay"})
    public @ResponseBody
    BaseResponse payOrder(@RequestParam(name = "orderId") int orderId) {
        BaseResponse response = new BaseResponse();

        if (orderId < 1) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "订单不存在");
        }

        try {
            PayRegisteredOrderRequest payRegisteredOrderRequest = PayRegisteredOrderRequest.newBuilder()
                    .setOrderId(orderId)
                    .setUserId(userService.getCurrentUserIdWrapped())
                    .build();
            PayRegisteredOrderResponse payRegisteredOrderResponse = orderServiceBlockingStub.payRegisteredOrder(payRegisteredOrderRequest);
            Result result = payRegisteredOrderResponse.getResult();

            if (result.getCode() == ResultCode.SUCCEED) {
                return response.succeed("处理成功");
            }

            String info = result.getInfo();
            if (!StringHelper.isNullOrWhiteSpace(info)) {
                info = info.replaceAll(":", "");
            }
            return response.failed(BaseResponse.APP_ERROR, info);
        } catch (Exception e) {
            logger.error("payOrder(): {}", e.getMessage());
            return response.error();
        }
    }

    /**
     * 取消预约挂号订单
     *
     * @param orderId
     * @return
     */
    @RequestMapping({"/cancel"})
    public @ResponseBody
    BaseResponse cancelOrder(@RequestParam(name = "orderId") int orderId) {
        BaseResponse response = new BaseResponse();

        if (orderId < 1) {
            return response.failed(BaseResponse.PARAMETER_ERROR, "订单不存在");
        }

        try {
            CancelRegisteredOrderRequest cancelRegisteredOrderRequest = CancelRegisteredOrderRequest.newBuilder()
                    .setOrderId(orderId)
                    .setUserId(userService.getCurrentUserIdWrapped())
                    .build();
            ResultInt result = orderServiceBlockingStub.cancelRegisteredOrder(cancelRegisteredOrderRequest);

            if (result.getCode() == ResultCode.SUCCEED) {
                Map<String, Object> map = new HashMap<>();
                map.put("status", result.getValue());

                return response.succeed(result.getInfo(), map);
            }

            return response.failed(BaseResponse.APP_ERROR, response.getInfo());
        } catch (Exception e) {
            logger.error("cancelOrder(): {}", e.getMessage());
            return response.error();
        }
    }


}
