package com.liangjian.dataplatform.member.controller;

import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.UserApi;
import com.liangjian.dataplatform.member.entity.po.secondary.WeixinUserInfo;
import com.liangjian.dataplatform.member.entity.response.ResultObject;
import com.liangjian.dataplatform.member.entity.vo.request.PhoneSMSInfo;
import com.liangjian.dataplatform.member.service.IPhoneSMSService;
import com.liangjian.dataplatform.member.service.IWeixinUserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Random;

/**
 * @Author: 黄子奇
 * @Date: 2019/11/15
 */
@RestController
@RequestMapping("/weixin/register")
@Api(value = "微信绑定手机控制器", tags = "Wechat", description = "微信绑定手机控制器")
public class WeixinRegisterController {

    @Autowired
    private IWeixinUserInfoService iWeixinUserInfoService;
    @Autowired
    private IPhoneSMSService iPhoneSMSService;

    @PostMapping("/sendCode")
    @ApiOperation(value = "发送短信验证码")
    public ResultObject<Object> sendCode(@ApiParam(value = "手机号信息", required = true) @RequestBody PhoneSMSInfo info) {
        try {
            String phone = info.getPhone();
            Integer code = new Random().nextInt(8999) + 1000;
            iPhoneSMSService.sendSms(phone, code.toString());
            return ResultObject.success("发送成功，60秒后可重发",null);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultObject.error("发送失败");
        }
    }

    @PostMapping("/verifyAndBind")
    @ApiOperation(value = "验证手机号验证码，并绑定（绑定成功后返回jwt，以后作为请求凭证）, 对于返回的结果，当success未false时，data的值： 1：已绑定 2：未知错误 3：未注册会员需跳转")
    public ResultObject<String> verifyAndBind(@ApiParam(value = "手机号信息", required = true) @RequestBody PhoneSMSInfo info) {
        String phone = info.getPhone();
        String code = info.getCode();
        String openid = info.getOpenid();
        if(iPhoneSMSService.verifyPhoneCode(phone, code)) {
            ApiResult apiResult = UserApi.getUserInfo(openid);
            WeixinUserInfo weixinUserInfo = WeixinUserInfo.fromMap(apiResult.getAttrs());
            int result = iWeixinUserInfoService.addWeixinUserInfo(weixinUserInfo, phone);
            switch (result) {
                case IWeixinUserInfoService.ADD_SUCCESS : {
                    //绑定成功，同时需要做登陆
                    return iWeixinUserInfoService.encodeJwt(weixinUserInfo, IWeixinUserInfoService.WECHAT)
                            .map(i -> ResultObject.success("绑定并登陆成功",i))
                            .orElse(ResultObject.error("发生未知错误"));
                }
                case IWeixinUserInfoService.NOT_USER_REGIS: {
                    var res =  ResultObject.<String>error("您暂未注册亮健会员，您可直接访问亮健官网注册会员！");
                    res.setData(IWeixinUserInfoService.NOT_USER_REGIS+"");
                    return res;
                }
                case IWeixinUserInfoService.HAS_EXIST: {
                    var res = ResultObject.<String>error("手机号已被绑定");
                    res.setData(IWeixinUserInfoService.HAS_EXIST+"");
                    return res;
                }
                default: {
                    var res = ResultObject.<String>error("发生未知错误");
                    res.setData(IWeixinUserInfoService.ADD_ERROR+"");
                    return res;
                }
            }
        } else {
            return ResultObject.error("验证码错误");
        }
    }
}
