/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package cn.ysk.cashier.config.security.rest;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.ysk.cashier.config.security.config.bean.LoginCodeEnum;
import cn.ysk.cashier.config.security.security.TokenProvider;
import cn.ysk.cashier.pojo.shop.TbMerchantAccount;
import cn.ysk.cashier.pojo.shop.TbPlussShopStaff;
import cn.ysk.cashier.repository.shop.TbMerchantAccountRepository;
import cn.ysk.cashier.repository.shop.TbPlussShopStaffRepository;
import cn.ysk.cashier.utils.*;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import cn.ysk.cashier.annotation.Log;
import cn.ysk.cashier.annotation.rest.AnonymousDeleteMapping;
import cn.ysk.cashier.annotation.rest.AnonymousGetMapping;
import cn.ysk.cashier.annotation.rest.AnonymousPostMapping;
import cn.ysk.cashier.config.RsaProperties;
import cn.ysk.cashier.exception.BadRequestException;

import cn.ysk.cashier.config.security.config.bean.LoginProperties;
import cn.ysk.cashier.config.security.config.bean.SecurityProperties;
import cn.ysk.cashier.config.security.service.dto.AuthUserDto;
import cn.ysk.cashier.config.security.service.dto.JwtUserDto;
import cn.ysk.cashier.config.security.service.OnlineUserService;
import cn.ysk.cashier.pojo.shop.TbShopInfo;
import cn.ysk.cashier.repository.shop.TbShopInfoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author Zheng Jie
 * @date 2018-11-23
 * 授权、根据token获取用户详细信息
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Api(tags = "系统：系统授权接口")
public class AuthorizationController {
    private final SecurityProperties properties;
    private final RedisUtils redisUtils;
    private final OnlineUserService onlineUserService;
    private final TokenProvider tokenProvider;
    private final AuthenticationManagerBuilder authenticationManagerBuilder;
    private final TbShopInfoRepository tbShopInfoRepository;
    private final TbPlussShopStaffRepository staffRepository;
    private final TbMerchantAccountRepository tbMerchantAccountRepository;

    @Resource
    private LoginProperties loginProperties;

    @ApiOperation("登录授权")
    @AnonymousPostMapping(value = "/login")
    public ResponseEntity<Object> login(@Validated @RequestBody AuthUserDto authUser, HttpServletRequest request) throws Exception {
        // 密码解密
        String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, authUser.getPassword());
        // 查询验证码
        String code = (String) redisUtils.get(authUser.getUuid());
        // 清除验证码
        redisUtils.del(authUser.getUuid());
        if (authUser.isChecked() && StringUtils.isBlank(code)) {
            throw new BadRequestException("验证码不存在或已过期");
        }
        if (authUser.isChecked() && StringUtils.isBlank(authUser.getCode()) || authUser.isChecked() && !authUser.getCode().equalsIgnoreCase(code)) {
            throw new BadRequestException("验证码错误");
        }
        String loginpre="";
        String shopId="";
        // 判断是否是员工登录
        if (authUser.getLoginType() != null && "staff".equals(authUser.getLoginType())) {
            if (StrUtil.isBlank(authUser.getMerchantName())) {
                throw new BadRequestException("商户名称不能为空");
            }

            TbMerchantAccount merchant = tbMerchantAccountRepository.findByAccount(authUser.getMerchantName());
            if (merchant == null) {
                throw new BadRequestException("商户不存在");
            }
            loginpre = merchant.getShopId() + "@";
            shopId = merchant.getShopId();
        }

        //生成token
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginpre+authUser.getUsername(), password);
        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 生成令牌与第三方系统获取令牌方式
        // UserDetails userDetails = userDetailsService.loadUserByUsername(userInfo.getUsername());
        // Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        // SecurityContextHolder.getContext().setAuthentication(authentication);
        final JwtUserDto jwtUserDto = (JwtUserDto) authentication.getPrincipal();
//        TbShopInfo byAccount = tbShopInfoRepository.findByAccount(jwtUserDto.getUsername());
        TbPlussShopStaff tbPlussShopStaff;
        if (authUser.getLoginType() != null && "staff".equals(authUser.getLoginType())) {
            tbPlussShopStaff = staffRepository.queryByAccount(authUser.getUsername(),shopId);
        } else {
            tbPlussShopStaff = staffRepository.queryByAccount(authUser.getUsername());
        }
        if (tbPlussShopStaff != null && tbPlussShopStaff.getType().equals("staff")) {
            Integer isManage = tbPlussShopStaff.getIsManage();
            if (isManage != null && isManage != 1) {
                throw new BadRequestException("该账号无权限登录，请联系管理员");
            }

            Integer status = tbPlussShopStaff.getStatus();
            if (status != null && status != 1) {
                throw new BadRequestException("该账号已被禁用，请联系管理员");
            }
        }
        TbShopInfo byAccount = tbShopInfoRepository.findById(Integer.valueOf(tbPlussShopStaff.getShopId())).get();
        //校验商户商户激活是否到期（未激活）
        String token = tokenProvider.createToken(authentication, tbPlussShopStaff.getShopId());
        Map<String, Object> authInfo = new HashMap<String, Object>(2) {{
            put("token", properties.getTokenStartWith() + token);
            put("user", jwtUserDto);
            if (byAccount != null) {
                put("shopId", byAccount.getId());
                put("loginType", org.apache.commons.lang3.StringUtils.isNotBlank(authUser.getLoginType())?authUser.getLoginType():"merchant");
                put("shopName", byAccount.getShopName());
                put("logo", byAccount.getLogo());
            }

        }};
        // 保存在线信息
        onlineUserService.save(jwtUserDto, token, request, byAccount.getId());

        if (loginProperties.isSingleLogin()) {
            //踢掉之前已经登录的token
            onlineUserService.checkLoginOnUser(authUser.getUsername(), token);
        }
        return ResponseEntity.ok(authInfo);
    }

    /**
     * 小程序登录
     *
     * @param authUser
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/appletsLogin")
    public ResponseEntity<Object> appletsLogin(@RequestBody AuthUserDto authUser, HttpServletRequest request) throws Exception {
        // 密码解密
        String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, authUser.getPassword());

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(authUser.getUsername(), password);
        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        final JwtUserDto jwtUserDto = (JwtUserDto) authentication.getPrincipal();
        // 返回 token 与 用户信息
        TbShopInfo byAccount = tbShopInfoRepository.findByAccount(jwtUserDto.getUsername());
        // 生成令牌与第三方系统获取令牌方式
        String token = tokenProvider.createToken(authentication, byAccount.getId().toString());
        // 保存在线信息
        onlineUserService.save(jwtUserDto, token, request, null);
        Map<String, Object> authInfo = new HashMap<String, Object>(2) {{
            put("token", properties.getTokenStartWith() + token);
            put("user", jwtUserDto);
            if (byAccount != null) {
                put("shopId", byAccount.getId());
            }

        }};
        if (loginProperties.isSingleLogin()) {
            //踢掉之前已经登录的token
            onlineUserService.checkLoginOnUser(authUser.getUsername(), token);
        }
        return ResponseEntity.ok(authInfo);
    }

    @ApiOperation("获取用户信息")
    @GetMapping(value = "/info")
    public ResponseEntity<Object> getUserInfo() {
        return ResponseEntity.ok(SecurityUtils.getCurrentUser());
    }

    @ApiOperation("获取验证码")
    @AnonymousGetMapping(value = "/code")
    public ResponseEntity<Object> getCode() {
        // 获取运算的结果
        Captcha captcha = loginProperties.getCaptcha();
        String uuid = properties.getCodeKey() + IdUtil.simpleUUID();
        //当验证码类型为 arithmetic时且长度 >= 2 时，captcha.text()的结果有几率为浮点型
        String captchaValue = captcha.text();
        if (captcha.getCharType() - 1 == LoginCodeEnum.ARITHMETIC.ordinal() && captchaValue.contains(".")) {
            captchaValue = captchaValue.split("\\.")[0];
        }
        // 保存
        redisUtils.set(uuid, captchaValue, loginProperties.getLoginCode().getExpiration(), TimeUnit.MINUTES);
        // 验证码信息
        Map<String, Object> imgResult = new HashMap<String, Object>(2) {{
            put("img", captcha.toBase64());
            put("uuid", uuid);
        }};
        return ResponseEntity.ok(imgResult);
    }

    @ApiOperation("设置验证码")
    @AnonymousGetMapping(value = "/setCode")
    public ResponseEntity<Object> setCode(@RequestParam String uuid, @RequestParam String code) {
        // 保存
        redisUtils.set(uuid, code, loginProperties.getLoginCode().getExpiration(), TimeUnit.MINUTES);
        return ResponseEntity.ok("ok");
    }

    @ApiOperation("退出登录")
    @AnonymousDeleteMapping(value = "/logout")
    public ResponseEntity<Object> logout(HttpServletRequest request) {
        onlineUserService.logout(tokenProvider.getToken(request));
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
