/*
 * Copyright (C), 2002-2015, 江苏三六五网络股份有限公司
 * FileName: PhpLoginController.java
 * Author:   chengjianfang
 * Date:     2015年1月26日 下午4:29:18
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.house365.web.controller;

import com.house365.rest.context.CmConstant;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.web.util.RestUtil;
import com.house365.web.util.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * PHP登陆控制器<br>
 * 实现PHP使用HTTP请求进行登陆控制
 *
 * @author chengjianfang
 * @version [v1.0.0, 2015年1月26日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("php/login")
public class PhpLoginController extends BaseController {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(PhpLoginController.class);


    /**
     * 功能描述: <br>
     * PHP进行登陆
     *
     * @param response 响应
     * @param request  请求
     * @param session  会话
     * @return 响应视图
     * @author chengjianfang
     * @version [v1.0.0, 2015年1月26日]
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    public String login(HttpServletResponse response, HttpServletRequest request, HttpSession session, Model model) {

        final String userName = request.getParameter(CmConstant.USER_NAME);
        final String userPassword = request.getParameter(CmConstant.USER_PASSWORD);
        final String cityKey = request.getParameter(CmConstant.CITY_ID);
        final String userRole = request.getParameter(CmConstant.USER_ROLE);

        final String redirectUrl = request.getParameter("url");

        List<NameValuePair> queryParams = new ArrayList<>();
        queryParams.add(new BasicNameValuePair("username", userName));
        queryParams.add(new BasicNameValuePair("psw", userPassword));
        queryParams.add(new BasicNameValuePair("powerCity", cityKey));

        String env = MemoryPropertyPlaceholderConfigurer.getContextProperty("system.env");
        String url = MemoryPropertyPlaceholderConfigurer.getContextProperty("php.login.url." + env);
        String newHouseUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("newhouse.php.login.url." + env);

        //---------------------------------_---------------------------------//
        if ("test".equalsIgnoreCase(env)) {
            session.setAttribute(CmConstant.USER_NAME, userName);
            session.setAttribute(CmConstant.USER_PASSWORD, userPassword);
            session.setAttribute(CmConstant.USER_ROLE, userRole);
            session.setAttribute(CmConstant.CITY_KEY, cityKey);
            return "redirect:/" + redirectUrl;
        }

        //---------------------------------_---------------------------------//
        //TODO 如果session中用户名没有变，则不需要重新登录
        try {
            Map<String, Object> result = RestUtil.getForObject(url, queryParams, HashMap.class);
            if (result.get("status").equals(1)) {
                if (StringUtils.isBlank(redirectUrl)) {
                    return "redirect:/";
                } else {
                    session.setAttribute(CmConstant.USER_NAME, userName);
                    session.setAttribute(CmConstant.USER_ROLE, userRole);
                    session.setAttribute(CmConstant.CITY_KEY, cityKey);
                    return "redirect:/" + redirectUrl;
                }
            } else {
                Map<String, Object> result1 = RestUtil.getForObject(newHouseUrl, queryParams, HashMap.class);
                if (result1.get("status").equals(1)) {
                    if (StringUtils.isBlank(redirectUrl)) {
                        return "redirect:/";
                    } else {
                        session.setAttribute(CmConstant.USER_NAME, userName);
                        session.setAttribute(CmConstant.USER_ROLE, userRole);
                        session.setAttribute(CmConstant.CITY_KEY, cityKey);
                        return "redirect:/" + redirectUrl;
                    }
                } else {
                    model.addAttribute("errorMessge", result.get("info"));
                    return "error/errorWithMessage";
                }
            }
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            return "error/error";
        }
    }
}
