package cn.wisenergy.web.admin.controller.app;

import cn.wisenergy.common.enums.ResultEnum;
import cn.wisenergy.common.utils.*;
import cn.wisenergy.web.sms.*;
import cn.wisenergy.model.app.User;
import cn.wisenergy.model.app.UsersDto;
import cn.wisenergy.service.app.UserService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 *
 * Created by m1991 on 2021/3/2 13:35
 */
@Api(tags = "登录/注册")
@Slf4j
@RequestMapping("/api/user")
@RestController
public class LoginController {
        @Autowired
        private RedisUtils redisUtils;

        @Autowired
        private UserService usersService;

//        @Autowired
//        private Result result;

    /**
     * 手机登录接口
     * @param userId
     * @param sms
     * @return
     * @throws Exception
     */

    @ApiOperation(value = "登录", notes = "登录", httpMethod = "POST", produces = "application/json;charset=UTF-8")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sms", value = "验证码", dataType = "String"),
            @ApiImplicitParam(name = "userId", value = "用户手机号", required = true, dataType = "String")})
        @RequestMapping("/login")
        public Result loginBySms(String userId, String sms)throws Exception{
            User users=null;
            String key= StringUtil.formatKeyWithPrefix(Constants.RedisKey.PROJECT_PRIFIX,Constants.RedisKey.SMS_PRIFIX,userId,Constants.Sms.CodeType.LOGIN_OR_REGISTER+"");
            String redisCode=redisUtils.getValue(key);
            if(StringUtil.isBlank(redisCode) || !sms.equals(redisCode)){
                throw new BaseException(ResultEnum.FAIL_VERIFY);
            }
            redisUtils.delete(key);
            //根据手机号判断用户是否存在
            //不存在则保存用户信息--修改为提示用户注册
            users=usersService.queryUsersByPhone(userId);

            if(null==users){
                throw new BaseException(ResultEnum.FAIL_ACCOUNT_NOT_EXIST);
//                users=new User();
//                users.setUserId(userId);
//                usersService.qdtxAddUsers(users);;

            }
            String token=createToken(users);
            if(!StringUtil.isBlank(token)){
                return ResultUtils.returnDataSuccess(StringUtil.createSimpleMap("token",token));
            }
            return ResultUtils.returnFail();
        }

        public String createToken(User users)throws Exception{
            String token=StringUtil.createToken();
            //保存token
            String tokenKey=StringUtil.formatKeyWithPrefix(Constants.RedisKey.PROJECT_PRIFIX,Constants.RedisKey.TOKEN_PRIFIX,token);
            UsersDto usersDto=new UsersDto();
            BeanUtils.copyProperties(users,usersDto);
            redisUtils.set(tokenKey, JSONObject.toJSONString(usersDto),Constants.Duration.HALF_HOUR_INT);
            return token;
        }


        @ApiOperation(value = "获取用户登录token信息", notes = "获取用户登录token信息", httpMethod = "POST", produces = "application/json; charset=UTF-8")
        @RequestMapping("/info")
        public Result info(HttpServletRequest request)throws Exception{
            String token=request.getHeader("token");
            String tokenKey=StringUtil.formatKeyWithPrefix(Constants.RedisKey.PROJECT_PRIFIX,Constants.RedisKey.TOKEN_PRIFIX,token);
            String userDtoJson=redisUtils.getValue(tokenKey);
            if(StringUtil.isBlank(userDtoJson)){
                throw new BaseException(ResultEnum.FILE_NOT_LOGIN);
            }
            UsersDto usersDto=JSONObject.parseObject(userDtoJson,UsersDto.class);
            usersDto.setPassword(null);
            return ResultUtils.returnDataSuccess(userDtoJson);
        }
        //用户注册
        @ApiOperation(value = "用户注册", notes = "用户注册", httpMethod = "POST", produces = "application/json; charset=UTF-8")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "userId", value = "用户手机号", required = true, dataType = "String"),
                @ApiImplicitParam(name = "beInvitedCode", value = "推荐人邀请码", required = false, dataType = "String"),
                @ApiImplicitParam(name = "sms", value = "验证码",required = true, dataType = "String")
                })
        @RequestMapping("/register")
        public Map register(@RequestParam String userId, String beInvitedCode, @RequestParam String sms)throws Exception {
            User users=null;
            String key= StringUtil.formatKeyWithPrefix(Constants.RedisKey.PROJECT_PRIFIX,Constants.RedisKey.SMS_PRIFIX,userId,Constants.Sms.CodeType.LOGIN_OR_REGISTER+"");
            String redisCode=redisUtils.getValue(key);
            if(StringUtil.isBlank(redisCode) || !sms.equals(redisCode)){
                throw new BaseException(ResultEnum.FAIL_VERIFY);
            }
            redisUtils.delete(key);
            //判断phone是否符合输入类型
            if(!userId.matches(Constants.RegConstant.PHONE_REGSTR)){
                throw new BaseException(ResultEnum.PHONE_ERROR);
            }

//            if(userId.equals())){
//                throw new BaseException(ResultEnum.PHONE_ERROR);
//            }

            return usersService.userByZx(userId,beInvitedCode);
            }

    }

