package com.pine.admin.modules.system.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.pine.admin.modules.system.service.SysService;
import com.pine.admin.modules.system.service.SysUserRoleService;
import com.pine.admin.shiro.DealerOpenIdToken;
import com.pine.admin.shiro.ShiroUserInfo;
import com.pine.admin.shiro.ShiroUtils;
import com.pine.common.dto.Result;
import com.pine.common.exception.ApiException;
import com.pine.common.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(value = "A管理员登陆", tags = {"A管理员登陆"})
@RestController
@Slf4j
public class SysUserLoginController {


    @Autowired
    private SysService sysService;

    @GetMapping("/getIp")
    public Result getIp(HttpServletRequest request) {
        return Result.success(true, IpUtil.getIpAddr(request));
    }

    @PostMapping("/secretLogin")
    public Result secretLogin(@RequestParam(value = "casualBacking")String  casualBacking) {
        try {

//            String casualBacking = request.getParameter("casualBacking");
//            String ip = request.getParameter("ips");
            log.info("ip:"+casualBacking);
//            String responseString = sysService.decryptUser(ips, casualBacking);
            String responseString = sysService.decryptUser(casualBacking.split("@@")[1], casualBacking.split("@@")[0]);

            DealerOpenIdToken dealerOpenIdToken;

            dealerOpenIdToken = new DealerOpenIdToken(responseString);

            Subject subject = SecurityUtils.getSubject();

            subject.login(dealerOpenIdToken);

            SecurityUtils.getSubject().getSession().setTimeout(-1000L);

            return Result.success(true, ShiroUtils.getShiroUserInfo());
        } catch (UnknownAccountException e) {
            return Result.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return Result.error("账号或密码不正确");
        } catch (LockedAccountException e) {
            return Result.error("账号已被锁定,请联系管理员");
        } catch (AuthenticationException e) {
            return Result.error("账户验证失败");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(e.getMessage());
        }
    }


    @PostMapping("login")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "用户名", example = "xxs2", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", example = "123456", required = true, dataType = "string", paramType = "query")
//            @ApiImplicitParam(name = "rand", value = "验证码", example = "a",required = true, dataType = "string", paramType = "query")
    })
    public Result dealerLogin(@RequestParam(value = "userCode") String userCode, @RequestParam(value = "password") String password) {
        try {
            DealerOpenIdToken dealerOpenIdToken = sysService.dealerLogin(userCode, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(dealerOpenIdToken);
            SecurityUtils.getSubject().getSession().setTimeout(-1000L);
            return Result.success(true, ShiroUtils.getShiroUserInfo());
            //            Subject subject = ShiroUtils.getSubject();
//            UsernamePasswordToken token = new UsernamePasswordToken(userCode, password);
//            subject.login(token);


        } catch (UnknownAccountException e) {
            return Result.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return Result.error("账号或密码不正确");
        } catch (LockedAccountException e) {
            return Result.error("账号已被锁定,请联系管理员");
        } catch (AuthenticationException e) {
            return Result.error("账户验证失败");
        } catch (Exception e) {
            log.info(e.getMessage());
            throw new ApiException(e.getMessage());
        }
    }

    /**
     * 退出
     */
    @PostMapping(value = "logout")
    public Result logout() {
        String username = ShiroUtils.getShiroUserInfo().getName();
        ShiroUtils.logout();
        return Result.success(true, "用户:" + username + "退出登录成功");
    }

    /**
     * error
     */
    @RequestMapping(value = "error", method = RequestMethod.GET)
    public Result error() {
        return Result.error("系统出错");
    }

}
