package com.bootdo.system.controller;

import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.constant.Constants;
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.domain.UserDO;
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("${sysProvince:#{null}}")
    public String sysProvince;

    @Value("${sysCity:#{null}}")
    public String sysCity;

    //登录地址
    @Value("${login_url:#{null}}")
    public String loginUrl;



    @Value("${oauth_permission_authentication.prefix:#{null}}")
    private String permAuthPrefix;
    @Value("${uniform_identity_authentication.appId:#{null}}")
    private String uniIdentAuthAppId;
    @Value("${logout.redirect_url:#{null}}")
    private String logoutRedirectUrl;



    @Autowired
    private SessionService sessionService;

    @Resource
    private TokenUtil tokenUtil;
    @Resource
    private RedisUtil redisUtil;

    @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");
        }
        UserDO currUser = ShiroUtils.getUser();
        logger.info("province:" + currUser.getProvince());
        logger.info("User:" + currUser.getDeptId() + ",deptName:" + currUser.getDeptName());
        model.addAttribute("username", currUser.getUsername());

        model.addAttribute("hiddenFlag", "");
        model.addAttribute("loadURl", "home");
        return "index_v1";
    }

    @GetMapping("/home")
    String home() {
        if("四川省".equals(sysProvince)){
            return "home_sichuan";
        } else if("湖南省".equals(sysProvince)){
            return "home_hunan";
        } else {
            return "error/404";
        }

    }

    @ResponseBody
    @GetMapping("/getLoginUrl")
    String getLoginUrl() {
        //return loginUrl;

        //获取当前登录账号信息
        UserDO currUser = ShiroUtils.getUser();

        if(!ObjectUtils.isEmpty(logoutRedirectUrl) && logoutRedirectUrl.contains("https")){
            //返回第三方退出登录接口
            //回调地址示例：https://testmicrosrv.scca.com.cn:9668/session/end?client_id=f104472f-02f4-6ab6-f6dc&access_token=HRMpcEUueorxSGQccNolRB2vkpaxnWHGvQonRtnoKEr3Z7KQthcUFz8jdaSD&logout_redirect_uri=http://124.70.58.209:19087/login
            String logoutRedirectBackUrl = permAuthPrefix + "/session/end" +
                    "?client_id=" + this.uniIdentAuthAppId +
                    "&access_token=" + redisUtil.hget(Constants.USERNAME_ACCESS_TOKEN, currUser.getUsername()) +
                    "&logout_redirect_uri=" + this.logoutRedirectUrl;
            logger.error("logoutRedirectBackUrl==============="+logoutRedirectBackUrl);
            return "redirect:" + logoutRedirectBackUrl;
        }else {
            return loginUrl;
        }
    }

    @GetMapping("/login")
    String login() {
        boolean bl = LicenseUtil.checkLicense();
        if (bl) {
            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";
        }

    }


    @GetMapping("/logout")
    String logout() {
        logger.error("logout======in==="+logoutRedirectUrl);

        //获取当前登录账号信息
        UserDO currUser = ShiroUtils.getUser();

        //正常退出
        try {
            sessionService.logout();
        } catch (Exception e){
            e.printStackTrace();
        }
        if(!ObjectUtils.isEmpty(logoutRedirectUrl) && logoutRedirectUrl.contains("http") && "四川省".equals(sysProvince)){
            //该路径只对四川省版本有效
            logger.error("logout======not null==="+logoutRedirectUrl);
            //返回第三方退出登录接口
            //回调地址示例：https://testmicrosrv.scca.com.cn:9668/session/end?client_id=f104472f-02f4-6ab6-f6dc&access_token=HRMpcEUueorxSGQccNolRB2vkpaxnWHGvQonRtnoKEr3Z7KQthcUFz8jdaSD&logout_redirect_uri=http://124.70.58.209:19087/login
            String logoutRedirectBackUrl = permAuthPrefix + "/session/end" +
                    "?client_id=" + this.uniIdentAuthAppId +
                    "&access_token=" + redisUtil.hget(Constants.USERNAME_ACCESS_TOKEN, currUser.getUsername()) +
                    "&logout_redirect_uri=" + this.logoutRedirectUrl;
            logger.error("logoutRedirectBackUrl========end======="+logoutRedirectBackUrl);
            return "redirect:" + logoutRedirectBackUrl;
        }else {
            logger.error("logout======is null==="+logoutRedirectUrl);
            return "redirect:" +  loginUrl;
        }

    }

    @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());
    }

}
