package com.ywt.alipaympapi.web.controller;

import com.ywt.alipaympapi.core.utils.*;
import com.ywt.alipaympapi.models.BaseResponse;
import com.ywt.alipaympapi.models.BaseResponse2;
import com.ywt.alipaympapi.models.Constants;
import com.ywt.alipaympapi.models.auth.*;
import com.ywt.alipaympapi.models.enums.TerminalEnum;
import com.ywt.alipaympapi.service.AuthService;
import com.ywt.alipaympapi.web.interceptors.WebAppContext;
import com.ywt.core.exception.AppMessageException;
import com.ywt.gapi.gateway.AuthServiceGrpc;
import com.ywt.gapi.gateway.IssueJWTRequest;
import com.ywt.gapi.gateway.IssueJWTResponse;
import com.ywt.gapi.user.BindAlipayUserInfoRequest;
import com.ywt.gapi.user.BindAlipayUserInfoResponse;
import com.ywt.gapi.user.UserServiceGrpc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @author Walker
 * Created on 2022/8/29
 */
@Slf4j
@RestController("/auth")
@RequestMapping({"/auth"})
public class AuthController {

    @Autowired
    private UserServiceGrpc.UserServiceBlockingStub userServiceBlockingStub;
    @Autowired
    private AuthServiceGrpc.AuthServiceBlockingStub authServiceBlockingStub;
    @Autowired
    private AuthService authService;


    @RequestMapping(value = {"/bind"}, method = RequestMethod.POST)
    public @ResponseBody BaseResponse2<BindAlipayMpResp> bind(@RequestBody
                                                              BindAlipayMpReq reqData) {
        BaseResponse2<BindAlipayMpResp> baseResponse = new BaseResponse2<>();
        try {
            int terminal = reqData.getTerminal();
            String ip = WebAppContext.current().getIP();
            String ticket = reqData.getTicket();
            CheckUtil.ensureNotEmpty(ticket, "ticket 不能为空");
            AlipayMpCfg cfg = authService.getCfg(terminal);
            // 获取用户信息
            GetAlipayUserInfoReq req = new GetAlipayUserInfoReq();
            req.setTicket(ticket);
            req.setAppId(cfg.getAppId());
            req.setSaasSecurityKey(cfg.getSaasSecurityKey());
            GetAlipayUserInfoResp resp = authService.getAlipayUserInfo(req);
            String alipayUid = Checker.getStringValue(resp.getAlipayUid());
            CheckUtil.ensureNotEmpty(alipayUid, "支付宝用户信息有误，alipayUid 为空");
            String avatar = Checker.getStringValue(resp.getAvatar());
            String realName = Checker.getStringValue(resp.getRealName());
            String nickName = Checker.getStringValue(resp.getNickName());
            String mobile = Checker.getStringValue(resp.getMobile());
            CheckUtil.ensureNotEmpty(alipayUid, "支付宝用户未绑定手机，请先前往支付宝个人中心绑定");
            int age = Checker.getIntegerValue(resp.getAge());
            String idCardNo = Checker.getStringValue(resp.getIdCardNo());
            BindAlipayUserInfoResponse response = userServiceBlockingStub.bindAlipayUserInfo(BindAlipayUserInfoRequest.newBuilder()
                            .setAlipayUid(alipayUid)
                            .setAvatar(avatar)
                            .setRealName(realName)
                            .setNickName(nickName)
                            .setMobile(mobile)
                            .setIdCardNo(idCardNo)
                            .setAge(age)
                            .setTerminal(terminal)
                            .setIp(ip)
                    .build());
            if (response.getCode() == BaseResponse.SUCCEED) {
                int userId = response.getUserId();
                BindAlipayMpResp r = new BindAlipayMpResp();
                r.setUserId(userId);
                r.setAlipayUid(alipayUid);
                r.setMobile(mobile);
                // 根据终端判断医院信息
                r.setHospitalId(BizUtil.getCurrentHospitalId());
                return baseResponse.succeed(r);
            }
            return baseResponse.failed(BaseResponse.APP_ERROR, response.getInfo());
        } catch (AppMessageException appMessageException) {
            return baseResponse.error(appMessageException.getMessage());
        } catch (Exception e) {
            log.error("AuthController#bind(reqData = {}): {}", reqData, e.getMessage(), e);
            return baseResponse.error(e.getMessage());
        }
    }


}
