package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.utils.RSAUtil;
import com.ruoyi.hywz.utils.HttpUtils;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import com.sgcc.isc.ualogin.client.IscServiceTicketValidator;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @ApiModelProperty(value = "门户账号登陆", notes = "门户账号登陆")
    @PostMapping("/sapSsoLogin/{ticket}")
    public AjaxResult loginUserName(@PathVariable("ticket") String ticket) throws UnsupportedEncodingException {
        IscServiceTicketValidator sv = new IscServiceTicketValidator();
        /*统一认证服务端校验器地址*/
        sv.setCasValidateUrl("http://10.223.57.127:17089/isc_sso/serviceValidate");//测试
//        sv.setCasValidateUrl("http://10.223.1.127:8098/isc_sso/serviceValidate");
        /*业务系统LoginModule访问地址*/
        sv.setService("http://25.212.177.102:19888/index");
        /*设置Ticket*/
        sv.setServiceTicket(ticket);
        System.out.println("校验ticket----------------");

        /*校验*/
        try {
            sv.validate();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String user = "";
        /* xmlResponse = sv.getResponse(); */
        if (sv.isAuthenticationSuccesful()) {
            user = sv.getUser();
        } else {
            String errorCode = sv.getErrorCode();
            String errorMessage = sv.getErrorMessage();
            /* handle the error */
            System.out.println("errorInfo -----------> " + errorCode + "\r\n" + errorMessage);
        }
        System.out.println("userinfo >>>>>>>>>>>> " +  URLDecoder.decode(user, "UTF-8"));

        JSONObject parse = JSONObject.parseObject(URLDecoder.decode(user, "UTF-8"));
        try {
            String loginName = parse.get("iscAdCode").toString();
            String baseOrgId = parse.get("baseOrgId").toString();
            if(StringUtils.isEmpty(loginName)){
                System.out.println("统一权限管理获取用户失败>>>>>>>>>>>>");
                AjaxResult ajax = AjaxResult.error("统一权限管理获取用户失败");
                return ajax;
            }
            System.out.println(loginName);
            System.out.println("loginName >>>>>>>>>>>> " + loginName);

            SysUser sysUser = userService.selectUserByUserName(loginName);
            if(sysUser==null){
                AjaxResult ajax = AjaxResult.error("未获取到当前用户信息");
                return ajax;
            }

            SysUser sysUser1 = new SysUser();
            sysUser1.setUserId(sysUser.getUserId());
            sysUser1.setLoginIp(IpUtils.getIpAddr());
            sysUser1.setLoginDate(DateUtils.getNowDate());
            userService.updateUserProfile(sysUser1);

            Set<String> permissions = permissionService.getMenuPermission(sysUser);
            LoginUser loginUser = new LoginUser();
            loginUser.setPermissions(permissions);
            loginUser.setUserId(sysUser.getUserId());
            loginUser.setOrgName(sysUser.getOrgName());
            loginUser.setOrgNo(sysUser.getOrgNo());
            loginUser.setDeptId(sysUser.getDeptId());
            loginUser.setUser(sysUser);
            String token = tokenService.createToken(loginUser);

            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @PostMapping("/sapSsoLogin/syncSgpt")
    public AjaxResult syncSgpt(@RequestBody Map<String,String> map){
        try{
            //集成数管平台日志
            String ticket = map.get("ticket");
            String orgNo = map.get("orgNo");
            Map<String,Object> logArgsMap = new HashMap<>();
            logArgsMap.put("token",ticket);
            logArgsMap.put("orgNo",orgNo);
            logArgsMap.put("menuHref","/dsjyy-chenzhou-web");
            logArgsMap.put("menuId",3195);
            logArgsMap.put("menuName","郴州专业仓定额储备");
            logArgsMap.put("menuLeave",4);
            logArgsMap.put("parentId",2876);
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization",ticket);
            HttpResponse httpResponse = HttpUtils.doPost("http://25.212.174.227","/micro/upms/logVisit/save","POST",headers,new HashMap<>(), JSONObject.toJSONString(logArgsMap));
            Header[] headers1 = httpResponse.getAllHeaders();
            for(Header header : headers1){
                System.out.println(header.getName()+":"+header.getValue());
            }
            String responseEntity = EntityUtils.toString(httpResponse.getEntity());
            System.out.println(responseEntity);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @ApiModelProperty(value = "退出用户登录信息", notes = "退出用户登录信息")
    @GetMapping("/logOut/{username}")
    public void logOut(@PathVariable("username") String username, HttpServletResponse response) throws IOException {
        System.out.println(">>>>>>>>>>logout>>>>>>>>");
        StringBuffer sbf = new StringBuffer();
        sbf.append("http://10.223.1.127:8098/isc_sso/logout?service=");
        sbf.append("http://25.212.177.102:19888/index");
        sbf.append("&username=");
        sbf.append(username);
        System.out.println("username>>>>>>" + username);
        System.out.println("full route>>>>>>" + sbf.toString());
        response.sendRedirect(sbf.toString());
    }
    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @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);

        int homeType = 0;
        for (String role : roles) {
            if (StringUtils.isNotBlank(role)) {
                if (role.contains("admin") || role.contains("YHS")) {
                    homeType = 1;
                    break;
                }
            }
        }
        ajax.put("homeType", homeType);
        return ajax;
    }


    /**
     * 获取公钥：前端用来密码加密
     * @return
     */
    @GetMapping("/getPublicKey")
    public RSAUtil.RSAKeyPair getPublicKey() {
        return RSAUtil.rsaKeyPair();
    }

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