package com.sw.mes.auth.controller;

/**
 * @Author wudanjun
 * @Description：
 * @Date: Create in 22:22 2018/4/6
 * @Modified By:
 */

import com.sw.mes.auth.config.JinkoSSOConfig;
import com.sw.mes.auth.domain.AuthUser;
import com.sw.mes.auth.service.AuthPermissionService;
import com.sw.mes.auth.service.AuthUserService;
import com.sw.mes.core.annotation.TokenNotValidation;
import com.sw.mes.core.constant.Constants;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.auth.utils.PasswordUtil;
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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/auth")
@Slf4j
@Api(description = "登录相关接口")
public class AuthController {
    @Autowired
    private AuthUserService authUserService;

    @Autowired
    private AuthPermissionService authPermissionService;

    /**
     *
     * @param loginName 登录名
     * @param password  用户密码
     * @param clientType 登录设备端类型
     * @param teamGroup 班组
     * @param classNo 班次
     * @return
     */
    @ApiOperation(value = "登录接口")
    @PostMapping("/login")
    public Result<String> login(@RequestParam(required = false) String loginName,
                                @RequestParam(required = false) String password,
                                @RequestParam(required = false) String clientType,
                                @RequestParam(required = false) String teamGroup,
                                @RequestParam(required = false) String classNo) {
        if (StringUtils.isEmpty(loginName)) {
            return ResultGenerator.fail("用户名为空！");
        }
        if (StringUtils.isEmpty(password)) {
            return ResultGenerator.fail("密码为空！");
        }
        return authUserService.login(loginName, password, clientType, teamGroup, classNo);
    }

    @ApiOperation(value = "修改密码(用户使用)")
    @ApiImplicitParams({@ApiImplicitParam(name = "oldPassword", value = "旧密码", dataType = "integer", paramType = "query", required = false, readOnly = false), @ApiImplicitParam(name = "newPassword", value = "新密码", dataType = "integer", paramType = "query", required = false, readOnly = false),})
    @PostMapping("/updatePassword")
    public Result<String> updatePassword(String oldPassword, String newPassword) {
        if (StringUtils.isEmpty(newPassword)) {
            return ResultGenerator.fail("新密码不能为空");
        }
        AuthUser user = authUserService.getById(BaseContextHandler.getUserID());
        try {
            //验证旧的密码是否正确
            boolean checkPassword = PasswordUtil.validatePassword(oldPassword, user.getPassword(), user.getSalt());
            if (!checkPassword) {
                return ResultGenerator.fail("旧密码输入错误");
            }
            PasswordUtil.HashPassword hashPassword = PasswordUtil.encryptPassword(newPassword);
            user.setSalt(hashPassword.salt);
            user.setPassword(hashPassword.password);
            if (Constants.USER_ORIGINAL.equals(user.getStatus())) {
                user.setStatus(Constants.USER_ENABLE);
            }
            authUserService.saveOrUpdate(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultGenerator.success("密码重置成功");
    }

    @PostMapping("/sso/callback")
    @TokenNotValidation
    public Result<String> callback() {
        return ResultGenerator.success(JinkoSSOConfig.composeAuthorization());
    }

    /**
     * @param code
     * @return Map<String, String>
     * key1:uid
     * key2:token header中的token
     * key3:jk_token 晶科sso返回的token
     */
    @PostMapping("/sso/access_token/{code}")
    @TokenNotValidation
    public Result<Map<String, String>> accessToken(@PathVariable("code") String code) {
        return JinkoSSOConfig.accessToken(code);
    }

}
