package com.github.wxiaoqi.security.admin.rpc;

import com.ace.cache.annotation.Cache;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.biz.AppUserLoginBiz;
import com.github.wxiaoqi.security.admin.entity.AppUserLogin;
import com.github.wxiaoqi.security.admin.rpc.service.AppPermissionService;
import com.github.wxiaoqi.security.admin.vo.ImiVo;
import com.github.wxiaoqi.security.api.vo.authority.PermissionInfo;
import com.github.wxiaoqi.security.api.vo.user.AppUserInfo;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.auth.client.jwt.UserAuthUtil;
import com.github.wxiaoqi.security.auth.common.util.jwt.IJWTInfo;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.util.process.SystemConfig;
import com.github.wxiaoqi.security.common.util.result.JsonResultUtil;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author keliii
 */
@RestController
@RequestMapping("api/app")
public class AppUserRest {
    @Autowired
    private AppPermissionService appPermissionService;

    @Autowired
    private UserAuthUtil authUtil;

    @Autowired
    private UserAuthConfig userAuthConfig;
    @Autowired
    private AppUserLoginBiz appUserLoginBiz;

//    @Cache(key="permission")
//    @RequestMapping(value = "/permissions", method = RequestMethod.GET)
//    public @ResponseBody
//    List<PermissionInfo> getAllPermission(){
//        return permissionService.getAllPermission();
//    }
//
    @Cache(key="app:permission:u{1}")
    @RequestMapping(value = "/user/un/{username}/permissions", method = RequestMethod.GET)
    public @ResponseBody List<PermissionInfo> getPermissionByUsername(@PathVariable("username") String username){
        return appPermissionService.getPermissionByUsername(username);
    }

    @RequestMapping(value = "/user/validate", method = RequestMethod.POST)
    public @ResponseBody
    AppUserInfo validate(@RequestBody Map<String,String> body){
        return appPermissionService.validate(body.get("username"),body.get("password"));
    }

    /**
     * 发送验证码
     * @param username
     * @param type 0-注册验证，1-找回密码验证，2&3-修改手机号
     * @return
     */
    @RequestMapping(value = "/user/sendsms", method = RequestMethod.POST)
    public @ResponseBody
    JSONObject sendsms(@RequestParam(value="username",defaultValue="")String  username, @RequestParam(value="type",defaultValue="0")Integer type){
        return appPermissionService.sendSMS(username,type);
    }

    /**
     * 注册
     * @param username
     * @param mobilecode
     * @param password
     * @return
     */
    @RequestMapping(value = "/user/register", method = RequestMethod.POST)
    public @ResponseBody
    JSONObject register(
            @RequestParam(value="username",defaultValue="")String  username,
            @RequestParam(value="mobilecode",defaultValue="")String mobilecode,
            @RequestParam(value="password",defaultValue="")String  password,
            @RequestParam(value="code",defaultValue="")String  code
    ){
        //默认昵称
        String nickname=SystemConfig.USER_NIKENAME_DEFAULT+(int)((Math.random()*9+1)*100000);
        return appPermissionService.register(username, password, SystemConfig.USER_HEADER_URL_DEFAULT,nickname,
                mobilecode, null, null,0,code);
    }


    /**
     *  微信注册/微信绑定
     * @param username
     * @param mobilecode
     * @param password
     * @param nickname
     * @param headimgurl
     * @param openid
     * @param unionid
     * @param type
     * @return
     */
    @RequestMapping(value = "/user/wxregister", method = RequestMethod.POST)
    public @ResponseBody
    JSONObject wxregister(
            @RequestParam(value="username",defaultValue="")String  username,
            @RequestParam(value="mobilecode",defaultValue="")String mobilecode,
            @RequestParam(value="password",defaultValue="")String  password,
            @RequestParam(value="nickname",defaultValue="")String  nickname,
            @RequestParam(value="headimgurl",defaultValue="")String  headimgurl,
            @RequestParam(value="openid",defaultValue="")String  openid,
            @RequestParam(value="unionid",defaultValue="")String  unionid,
            @RequestParam(value="type",defaultValue="0")Integer  type,
            @RequestParam(value="isQQ",defaultValue="0")Integer  isQQ,
            @RequestParam(value="code",defaultValue="")String  code
    ){
        if(StringUtils.isBlank(headimgurl)){
            headimgurl=SystemConfig.USER_HEADER_URL_DEFAULT;
        }
        if(StringUtils.isBlank(nickname)){
             nickname=SystemConfig.USER_NIKENAME_DEFAULT+(int)((Math.random()*9+1)*100000);
        }
        return appPermissionService.weCahtRegister(username,password,openid, unionid,nickname,headimgurl,type,mobilecode,isQQ,code);
    }
    /**
     * 手机号码检测是否已绑定
     *
     * @param username
     * @return
     */
    @RequestMapping(value = "/user/checkBindWechat")
    public @ResponseBody JSONObject checkBindWechat(@RequestParam(value="username",defaultValue="")String  username) {
        if (StringUtils.isBlank(username)) {
            return JsonResultUtil.createFailedResult(ResultCode.NULL_CODE, "参数为空");
        }
        return appPermissionService.checkBindWechat(username);
    }


    @RequestMapping(value = "/user/wxlogin")
    public @ResponseBody JSONObject wxlogin(
            @RequestParam(value="openid",defaultValue="")String  openid,
            @RequestParam(value="isQQ",defaultValue="0")Integer isQQ,
            @RequestParam(value="code",defaultValue="")String  code) {
        return appPermissionService.weCahtLogin(openid,isQQ,code);
    }

    /**
     * 登录
     * @param username
     * @param mobilecode
     * @param password
     * @param type 1-账号密码;2-验证码
     * @return
     */
    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public @ResponseBody
    JSONObject login(
            @RequestParam(value="username",defaultValue="")String  username,
            @RequestParam(value="mobilecode",defaultValue="")String mobilecode,
            @RequestParam(value="password",defaultValue="")String  password,
            @RequestParam(value="type",defaultValue="1")Integer  type,
            @RequestParam(value="code",defaultValue="")String  code
    ){

        return appPermissionService.login(username,password,mobilecode,type,code);
    }

    @RequestMapping(value = "/user/reset", method = RequestMethod.POST)
    public @ResponseBody
    JSONObject reset(
            @RequestParam(value="username",defaultValue="")String  username,
            @RequestParam(value="mobilecode",defaultValue="")String mobilecode,
            @RequestParam(value="password",defaultValue="")String  password
    ){
        return appPermissionService.reset(username,mobilecode,password);
    }

    @RequestMapping(value = "/user/authentication", method = RequestMethod.POST)
    public @ResponseBody ObjectRestResponse authentication(
            @RequestParam(value="userId",defaultValue="0")Integer  userId,
            @RequestParam(value="name",defaultValue="")String name,
            @RequestParam(value="idNumber",defaultValue="")String idNumber,
            @RequestParam(value="status",defaultValue="0")Integer  status
    ){
        return appPermissionService.upAuthentication(userId,name,idNumber,status);
    }

    /**
     * 通过用户id登录 unbelievable! ! !
     * @param userid
     * @return
     */
    @PostMapping("/applet/uid/login")
    public JSONObject appletLogin(@RequestParam(value = "userid") Integer userid){
        return appPermissionService.appletLoginByUserId(userid);
    }


    @PostMapping("/applet/registry")
    public JSONObject appletRegistry(
            @RequestParam(value="username",defaultValue="")String  username,
            @RequestParam(value="nickname",defaultValue="")String  nickname,
            @RequestParam(value="headimgurl",defaultValue="")String  headimgurl,
            @RequestParam(value="userid",defaultValue="0")Integer  userid
            ){
        if(StringUtils.isBlank(headimgurl)){
            headimgurl=SystemConfig.USER_HEADER_URL_DEFAULT;
        }
        if(StringUtils.isBlank(nickname)){
            nickname=SystemConfig.USER_NIKENAME_DEFAULT+(int)((Math.random()*9+1)*100000);
        }
        return appPermissionService.appletRegistry(username,headimgurl,nickname,userid);
    }

    @PostMapping("/imi/login")
    public String loginImiWithToken(){
       ServletRequestAttributes servletRequestAttributes  = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        try {
            IJWTInfo infoFromToken = authUtil.getInfoFromToken(userAuthConfig.getToken(request));
           return appPermissionService.loginImiWithUserId(Integer.valueOf(infoFromToken.getId()));
        } catch (Exception e) {
            throw new BaseException(e);
        }
    }

    @GetMapping("/imi/{imiId}")
   public ImiVo findUserInfoByImiId(@PathVariable(value = "imiId") Integer imiId){
        return appPermissionService.findUserInoByImiId(imiId);
    }

    @ApiModelProperty("检查手机号是否注册过")
    @GetMapping("/unauth/check")
    public ObjectRestResponse check(@RequestParam(value = "phone") String phone){
        if (StringUtils.isBlank(phone)){
            return ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE, "参数为空");
         }
           AppUserLogin rsUserLogin = appUserLoginBiz.checkeUserLogin(phone);
            if (rsUserLogin == null){
                return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "手机号未注册");
            }
        return ObjectRestResponse.succ();
}

    @ApiModelProperty("检查手机号验证码")
    @GetMapping("/unauth/checkMobilecode")
    public ObjectRestResponse checkMobilecode(@RequestParam(value = "phone") String phone,
                                              @RequestParam(value = "mobilecode") String mobilecode) {
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(mobilecode)) {
            return ObjectRestResponse.createFailedResult(ResultCode.NULL_CODE, "参数为空");
        }
        String redisKey = appPermissionService.checkCodeByUsername(phone, mobilecode);
        if (StringUtils.isBlank(redisKey)) {
            return ObjectRestResponse.createFailedResult(ResultCode.NOTEXIST_CODE, "验证码错误");
        }
        return ObjectRestResponse.succ();
    }

    @ApiModelProperty("修改手机号码")
    @GetMapping("/updUsername")
    public ObjectRestResponse updUsername(@RequestParam(value = "username") String username,
                                    @RequestParam(value = "mobilecode") String mobilecode,
                                    @RequestParam(value = "userId",defaultValue = "0") Integer userId){
        return appPermissionService.updUsername(userId,username,mobilecode);

    }


}
