package com.sysu.admin.controller;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.sysu.admin.support.shiro.ShiroToken;
import com.sysu.admin.support.system.menu.SMenuService;
import com.sysu.admin.support.system.role.SRoleRepository;
import com.sysu.admin.support.system.role_permission.RolePermissionService;
import com.sysu.admin.support.system.user.User;
import com.sysu.admin.support.system.user.UserRepository;
import com.sysu.admin.support.system.user_role.UserRole;
import com.sysu.admin.support.system.user_role.UserRoleRepository;
import com.sysu.admin.utils.i18n.MessageUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiesx.fastboot.base.result.BaseResult;
import com.xiesx.fastboot.base.result.R;
import com.sysu.admin.support.base.ServiceContext;

/**
 * @title MainController
 * @description
 * @author XIE
 * @date 2020年4月24日下午10:08:06
 */
@Controller
public class MainController extends ServiceContext {

    @Autowired
    SMenuService mMenuService;
    @Autowired
    UserRepository mUserRepository;
    @Autowired
    UserRoleRepository mUserRoleRepository;
    @Autowired
    SRoleRepository mSRoleRepository;
    @Autowired
    RolePermissionService mRolePermissionService;
    @Autowired
    ServletContext servletContext;


    /**
     * 登录页
     * @return
     */
    @RequestMapping(value = "/")
    public String index() {
        if(mShiroService.isAuthenticated()){
            return admin();
        }
        return "comm/login";
    }


    /**
     * 登录页
     * @return
     */
    @RequestMapping(value = "/login")
    public String login() {
        return "comm/login";
    }

    /**
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/init")
    public BaseResult init() {
        int row = 0;
        List<User> list = mUserRepository.findAll();
        for (User user : list) {
            String password = DigestUtils.md5Hex(user.getUsername() + "123456");
            user.setPassword(password);
            row = row + mUserRepository.insertOrUpdate(user);
        }
        return R.succ(row);
    }


    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @param returnUrl
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/admin/login")
    public BaseResult login(HttpServletRequest request, String username, String password, @RequestParam("redirect_url") String returnUrl) {
        try {
            // 密码加密
            password = DigestUtils.md5Hex(username + password);
            // 创建用户验证身份令牌
            ShiroToken token = new ShiroToken(username, password);
            SecurityUtils.getSubject().login(token);
            // 重定向路径
            if (StringUtils.isEmpty(returnUrl)) {
                returnUrl = request.getContextPath() + "/admin2";
            }
            // 登录成功
            return R.succ(BaseResult.SUCCESS, MessageUtils.get("main.loginSuccess"), returnUrl);
        } catch (UnsupportedTokenException e) {
            return R.fail(MessageUtils.get("main.vcode_error"));
        } catch (UnknownAccountException e) {
            return R.fail(MessageUtils.get("main.u_and_p_error"));
        } catch (IncorrectCredentialsException e) {
            return R.fail(MessageUtils.get("main.u_and_p_error"));
        } catch (ExcessiveAttemptsException e) {
            return R.fail(MessageUtils.get("main.failed_login_times"));
        } catch (LockedAccountException e) {
            return R.fail(MessageUtils.get("main.locked"));
        } catch (DisabledAccountException e) {
            return R.fail(MessageUtils.get("main.disabled"));
        }
    }

    /**
     * 注销登录
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/admin/logout")
    public BaseResult logout(HttpServletRequest request) {
        // shiro 退出
        SecurityUtils.getSubject().logout();
        // session 失效
        request.getSession().invalidate();
        return R.succ();
    }

    /**
     * 管理页
     *
     * @return
     */
    @RequestMapping(value = "/admin")
    public String admin() {
        return "comm/admin";
    }

    /**
     * 管理页
     *
     * @return
     */
    @RequestMapping(value = "/admin2")
    public String admin2(Model model) {
        String vector_wmts = mSConfigService.getV("vector_wmts");
        String img_wmts = mSConfigService.getV("img_wmts");
        String qyz = mSConfigService.getV("qyz");
        String qysdcj = mSConfigService.getV("qysdcj");
        String ext1 = mSConfigService.getV("ext1");
        String ext2 = mSConfigService.getV("ext2");
        String ext3 = mSConfigService.getV("ext3");
        String ext4 = mSConfigService.getV("ext4");

        model.addAttribute("vector_wmts",vector_wmts);
        model.addAttribute("img_wmts",img_wmts);
        model.addAttribute("qyz",qyz);
        model.addAttribute("qysdcj",qysdcj);
        model.addAttribute("ext1",ext1);
        model.addAttribute("ext2",ext2);
        model.addAttribute("ext3",ext3);
        model.addAttribute("ext4",ext4);
        servletContext.setAttribute("geoserver", mGeoServerConfig.getText());

        User user = mShiroService.getCurrentUser();
        model.addAttribute("cropTypes", JSON.toJSONString(mCropItemService.findAll()));
        model.addAttribute("cropPeriods", JSON.toJSONString(mCropPeriodService.findAll()));
        model.addAttribute("user", user);
        model.addAttribute("roles", mSRoleRepository.findAll());
        model.addAttribute("userRoles", mUserRoleRepository.getRoleByUsers(mShiroService.getCurrentUserId()));// 这里用户对角色1v1
        model.addAttribute("organ", mOrganService.findOne(user.getOrganId()));


        return "comm/admin2";
    }

    /**
     * 修改密码页面
     *
     * @return
     */
    @RequestMapping(value = "/admin/password")
    public String setUserPassword(Model model) {
        model.addAttribute("user", mShiroService.getCurrentUser());
        return "comm/password";
    }

    /**
     * 提交密码修改
     *
     * @return
     */
    @PostMapping(value = "/admin/submitUpdatePassword")
    @ResponseBody
    public BaseResult submitUpdatePassword(@RequestParam("oldPassword") String oldPassword, @RequestParam("newPassword")String newPassword) {
        try {
            User user = mShiroService.getCurrentUser();
            // 密码加密
            oldPassword = DigestUtils.md5Hex(user.getUsername() + oldPassword);
            // 创建用户验证身份令牌
            ShiroToken token = new ShiroToken(user.getUsername(), oldPassword);
            SecurityUtils.getSubject().login(token);
            // 验证成功生成新的密码，并修改密码
            user.setCode(newPassword);
            newPassword = DigestUtils.md5Hex(user.getUsername() + newPassword);
            user.setPassword(newPassword);
            int result = mUserRepository.insertOrUpdate(user);
            if(result > 0){
                return R.succ(MessageUtils.get("main.pwd_succ"));
            }
        } catch (UnsupportedTokenException e) {
            return R.fail(MessageUtils.get("main.vcode_error"));
        } catch (UnknownAccountException e) {
            return R.fail(MessageUtils.get("main.u_and_p_error"));
        } catch (IncorrectCredentialsException e) {
            return R.fail(MessageUtils.get("main.u_and_p_error"));
        } catch (ExcessiveAttemptsException e) {
            return R.fail(MessageUtils.get("main.failed_login_times"));
        } catch (LockedAccountException e) {
            return R.fail(MessageUtils.get("main.locked"));
        } catch (DisabledAccountException e) {
            return R.fail(MessageUtils.get("main.disabled"));
        }
        return R.fail(MessageUtils.get("main.failed_pwd"));
    }

    /**
     * 控制台
     *
     * @return
     */
    @RequestMapping(value = "/console")
    public String console(Model model) {
        User user = mShiroService.getCurrentUser();
        model.addAttribute("user", user);
        model.addAttribute("roles", mSRoleRepository.findAll());
        model.addAttribute("userRoles", mUserRoleRepository.getRoleByUsers(mShiroService.getCurrentUserId()));// 这里用户对角色1v1
        model.addAttribute("organ", mOrganService.findOne(user.getOrganId()));
        return "comm/console";
    }

    /**
     * 用户导航
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/admin/navigation")
    public BaseResult navigation() {
        User user = mUserRepository.findOne(mShiroService.getCurrentUserId());
        if (ObjectUtils.isNotEmpty(user)) {
            // 查询当前用户角色
            UserRole userRole = mUserRoleRepository.getRoleByUser(user.getId());
            if (ObjectUtils.isNotEmpty(userRole)) {
                // 查询当前用户角色权限
                String[] permissions = mRolePermissionService.getPermissions(userRole.getPk().roles());
                return R.succ(mMenuService.getNavigTree(permissions));
            }
        }
        return R.fail();
    }
}
