package com.zcxk.controller;

import com.zcxk.dto.UserAuthDto;
import com.zcxk.exception.ServiceException;
import com.zcxk.model.LoginUser;
import com.zcxk.entity.User;
import com.zcxk.model.AjaxMessage;
import com.zcxk.model.ResultStatus;
import com.zcxk.service.UserService;

import com.zcxk.util.ByteArrayUtils;
import com.zcxk.util.RedisUtil;
import com.zcxk.util.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Optional;

/**
 * 用户(User)控制层
 *
 * @author makejava
 * @since 2020-10-21 15:23:47
 */
@RestController
@RequestMapping("/user")

@Api(tags = "用户接口")
public class UserController {
    /**
     * 服务对象
     */
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 登录
     *
     *
     *
     *
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ApiOperation(value = "登录")
    public AjaxMessage< User> login(String mobile, String tenatId) {
        User user=new User();
        user.setPhone(mobile);
        user.setTenantId(tenatId);
      ;
        User user2 = userService.chooseUser(user);
        if(user2==null){
            return new AjaxMessage<>(ResultStatus.ROLE_HAS_DISABLE);
        }

        return new AjaxMessage<>(ResultStatus.OK,user2);
    }
    /**
     * 退出
     *
     *
     *
     *
     */
    @RequestMapping(value = "logout", method = RequestMethod.POST)
    @ApiOperation(value = "退出")
    public AjaxMessage logout(String access_token) {

        if (userService.logOut(access_token)) {
            return new AjaxMessage<>(ResultStatus.OK);
        } else {
            return new AjaxMessage<>(ResultStatus.ERROR);
        }
    }
    @GetMapping("/info")
    @CrossOrigin(allowCredentials = "true")
    @ApiOperation(value = "用户信息")
    public AjaxMessage info() {
        LoginUser loginUser = UserUtil.getCurrentUser();
        return new AjaxMessage<>(ResultStatus.OK,loginUser);
    }

    @ApiIgnore
    @GetMapping("/principal")
    @ApiOperation(value = "各子系统获取用户信息接口")
    public Principal user(Principal principal,HttpServletRequest request)
    {
        LoginUser currentUser = UserUtil.getCurrentUser();
        Integer roleId = currentUser.getRoleId();
        String roleKey="disableRole:"+roleId;
        String companyKey="disableCompany:"+currentUser.getCompanyId();
        String departmentKey="department:"+currentUser.getDepartmentId();
        String userKey="disableUser:" + currentUser.getId();
        byte[] bytes = redisUtil.get(roleKey.getBytes());
        byte[] bytes2 = redisUtil.get(companyKey.getBytes());
        byte[] bytes3 = redisUtil.get(departmentKey.getBytes());
        byte[] bytes4 = redisUtil.get(userKey.getBytes());
        String authorization = request.getHeader("Authorization");
        String token =authorization.substring(authorization.indexOf("Bearer")+6).trim();
        String tokenKey = "offlineStatus:" + token;
        boolean flag=false;
        int status=0;
        if(bytes!=null){
            status=2;
            flag=true;
        }
        if(bytes2!=null){
            status=3;
            flag=true;
        }
        if((currentUser.getDepartmentId()!=null&&bytes3!=null)){
            status=4;
            flag=true;
        }
        if(bytes4!=null){
            status=5;
            flag=true;
        }
        if(flag){
            redisUtil.setExpire(tokenKey.getBytes(),
                    ByteArrayUtils.objectToBytes(status).get(), 1800);//15分钟过期
        }


        if(bytes!=null||bytes2!=null||(currentUser.getDepartmentId()!=null&&bytes3!=null)
        ||bytes4!=null){
            return null;
        }
        /*redisUtil.setExpire("auth:"+token,60000);
        redisUtil.setExpire("access:"+token,60000);*/
        return principal;
    }


    /**
     * 新增一条注册数据
     *
     * @param user 实体类
     * @return Response对象
     */
    @RequestMapping(value = "insertRegister", method = RequestMethod.POST)
    @ApiOperation(value = "插入注册申请")
    public AjaxMessage<Integer> insertRegister(@ApiParam(value = "注册申请信息", required = true) @RequestBody User user) {
        if(StringUtils.isEmpty(user.getUsername())||StringUtils.isEmpty(user.getPhone())||StringUtils.isEmpty(user.getUserType())) {
            return new AjaxMessage<>(ResultStatus.PARAM_ERROR);
        }
        int result = userService.insertRegister(user);
        return new AjaxMessage<>(ResultStatus.OK, result);
    }
    @RequestMapping(value = "getUserStatus", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户当前状态",notes = "返回0代表超时，1有其他用户登录了，其他用户被禁用")
    public AjaxMessage<Integer> getUserStatus(@ApiParam(value = "accessToken", required = true)@RequestParam String accessToken) {
       String key="offlineStatus:"+ accessToken;
        byte[] bytes = redisUtil.get(key.getBytes());
        int result=0;
        if(bytes!=null){
            Optional<Integer> status = ByteArrayUtils.bytesToObject(bytes);
            result=status.get();
        }
        return new AjaxMessage<>(ResultStatus.OK, result);
    }
    @RequestMapping(value = "getRangeCode", method = RequestMethod.GET)
    @ApiOperation(value = "获取登录随机code")
    public AjaxMessage<String> getRangeCode(@ApiParam(value = "appId", required = true)@RequestParam String appId) {
        String code=userService.getRangeCode(appId);
        return new AjaxMessage<String>(ResultStatus.OK, code);
    }


    /*@RequestMapping(value = "getUniqId", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户标识")
    public AjaxMessage<String> getUniqId(@ApiParam(value = "appId", required = true)@RequestParam String appId,
                                             @ApiParam(value = "APPSECRET", required = true)@RequestParam String appSecret,
                                         @ApiParam(value = "code", required = true)@RequestParam String code                                    ) {
        String uniqId=userService.getUniqId(appId,appSecret,code);
        return new AjaxMessage<String>(ResultStatus.OK, uniqId);
    }*/

    @RequestMapping(value = "getUniqId", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户标识")
    public AjaxMessage<UserAuthDto> getUniqId(@ApiParam(value = "appId", required = true)@RequestParam String appId,
                                                 @ApiParam(value = "key", required = true)@RequestParam String key) {
        try {
            UserAuthDto userAuthDto  = userService.getUniqId(appId, key);
            return new AjaxMessage<UserAuthDto>(ResultStatus.OK, userAuthDto);
        } catch (ServiceException e) {
            return new AjaxMessage<UserAuthDto>(e.getStatus(),e.getMessage(), null);
        }
    }

}