package com.ywt.outpatient.service.rpc.common;

import com.ywt.biz.common.util.Checker;
import com.ywt.gapi.Result;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.drug.*;
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.List;
import java.util.Map;

/**
 * @author daiyihua
 * @create 2018-08-30 上午10:03
 * @desc 调用处方rpc相关类
 **/
@Service
public class DrugProvider {

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

    @Autowired
    private DrugService drugServiceBlockingStub;


    /**
     * 得到处方记录(his_order_no为空)
     *
     * @param userId 用户ID
     * @param type   1-进行中，2-已完成
     * @param mobile 手机号
     * @return
     */
    public Map<String, Object> getPrescriptionBaseInfoList(int userId, int type, String mobile) {
        Map map = new HashMap();
        try {
            GetPrescriptionBaseInfoListRequest request = GetPrescriptionBaseInfoListRequest.newBuilder()
                    .setUserId(userId)
                    .setType(type)
                    .setMobile(mobile)
                    .build();
            GetPrescriptionBaseInfoListResponse response = drugServiceBlockingStub.getPrescriptionBaseInfoList(request);
            if (response.getCode() == ResultCode.SUCCEED.getNumber()) {
                map.put("list", response.getBaseInfoList());
                map.put("prescriptionIds", response.getInfo());
                return map;
            }
        } catch (Exception e) {
            logger.error("患者获取处方记录getPrescriptionBaseInfoList:", e.getMessage(), e);
        }
        return map;
    }

    public ServiceResult savePrescriptionInfo(
            int userId, String idCardNo, int hospitalId, String patientName, int patientSex, int patientAge,
            String patientMobile, String diagnosis, String allergicHistory, String description,
            int doctorId, String doctorName, int doctorSignId, List<DrugUsage> drugUsageList) {
        ServiceResult result = new ServiceResult();
        SavePrescriptionInfoRequest req = SavePrescriptionInfoRequest.newBuilder()
                .setHospitalId(hospitalId)
                .setPatientName(patientName)
                .setPatientSex(patientSex)
                .setPatientAge(patientAge)
                .setPatientMobile(patientMobile)
                .setDiagnosis(diagnosis)
                .setAllergicHistory(Checker.getStringValue(allergicHistory))
                .setDescription(Checker.getStringValue(description))
                .setDoctorId(doctorId)
                .setDoctorName(doctorName)
                .setDoctorSignId(doctorSignId)
                .addAllDrugUsage(drugUsageList)
                .setUserId(userId)
                .setIdCardNo(idCardNo)
                .build();
        SavePrescriptionInfoResponse res = drugServiceBlockingStub.savePrescriptionInfo(req);

        if (res.getCode() == 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("prescriptionId", res.getPrescriptionId());
            map.put("preBizNo", res.getPreBizNo());
            return result.succeed(map);
        }
        return result.failed(res.getInfo());
    }


    /**
     * 保存处方费用请求
     *
     * @param individual         个人支付费用
     * @param prescriptionInfoId 处方单ID
     * @param userId             用户ID
     * @return
     */
    public ServiceResult savePrescriptionFee(int individual, int prescriptionInfoId, int userId) {
        ServiceResult result = new ServiceResult();
        try {
            SavePrescriptionFeeRequest request = SavePrescriptionFeeRequest.newBuilder()
                    .setIndividual(individual)
                    .setPrescriptionInfoId(prescriptionInfoId)
                    .setUserId(userId)
                    .build();
            Result res = drugServiceBlockingStub.savePrescriptionFee(request);
            if (res.getCode().getNumber() == 0) {
                return result.succeed("处理成功");
            }
            return result.failed(res.getInfo());
        } catch (Exception e) {
            logger.error("保存处方费用请求savePrescriptionFee,{},{}", individual, prescriptionInfoId, e.getMessage(), e);
        }
        return result.failed("处理失败");
    }


    /**
     * 保存处方地址以及费用
     *
     * @param addressId          填写的地址ID（如果取药方式为自取，则药房地址ID不为空）
     * @param pharmacyId         药房地址ID
     * @param freight            快递费（单位：分）
     * @param individual         个人结算金额（单位：分）
     * @param needPrintStatus    是否需要打印（是否需要打印发票，0-不需要，1-需要）
     * @param prescriptionInfoId 处方单ID（对应处方表ID）
     * @param deliveryMethod     1-快递到家，2-自取
     * @return
     */
    public ServiceResult savePrescriptionExpressAddress(int addressId, int pharmacyId, int freight, int individual,
                                                        int needPrintStatus, int prescriptionInfoId, int deliveryMethod, String timeStandard) {
        ServiceResult result = new ServiceResult();
        try {
            SavePrescriptionExpressAddressRequest addressRequest = SavePrescriptionExpressAddressRequest.newBuilder()
                    .setAddressId(addressId)
                    .setPharmacyId(pharmacyId)
                    .setFreight(freight)
                    .setIndividual(individual)
                    .setNeedPrintStatus(needPrintStatus)
                    .setPreId(prescriptionInfoId)
                    .setDeliveryMethod(deliveryMethod)
                    .setTimeStandard(timeStandard)
                    .build();
            ResultResponse res = drugServiceBlockingStub.savePrescriptionExpressAddress(addressRequest);
            if (res.getCode() == 0) {
                return result.succeed("处理成功");
            }
            return result.failed(res.getInfo());
        } catch (Exception e) {
            logger.error("保存处方费用请求savePrescriptionExpressAddress,{},{},{},{},{},{}",
                    addressId, pharmacyId, freight, individual, needPrintStatus, prescriptionInfoId, e.getMessage(), e);
        }
        return result.failed("处理失败");
    }


    /**
     * 根据preId(处方表ID)获取处方基本信息
     *
     * @param preId
     * @return
     */
    public PrescriptionBaseInfo getPrescriptionBaseByPreId(int preId) {
        try {
            GetPrescriptionBaseInfoByIdRequest req = GetPrescriptionBaseInfoByIdRequest.newBuilder().setPreId(preId).build();
            GetPrescriptionBaseInfoByIdResponse response = drugServiceBlockingStub.getPrescriptionBaseInfoById(req);
            if (response.getCode() == ResultCode.SUCCEED.getNumber()) {
                return response.getPrescriptionBaseInfo();
            }
        } catch (Exception e) {
            logger.error("根据preId获取处方信息getPrescriptionBaseInfoById:", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 判断是否是白云和太和外转处方
     *
     * @param preId 处方号ID
     * @return
     */
    public boolean checkIsByAndThPrescription(int preId) {
        try {
            GetPrescriptionTypeRequest req = GetPrescriptionTypeRequest.newBuilder().setPreId(preId).build();
            GetPrescriptionTypeResponse response = drugServiceBlockingStub.getPrescriptionType(req);
            if (response.getCode() == ResultCode.SUCCEED.getNumber()) {
                return response.getIsByAndThPrescription();
            }
        } catch (Exception e) {
            logger.error("根据preId获取处方信息getPrescriptionBaseInfoById:", e.getMessage(), e);
        }
        return false;
    }

}
