package com.srs.web.controller.system;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Set;

import com.srs.stureg.domain.SrsStuReg;
import com.srs.stureg.service.ISrsStuRegService;
import com.srs.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.srs.common.constant.Constants;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.entity.SysMenu;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.core.domain.model.LoginBody;
import com.srs.common.utils.SecurityUtils;
import com.srs.framework.web.service.SysLoginService;
import com.srs.framework.web.service.SysPermissionService;
import com.srs.system.service.ISysMenuService;

/**
 * 登录验证
 * 
 * @author srs
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISrsStuRegService srsStuRegService;

    @Autowired
    private ISysUserService userService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser sysUser=new SysUser();
        if (!loginBody.getUsername().isEmpty()) {
            sysUser = userService.selectUserByUserName(loginBody.getUsername());
        }
        String srsStuRegStatus="1";
        SrsStuReg srsStuReg=new SrsStuReg();
        if (sysUser==null){
            srsStuReg = srsStuRegService.selectSrsStuRegByStuNo(loginBody.getUsername());//学号登录
            if (srsStuReg != null) {
                loginBody.setUsername(srsStuReg.getKSH());
                srsStuRegStatus=srsStuReg.getRegStatus();
            }
        }else {
            srsStuReg = srsStuRegService.getOwnInfoByKsh(loginBody.getUsername());//考生号登录
            if (srsStuReg!=null) {
                srsStuRegStatus = srsStuReg.getRegStatus();
                if(srsStuRegStatus.equals("0")){
                    srsStuReg.setRegStatus("2");
                    srsStuRegService.updateById(srsStuReg);
                }
            }
        }
        ajax.put("regStatus",srsStuRegStatus);
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

//    @RequestMapping("/caslogin")
//    public AjaxResult casUserLogin(@PathVariable("ticket") Long ticket){
//        try {
//            URL url = new URL("https://rsso.gxsdxy.cn/p3/serviceValidate");
//
//            // 创建HttpURLConnection对象
//            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//
//            // 设置请求方法为GET
//            conn.setRequestMethod("GET");
//
//            // 发送请求
//            int responseCode = conn.getResponseCode();
//
//            // 读取响应内容
//            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//            String inputLine;
//            StringBuffer response = new StringBuffer();
//            while ((inputLine = in.readLine()) != null) {
//                response.append(inputLine);
//            }
//            System.out.println(response.toString());
//
//        }catch (Exception ex){
//
//
//        }
//        return AjaxResult.success();
//    }
//    @RequestMapping("/casindex")
//    public AjaxResult userIndex(){
//        String username="";
//        AjaxResult ajax = AjaxResult.success();
//        SysUser user = userService.selectUserByUserName(username);
//        String token = loginService.login(user.getUserName(),null,null);
//        ajax.put(Constants.TOKEN, token);
//        return  AjaxResult.success();
//    }
    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters(@RequestParam("menuUseful") String menuUseful)
    {
        System.out.println(menuUseful);
        Long userId = SecurityUtils.getUserId();
        //List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        List<SysMenu> menus =menuService.selectMenuTreeByUserIdAndMenuUseful(userId,menuUseful);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
