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

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.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 WebUserService {
    private static Logger logger = LoggerFactory.getLogger(WebUserService.class);

    @DubboReference
    private com.ywt.gapi.user.UserService userServiceBlockingStub;

    /**
     * 获取当前登录用户的UserId
     *
     * @return
     */
    public int getCurrentUserId() {
        PatientLoginInfo loginInfo = getPatientLoginInfo();
        return loginInfo != null ? loginInfo.getUserId() : 0;
    }

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

    public PatientLoginInfo getPatientLoginInfo() {
        PatientLoginInfo loginInfo = null;
//        String unionId = WebAppContext.current().getUnionId();
        String openId = WebAppContext.current().getOpenId();

        if (!StringHelper.isNullOrWhiteSpace(openId)) {
            GetOfficialUserInfoRequest req = GetOfficialUserInfoRequest.newBuilder()
                    .setHospitalId(0)
                    .setOpenId(openId)
//                    .setUnionId(unionId)
                    .setTerminal(TerminalEnum.PatientWxOfficial.getValue())
                    .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(8);
//        loginInfo.setMobile("15817163240");
//        loginInfo.setUnionId("");

        return loginInfo;
    }

    /**
     * 获取当前登录用户的UserId
     *
     * @return
     */
    public int getCurrentTerminal() {
        return WebAppContext.current().getTerminal();
    }


}
