package com.bootdo.system.controller;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.config.ThirdPartSsoConfig;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.domain.Tree;
import com.bootdo.common.service.FileService;
import com.bootdo.common.token.Payload;
import com.bootdo.common.token.Token;
import com.bootdo.common.token.TokenUtil;
import com.bootdo.common.utils.*;
import com.bootdo.system.domain.MenuDO;
import com.bootdo.system.service.MenuService;
import com.bootdo.system.service.SessionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

@Controller
public class LoginController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    MenuService menuService;
    @Autowired
    FileService fileService;
    @Autowired
    BootdoConfig bootdoConfig;

    @Value("${managerValue}")
    public String managerValue;

    /**
     * sso相关配置
     */
    @Autowired
    private ThirdPartSsoConfig thirdPartSsoConfig;

    @Autowired
    private SessionService sessionService;


    @Resource
    private TokenUtil tokenUtil;

    @GetMapping({"/", ""})
    String welcome(Model model) {
        boolean bl = LicenseUtil.checkLicense();
        if (bl) {
            return "redirect:/login";
        } else {
            return "redirect:/checkLicense";
        }

    }

    @Log("请求访问主页")
    @GetMapping({"/index"})
    String index(@RequestParam("sysFlag") String sysFlag, Model model) {
        List<Tree<MenuDO>> menus = menuService.listMenuTree(sysFlag,getUserId());
        model.addAttribute("menus", menus);
        model.addAttribute("name", getUser().getName());
        FileDO fileDO = fileService.get(getUser().getPicId());
        if (fileDO != null && fileDO.getUrl() != null) {
            if (fileService.isExist(fileDO.getUrl())) {
                model.addAttribute("picUrl", "/img/photo_s.png");
            } else {
                model.addAttribute("picUrl", "/img/photo_s.png");
            }
        } else {
            model.addAttribute("picUrl", "/img/photo_s.png");
        }
        logger.info("province:" + getUser().getProvince());
        logger.info("User:" + getUser().getDeptId() + ",deptName:" + getUser().getDeptName());
        model.addAttribute("username", getUser().getUsername());
        if (!managerValue.contains(getUser().getDeptId().toString())) {
            logger.info("地方主管部门");
            model.addAttribute("loadURl", "dashboard-2");
            //隐藏操作手册标识
            model.addAttribute("hiddenFlag", "");
        } else {
            logger.info("工信部 系统管理员");
            model.addAttribute("loadURl", "dashboard-1");
            //隐藏操作手册标识
            model.addAttribute("hiddenFlag", "hidden");
        }
        return "index_v1";
    }

    // "dashboard/dashboard-1"; //工信部
    // "dashboard/dashboard-2"; //地方主管部门
    @GetMapping("/dashboard-1")
    String dashboard1() {
        return "dashboard/dashboard-1";
    }

    @GetMapping("/dashboard-2")
    String dashboard2() {
        return "dashboard/dashboard-2";
    }

    @GetMapping("/login")
    String login() {
        boolean bl = LicenseUtil.checkLicense();
        if (bl) {
            if (thirdPartSsoConfig.getSwitchFlag()) {
                return "redirect:" + thirdPartSsoConfig.getSsoRedirectUrl();
            }
            return "login";
        } else {
            return "checkLicense";
        }
    }

    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
    R ajaxLogin(String username, String password, String verify, HttpServletRequest request) {

        try {
            // 从session中获取随机数
            String random = (String)request.getSession().getAttribute(RandomValidateCodeUtil.RANDOMCODEKEY);
            if (StringUtils.isBlank(verify)) {
                return R.error("请输入验证码");
            }
            if (random.equalsIgnoreCase(verify)) {
            }
//            else if ("6666".equals(verify)) {
//            }
            else {
                return R.error("请输入正确的验证码");
            }
        } catch (Exception e) {
            logger.error("验证码校验失败", e);
            return R.error("验证码校验失败");
        }
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);

            return R.ok();
        } catch (Exception e) {
            return R.error("用户或密码错误");
        }
    }

    @Log("单点登录")
    @GetMapping("/ssoLogin")
    String ssoLogin(String token) {
        try {
            if(ObjectUtils.isEmpty(token)){
                throw new Exception("token不能为空");
            }

            Token tokenObj = tokenUtil.getToken(token);
            if(ObjectUtils.isEmpty(tokenObj) || !tokenUtil.verifyToken(tokenObj)){
                throw new Exception("token无效");
            }
            Payload payload = tokenObj.getPayload();
            String username = payload.getUsername();
            String password = payload.getPassword();

            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);
            return "ssoLogin";
        } catch (Exception e) {
            e.printStackTrace();
            return "login";
        }

    }

    /**
     * 获取当前token
     */
    @GetMapping(value = "/getCurrToken")
    @ResponseBody
    public String getCurrToken() {
        try {
           return tokenUtil.createCurrTokenString();
        } catch (Exception e) {
            logger.error("获取当前token失败>>>> ", e);
            return null;
        }
    }

    @GetMapping("/logout")
    String logout() {
        try {
            sessionService.logout();
        } catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:/login";
    }

    @GetMapping("/main")
    String main() {
        return "main";
    }

    /**
     * 生成验证码
     */
    @GetMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);// 输出验证码图片方法
        } catch (Exception e) {
            logger.error("获取验证码失败>>>> ", e);
        }
    }

    @GetMapping("/code")
    @ResponseBody
    boolean code() {
        return !Objects.isNull(ShiroUtils.getUser());
    }

}
