package im.zhaojun.system.controller;

import cn.hutool.core.util.IdUtil;
import im.zhaojun.common.annotation.OperationLog;
import im.zhaojun.common.shiro.ShiroActionProperties;
import im.zhaojun.common.util.CaptchaUtil;
import im.zhaojun.common.util.DateUtils;
import im.zhaojun.common.util.ResultBean;
import im.zhaojun.system.model.ResultObj;
import im.zhaojun.system.model.User;
import im.zhaojun.system.service.MailService;
import im.zhaojun.system.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.thymeleaf.TemplateEngine;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

@Controller
public class LoginController {

    @Resource
    private UserService userService;


    @Resource
    private TemplateEngine templateEngine;

    @Resource
    private ShiroActionProperties shiroActionProperties;


    @Autowired
    private RestTemplate restTemplate;


    @GetMapping(value = { "/","/login"})
    public String login(Model model) {
        model.addAttribute("loginVerify", shiroActionProperties.getLoginVerify());
        return "login";
    }

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @PostMapping("/login")
    @ResponseBody
    public ResultBean login(User user, @RequestParam(value = "captcha", required = false) String captcha,HttpServletResponse response) {
        Subject subject = SecurityUtils.getSubject();


        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        subject.login(token);
        userService.updateLastLoginTimeByUsername(user.getUsername(), DateUtils.dateTimeNow("YYYY/MM/dd HH:mm:ss"));
        //查询用户操作权限一级菜单
        User cuser= userService.selectOneByUserName(user.getUsername());
        return ResultBean.success(cuser);
    }

    @OperationLog("注销")
    @GetMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:login";
    }

    @PostMapping("/register")
    @ResponseBody
    public ResultBean register(User user) {
        userService.checkUserNameExistOnCreate(user.getUsername());
        String activeCode = IdUtil.fastSimpleUUID();
        user.setActiveCode(activeCode);
        user.setStatus("0");

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        String url = request.getScheme() + "://"
//                + request.getServerName()
//                + ":"
//                + request.getServerPort()
//                + "/active/"
//                + activeCode;
//        Context context = new Context();
//        context.setVariable("url", url);
//        String mailContent = templateEngine.process("mail/registerTemplate", context);
//        new Thread(() ->
//                mailService.sendHTMLMail(user.getEmail(), "Shiro-Action 激活邮件", mailContent))
//                .start();

        // 注册后默认的角色, 根据自己数据库的角色表 ID 设置
        Integer[] initRoleIds = {2};
        return ResultBean.success(userService.add(user, initRoleIds));
    }

    @GetMapping("/captcha")
    public void captcha(HttpServletResponse response) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CaptchaUtil.Captcha captcha = CaptchaUtil.createCaptcha(140, 38, 4, 10, 30);
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("captcha", captcha.getCode());

        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(captcha.getImage(), "png", os);
    }

    @OperationLog("激活注册账号")
    @GetMapping("/active/{token}")
    public String active(@PathVariable("token") String token, Model model) {
        User user = userService.selectByActiveCode(token);
        String msg;
        if (user == null) {
            msg = "请求异常, 激活地址不存在!";
        } else if ("1".equals(user.getStatus())) {
            msg = "用户已激活, 请勿重复激活!";
        } else {
            msg = "激活成功!";
            user.setStatus("1");
            userService.activeUserByUserId(user.getUserId());
        }
        model.addAttribute("msg", msg);
        return "active";
    }


    @OperationLog("用户账号查询权限")
    @PostMapping("/firstmenu")
    @ResponseBody
    public ResultBean firstmenu(String username) {
        if (null!=username && shiroActionProperties.getSuperAdminUsername().equals(username)) {
            username = null;
            return ResultBean.success(userService.selectUserFirstMenu(username));
        }
        else if(null!=username) {
            return ResultBean.success(userService.selectUserFirstMenu(username));
        }
        return ResultBean.success();
    }

    @OperationLog("用户账号查询权限")
    @PostMapping("/secondmenu")
    @ResponseBody
    public ResultBean firstmenu(Integer menuid,String username) {
        if (null!=username && shiroActionProperties.getSuperAdminUsername().equals(username)) {
            username = null;
            return ResultBean.success(userService.selectUserSecondMenu(menuid,username));
        }
        else if(null!=username) {
            return ResultBean.success(userService.selectUserSecondMenu(menuid,username));
        }

        return ResultBean.success();
    }


    /**
     * 事件推送测试模拟接口
     *
     * @return 推送结果
     */
    @RequestMapping("/test")
    public ResultObj test() {
        String message = "{\n" +
                "    \"type\": \"TRAFFIC_INCIDENT_ALARM\",\n" +
                "    \"id\": \"d9a2b0f0-f0cf-49b9-9b64-3da86a122afa\",\n" +
                "    \"video_id\": \"20200305112027144_0\",\n" +
                "    \"ts\": \"1609310601820\",\n" +
                "    \"incident_type\": \"no_motor_ban\",\n" +
                "    \"img_urls\": [\n" +
                "      \"http://33.57.1.22:8001/api/alg/files/1605126187-20200619143331241059_0-627?location=\",\n" +
                "      \"http://33.57.1.22:8001/api/alg/files/1605126187-20200619143331241059_0-627?location=\",\n" +
                "      \"http://33.57.1.22:8001/api/alg/files/1605126187-20200619143331241059_0-627?location=\",\n" +
                "      \"http://33.57.1.22:8001/api/alg/files/1605126187-20200619143331241059_0-627?location=\",\n" +
                "      \"http://33.57.1.22:8001/api/alg/files/1605126187-20200619143331241059_0-627?location=\"\n" +
                "    ],\n" +
                "    \"video_record_url\": \"http://33.57.1.22:8001/api/alg/files/1605126187-20200619143331241059_0-627?location=\",\n" +
                "    \"obj_location\": {\n" +
                "        \"x\": 0.1,\n" +
                "        \"y\": 0.2,\n" +
                "        \"width\": 0.4,\n" +
                "        \"height\": 0.7\n" +
                "    },\n" +
                "    \"img_base64\": [\"d0xEMHcFAESwdwaUjWDqB6/1Qw4LapAiSICVTOFWsGT0sgt\"]\n" +
                "}";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> requestEntity = new HttpEntity<>(message, headers);
        return restTemplate.postForObject("http://localhost:" + 8089 + "/alarmevent", requestEntity, ResultObj.class);
    }



}
