package com.uas.finance.controller;

import com.alibaba.fastjson.JSON;
import com.uas.finance.dao.FinancingApplyDao;
import com.uas.finance.filter.BaseController;
import com.uas.finance.model.Enterprise;
import com.uas.finance.model.FinancingApply;
import com.uas.finance.util.SystemSession;
import com.uas.platform.core.util.AgentUtils;
import com.uas.sso.AuthToken;
import com.uas.sso.SSOConfig;
import com.uas.sso.SSOHelper;
import com.uas.sso.SSOToken;
import com.uas.sso.entity.UserAccount;
import com.uas.sso.entity.UserSpaceView;
import com.uas.sso.entity.UserView;
import com.uas.sso.util.AccountUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

/**
 * 账号登录配置
 * Created by hejq on 2017-11-15.
 */
@RequestMapping(value = "/sso")
@RestController
public class SecurityController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(SecurityController.class);

    @Autowired
    private FinancingApplyDao financingApplyDao;

    /**
     * 获取登录名
     */
    @RequestMapping(value = "/getName", method = RequestMethod.GET)
    public ModelMap getName() {
        logger.info("获取登录名");
        return success(SystemSession.getUserAccount().getVipName());
    }

    /**
     * 获取登录人公司
     */
    @RequestMapping(value = "/getCompany", method = RequestMethod.GET)
    public ModelMap getCompany() {
        logger.info("获取登录人公司");
        return success(SystemSession.getUserAccount().getSpaceName());
    }

    /**
     * 获取登录人企业并且判断是否有已审批的保理单
     */
    @RequestMapping(value = "/getEnuu", method = RequestMethod.GET)
    public ModelMap getEnuu() {
        ModelMap modelMap = new ModelMap();
        String enuu = String.valueOf(SystemSession.getUserAccount().getSpaceUU());
        if (!"".equals(enuu)) {
            modelMap.put("enuu", enuu);
            Long uu = Long.parseLong(enuu);
            //查询所有已审批的金融保理单
            List<FinancingApply> list = financingApplyDao.hasApproved(uu);
            if (list.size() > 0) {
                modelMap.put("approved", true);
            }
        }
        logger.info("获取登录人企业并且判断是否有已审批的保理单");
        return modelMap;
    }

    /**
     * 账户信息、SSO配置
     */
    @RequestMapping(value = "/account", method = RequestMethod.GET)
    public ModelMap getAccountInfo() {
        logger.info("账户信息、SSO配置");
        return success(SystemSession.getUserAccount());
    }

    /**
     * 跳转登录
     *
     * @throws IOException
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelMap getLoginPage(HttpServletRequest request, HttpServletResponse response, String returnUrl) throws IOException {
       // request.getSession().setAttribute(SSOConfig.SSOReferer, returnUrl );
        logger.info("跳转登录");
        SSOHelper.clearLogin(request, response);
        String redirectUrl = null;
        if (StringUtils.isEmpty(returnUrl)) {
            redirectUrl = SSOHelper.getRedirectRefererLoginUrl(request);
        } else {
            redirectUrl = SSOHelper.getRedirectLoginUrl(request, returnUrl);
        }
        boolean cross = SSOHelper.isCrossDomain(request);
        if (cross) {
            // 跨域代理界面
            redirectUrl = request.getContextPath() + "/login/proxy";
        }
        return new ModelMap("content", redirectUrl);
    }


    /**
     *
     * 退出
     *
     * @throws IOException
     */
   /* @RequestMapping(value = "/logout", method = RequestMethod.GET, headers = "Accept=application/json")
    @ResponseStatus(value = HttpStatus.OK)
    public ModelMap logout(HttpServletRequest request, HttpServletResponse response, HttpSession session, String returnUrl) throws IOException {
        session.invalidate();
        SSOHelper.clearLogin(request, response);
        SystemSession.clear();
        if (StringUtils.isEmpty(returnUrl)) {
            returnUrl = request.getHeader("Referer");
        }
        boolean cross = SSOHelper.isCrossDomain(request);
        if (cross) {
            request.getSession().setAttribute(SSOConfig.SSOReferer, returnUrl);
            // 跨域情况，需要再次询问账户中心
            returnUrl = "logout/proxy";
        }
        return new ModelMap("content", returnUrl);
    }
*/
    /**
     * 获取跳转登录的url
     *
     * @param request
     * @param response
     * @returnf
     * @throws IOException
     */
    @RequestMapping(value = "/login/page", method = RequestMethod.GET)
    public ModelMap signin(HttpServletRequest request, HttpServletResponse response,String returnUrl) throws IOException {
        logger.info("获取跳转登录的url");
        request.getSession().setAttribute(SSOConfig.SSOReferer, request.getHeader("Referer"));
        SSOHelper.clearLogin(request, response);
        String redirectUrl = SSOHelper.getRedirectRefererLoginUrl(request);
        if (!StringUtils.isEmpty(returnUrl)) {
            redirectUrl = SSOHelper.getRedirectLoginUrl(request, returnUrl);
        }
        boolean cross = SSOHelper.isCrossDomain(request);
       /*if (cross) {
            // 跨域代理界面
            redirectUrl = "login/proxy";
        }*/
        return new ModelMap("content", redirectUrl).addAttribute("cross", cross);
    }

    /**
     * 获取跨域登录的参数
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/login/crossBefore")
    public ModelMap getCrossLoginData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("获取跨域登录的参数");
        ModelMap model = new ModelMap();
        SSOConfig config = SSOHelper.getSSOService().getConfig();
        // 业务系统私钥签名 authToken 自动设置临时会话 cookie 授权后自动销毁
        AuthToken at = SSOHelper.askCiphertext(request, response, config.getClientPrivateKey());
        // askUrl 询问 sso 是否登录地址
        model.addAttribute("askUrl", config.getCrossAskUrl());
        // askTxt 询问 token 密文
        model.addAttribute("askData", at.encryptAuthToken());
        // 未登录情况下，登录地址
        Object loginUrl = null;
        boolean cross = SSOHelper.isCrossDomain(request);
        if (cross) {
            loginUrl = SSOHelper.getRedirectRefererLoginUrl(request);
        } else {
            loginUrl = SSOHelper.getRedirectLoginUrl(request, String.valueOf(request.getSession().getAttribute("SSOReferer")));
        }
        model.addAttribute("loginUrl", loginUrl);
        return model;
    }

    @InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        dataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String value) {
                setValue(new Date(Long.valueOf(value)));
            }
        });
    }

    /**
     * 其他地点登录后 同步登录状态
     * @param request
     * @param response
     */
    @RequestMapping(value = "/login/other", produces = {"application/javascript"})
    @ResponseBody
    public void afterCrossLogin(HttpServletRequest request, HttpServletResponse response, UserAccount userAccount, Integer maxage) throws Exception {
        String data;
        if (userAccount != null && userAccount.getMobile() != null) {
            SSOToken tk = new SSOToken();
            // 设置cookie
            tk.setUid(userAccount.getMobile());
            tk.setTime(System.currentTimeMillis());
            tk.setData(JSON.toJSONString(userAccount));
            if (null != maxage) {
                request.setAttribute("sso_cookie_maxage", maxage);
            }
            SSOHelper.setSSOCookie(request, response, tk, true);
            response.setHeader("P3P","CP='IDCDSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'");
            response.setHeader("P3P","CP=\"CURaADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSPCOR\"");

            data= "successCallback({success:'1'})";

        } else {
            data="successCallback({success:'0'})";
        }
        PrintWriter out = response.getWriter();
        out.write(data);
        out.close();
    }

    @RequestMapping(value = "/test")
    public String test() {
        return "dsfsa";
    }

    /**
     * 获取跨域登录的参数
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/logout/crossBefore")
    public ModelMap getCrossLogoutData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("获取跨域登录的参数");
        SSOHelper.clearLogin(request, response);
        ModelMap model = new ModelMap();
        SSOConfig config = SSOHelper.getSSOService().getConfig();
        model.addAttribute("askUrl", config.getCrossAskOutUrl());
        Object referer = request.getSession().getAttribute(SSOConfig.SSOReferer);
        model.addAttribute("returnUrl", null == referer ? "/" : referer.toString());
        // 未登录情况下，登录地址
        Object logoutUrl = null;
        boolean cross = SSOHelper.isCrossDomain(request);
        if (cross) {
            logoutUrl = SSOHelper.getRedirectRefererLogoutUrl(request);
        } else {
            logoutUrl = SSOHelper.getRedirectLogoutUrl(request, String.valueOf(request.getSession().getAttribute("SSOReferer")));
        }
        model.addAttribute("logoutUrl", logoutUrl);
        model.addAttribute("baseUrl","/logout");
        return model;
    }

    /**
     * 获取跳转注册的url
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/register/page", method = RequestMethod.GET)
    public ModelMap register(HttpServletRequest request, HttpServletResponse response, String returnUrl) throws IOException {
        logger.info("获取跳转注册的url");
        request.getSession().setAttribute(SSOConfig.SSOReferer, returnUrl);
        SSOHelper.clearLogin(request, response);
        String redirectUrl = null;
        if (StringUtils.isEmpty(returnUrl)) {
            redirectUrl = SSOHelper.getRedirectRefererRegisterUrl(request);
        } else {
            redirectUrl = SSOHelper.getRedirectRegisterUrl(request, returnUrl);
        }
        return new ModelMap("content", redirectUrl);
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET, headers = "Accept=application/json")
    @ResponseStatus(value = HttpStatus.OK)
    public ModelMap logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        logger.info("退出账号");
        session.invalidate();
        SSOHelper.clearLogin(request, response);
        SystemSession.clear();
        String returnUrl = request.getHeader("Referer");
        boolean cross = SSOHelper.isCrossDomain(request);
        if (cross) {
            request.getSession().setAttribute(SSOConfig.SSOReferer, returnUrl);
            // 跨域情况，需要再次询问账户中心
            returnUrl = "logout/proxy";
        }

        return new ModelMap("content", returnUrl);
    }
}
