package com.ywt.outpatient.service.rpc;

import com.ywt.gapi.nfyy.*;
import com.ywt.outpatient.service.rpc.common.ServiceResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

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

    @Autowired
    private NfyyService nfyyServiceBlockingStub;

    public void getDoctorList() {
        GetDoctorListRequest getDoctorListRequest = GetDoctorListRequest.newBuilder()
                .setDoctorName("")
                .setDepartmentCode("")
                .build();
        GetDoctorListResponse getDoctorListResponse = nfyyServiceBlockingStub.getDoctorList(getDoctorListRequest);
        int code = getDoctorListResponse.getCode();
//        Result result = getDoctorListResponse.getResult();

    }

    public GetPatientInfoResponse getPatientInfo(String patientCard, String patientId, String idNo, String patientName) {
        try {
            GetPatientInfoRequest request = GetPatientInfoRequest.newBuilder()
                    .setPatientCard(patientCard)
                    .setPatientId(patientId)
                    .setIdNo(idNo)
                    .setPatientName(patientName)
                    .build();
            return nfyyServiceBlockingStub.getPatientInfo(request);
        } catch (Exception e) {
            logger.error("getPatientInfo({}, {}, {}, {}): {}", patientCard, patientId, idNo, patientName, e.getMessage());
            return null;
        }
    }

    /**
     * 预约挂号
     *
     * @param scheduleItemCode 门诊排班项代码
     * @param patientId        病人ID
     * @param cardNo           卡号
     * @param cardType         卡类型
     * @param payModeCode      支付方式代码
     * @param payFee           个人支付费用
     * @param startTime        开始时间(09:00)
     * @param endTime          结束时间(09:30)
     * @return
     */
    public ServiceResult createOrder(String scheduleItemCode, String patientId, String cardNo, String cardType,
                                     String payModeCode, String payFee, String startTime, String endTime, int type,
                                     String patientName) {
        ServiceResult serviceResult = new ServiceResult();
        try {
            CreateOrderRequest request = CreateOrderRequest.newBuilder()
                    .setScheduleItemCode(scheduleItemCode)
                    .setPatientId(patientId)
                    .setCardNo("")
                    .setCardType("02")
                    .setPayModeCode("")
                    .setPayFee(payFee)
                    .setStartTime(startTime)
                    .setEndTime(endTime)
                    .setType(type)
                    .setPatientName(patientName)
                    .build();
            CreateOrderResponse response = nfyyServiceBlockingStub.createOrder(request);

            if (response.getCode() == 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("seqCode", response.getSeqCode());              //挂号序号
                map.put("regFee", response.getRegFee());                //挂号费
                map.put("admitRange", response.getAdmitRange());        //就诊时间段
                map.put("admitAddress", response.getAdmitAddress());    //就诊地点
                map.put("orderContent", response.getOrderContent());    //预约单内容（内容说明：卡号^病人Rowid^病人姓名^性别^挂号序号(班别)^挂号序号^科室名称^医生姓名^预约日期^时间^候诊日期^^）
                map.put("transactionId", response.getTransactionId());  //交易流水号
                map.put("orderCode", response.getOrderCode());          //预约单号

                return serviceResult.succeed(response.getMsg(), map);
            }

            return serviceResult.failed(response.getMsg());
        } catch (Exception e) {
            logger.error("createOrder(): {}", e.getMessage());
            return serviceResult.failed(e.getMessage());
        }
    }

    /**
     * 病人取号确认
     *
     * @param orderCode
     * @param patientId
     * @param amount
     * @param payModeCode
     * @return
     */
    public ServiceResult confirm(String orderCode, String patientId, String amount, String payModeCode) {
        ServiceResult serviceResult = new ServiceResult();

        try {
            ConfirmRequest request = ConfirmRequest.newBuilder()
                    .setOrderCode(orderCode)
                    .setPatientId(patientId)
                    .setPayAmt(amount)
                    .setPayModeCode(payModeCode)
                    .buildPartial();

            ConfirmResponse response = nfyyServiceBlockingStub.confirm(request);

            if (response.getCode() == 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("seqCode", response.getSeqCode());              //挂号序号
                map.put("regFee", response.getRegFee());                //挂号费
                map.put("admitRange", response.getAdmitRange());        //就诊时间段
                map.put("admitAddress", response.getAdmitAddress());    //就诊地点
                map.put("admNo", response.getAdmNo());                  //就诊号
                map.put("transactionId", response.getTransactionId());  //交易流水号

                return serviceResult.succeed(response.getMsg(), map);
            }

            return serviceResult.failed(response.getMsg());
        } catch (Exception e) {
            logger.error("confirm(): {}", e.getMessage());
            return serviceResult.failed(e.getMessage());
        }
    }

    /**
     * 取消没有支付的预约记录
     * @param orderCode 预约单号
     * @return
     */
    public ServiceResult cancelOrder(String orderCode, int type) {
        ServiceResult serviceResult = new ServiceResult();

        try {
            CancelOrderRequest request = CancelOrderRequest.newBuilder()
                    .setOrderCode(orderCode)
                    .setType(type)
                    .build();
            CancelOrderResponse response = nfyyServiceBlockingStub.cancelOrder(request);

            if (response.getCode() == 0) {
                return serviceResult.succeed(response.getMsg());
            }

            return serviceResult.failed(response.getMsg());
        } catch (Exception e) {
            logger.error("cancelOrder(): {}", e.getMessage());
            return serviceResult.failed(e.getMessage());
        }
    }

    /**
     * 退号
     * @param clinicCode 就诊流水号
     * @return
     */
    public ServiceResult cancelReg(String clinicCode){
        ServiceResult serviceResult = new ServiceResult();

        try{
            CancelRegRequest request = CancelRegRequest.newBuilder().setAdmNo(clinicCode).build();
            CancelRegResponse response = nfyyServiceBlockingStub.cancelReg(request);

            if(response.getCode() == 0){
                Map<String, Object> map = new HashMap<>();
                map.put("returnFee", response.getReturnFee());          //就诊号
                map.put("transactionId", response.getTransactionId());  //交易流水号

                serviceResult.setData(map);
                return serviceResult.succeed(response.getMsg());
            }

            return serviceResult.failed(response.getMsg());
        } catch (Exception e) {
            logger.error("cancelReg(): {}", e.getMessage());
            return serviceResult.failed(e.getMessage());
        }
    }
}