package com.yanzhu.wechat.controller;

import com.yanzhu.common.annotation.Anonymous;
import com.yanzhu.common.annotation.Log;
import com.yanzhu.common.annotation.RateLimiter;
import com.yanzhu.common.constant.Constants;
import com.yanzhu.common.core.controller.BaseController;
import com.yanzhu.common.core.domain.AjaxResult;
import com.yanzhu.common.core.domain.entity.SysDept;
import com.yanzhu.common.core.domain.entity.SysUser;
import com.yanzhu.common.core.domain.model.LoginBody;
import com.yanzhu.common.core.domain.model.LoginUser;
import com.yanzhu.common.core.redis.RedisCache;
import com.yanzhu.common.core.text.Convert;
import com.yanzhu.common.enums.BusinessType;
import com.yanzhu.common.enums.LimitType;
import com.yanzhu.common.enums.OperatorType;
import com.yanzhu.common.exception.ServiceException;
import com.yanzhu.framework.web.service.SysLoginService;
import com.yanzhu.framework.web.service.SysPermissionService;
import com.yanzhu.framework.web.service.TokenService;
import com.yanzhu.system.domain.vo.UpdatePwdVo;
import com.yanzhu.system.service.ISysDeptService;
import com.yanzhu.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
import java.util.Objects;

/**
 * @version : V1.0
 * @ClassName: LoginController
 * @Description: 用户登录
 * @Auther: JiangYuQi
 * @Date: 2020/7/7 18:03
 */
@RestController
@RequestMapping("/wxApi")
public class WxLoginController extends BaseController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation(value = "账号密码登录")
    @RateLimiter(count = 10, limitType = LimitType.IP)
    @Anonymous
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),loginBody.getUuid());
        // 移动端这里刷新token有效期为长期
        tokenService.refreshMobileToken(token);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 用户修改密码
     *
     * @return 结果
     */
    @ApiOperation(value = "修改密码")
    @RateLimiter(count = 10, limitType = LimitType.IP)
    @Log(title = "用户修改密码", businessType = BusinessType.UPDATE, operatorType = OperatorType.MOBILE)
    @PostMapping("/updatePwd")
    public AjaxResult updatePwd(@RequestBody @Valid UpdatePwdVo updatePwdVo)
    {
        sysUserService.updatePwd(updatePwdVo);
        return success();
    }

    /**
     * 用户退出登录
     *
     * @return 结果
     */
    @ApiOperation(value = "退出登录")
    @RateLimiter(count = 10, limitType = LimitType.IP)
    @Log(title = "用户退出登录", businessType = BusinessType.UPDATE, operatorType = OperatorType.MOBILE)
    @GetMapping("/loginOut")
    public AjaxResult loginOut(HttpServletRequest request)
    {
        tokenService.delLoginUser(request);
        return success();
    }

    /**
     * 刷线用户信息
     *
     * @return 结果
     */
    @ApiOperation(value = "刷线用户信息")
    @RateLimiter(count = 10, limitType = LimitType.IP)
    @GetMapping("/refreshUserInfo")
    public AjaxResult refreshUserInfo(HttpServletRequest request)
    {
        SysUser user = sysUserService.selectUserByUserName(super.getUsername());
        if(Objects.isNull(user)){
            throw new ServiceException("用户信息异常...");
        }
        //设置项目单位信息
        if(!user.isAdmin()){
            //判断是否是段队管理员
            String[] ancestors = user.getDept().getAncestors().split(",");
            Long deptId = Convert.toLong(ancestors[ancestors.length-1]);
            if(deptId != null){
                SysDept sysDept = sysDeptService.selectDeptById(deptId);
                user.setParDeptId(sysDept.getDeptId());
                user.setParDeptName(sysDept.getDeptName());
            }
        }else{
            user.setParDeptId(100L);
            user.setParDeptName("中铁建设集团有限公司");
        }
        LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
        tokenService.refreshUserInfo(tokenService.getToken(request),loginUser);
        return success();
    }

}
