package com.ywt.outpatient.service.web.taihe;

import com.ywt.biz.common.enums.TerminalEnum;
import com.ywt.biz.common.util.StringHelper;
import com.ywt.gapi.Result;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.user.GetOfficialUserInfoRequest;
import com.ywt.gapi.user.GetOfficialUserInfoResponse;
import com.ywt.gapi.user.UserService;
import com.ywt.outpatient.domain.models.PatientLoginInfo;
import com.ywt.outpatient.core.WebAppContext;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

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

    @DubboReference
    private UserService userServiceBlockingStub;

    public int getCurrentUserIdWrapped() {
//        return 5;
        return getCurrentUserId(WebAppContext.current().getTerminal());
    }

    public int getCurrentUserId(int terminal) {
        int curTerminal = WebAppContext.current().getTerminal();
        if(curTerminal == TerminalEnum.TAI_HE_OFFICIAL.getValue() || curTerminal == TerminalEnum.NFYYBYFY_WXAPP.getValue()){
            return WebAppContext.current().getUserId();
        }

        PatientLoginInfo loginInfo = getPatientLoginInfo(terminal);
        return loginInfo != null ? loginInfo.getUserId() : 0;
    }

    /**
     * 获取当前登录用户的OpenId
     *
     * @return
     */
    public String getCurrentOpenId() {
        return WebAppContext.current().getOpenId();
    }

    public PatientLoginInfo getPatientLoginInfo(int terminal){
        PatientLoginInfo loginInfo = null;
        String unionId = WebAppContext.current().getUnionId();

        if (!StringHelper.isNullOrWhiteSpace(unionId)) {
            GetOfficialUserInfoRequest req = GetOfficialUserInfoRequest.newBuilder()
                    .setHospitalId(0)
                    .setUnionId(unionId)
                    .setTerminal(terminal)
                    .build();
            GetOfficialUserInfoResponse res = userServiceBlockingStub.getOfficialUserInfo(req);
            Result result = res.getResult();

            if (result.getCode() == ResultCode.SUCCEED) {
                loginInfo  = new PatientLoginInfo();
                loginInfo.setUserId(res.getUserId());
                loginInfo.setMobile(res.getMobile());
                loginInfo.setUnionId(res.getUnionId());
            }
        }

//        loginInfo  = new PatientLoginInfo();
//        loginInfo.setUserId(10178);
//        loginInfo.setMobile("15817163240");
//        loginInfo.setUnionId("");
//        loginInfo  = new PatientLoginInfo();
//        loginInfo.setUserId(4);
//        loginInfo.setMobile("18867318932");
//        loginInfo.setUnionId("");

        return loginInfo;
    }
}
