package com.house365.web.controller;

import com.google.common.base.Strings;
import com.house365.beans.entity.UserEntity;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.MD5Util;
import com.house365.ws.beans.request.UserListRequest;
import com.house365.ws.beans.response.UserListResponse;
import com.house365.ws.interfaces.server.IUser;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:whh
 */
@Controller
@RequestMapping("/appLogin")
public class AppLoginController extends BaseController {

    Logger logger = LoggerFactory.getLogger(getClass());
    public static final String PREFIX = "HGS_";
    @Autowired
    private IUser iuser;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据 loginName 获取帐户信息
     *
     * @param loginName 登录名
     * @return 帐户 entity,获取不到返回 null
     */
    private UserEntity getUser(String loginName, String password) {
        Map<String, Object> searchMap = new HashMap<>(10);
        UserListRequest userListRequest = new UserListRequest();
        searchMap.put("EQ_name", loginName);
        searchMap.put("EQ_password", password);
        userListRequest.setSearchParams(searchMap);
        UserListResponse userListResponse = iuser.getUserList(userListRequest);
        UserEntity accountEntity = null;
        if (userListResponse != null && !userListResponse.getObjectList().isEmpty()) {
            accountEntity = userListResponse.getObjectList().get(0);
        }
        return accountEntity;
    }


    /**
     * 校验登陆
     *
     * @return 结果视图
     */
    @RequestMapping(value = "/checkAppLogin")
    public JSONObject checkAppLogin(Model model, HttpServletRequest request, HttpServletResponse response) {
        JSONObject jo = new JSONObject();
        String account = request.getParameter("userName").trim();
        String password = request.getParameter("userPassword").trim();
        if (!Strings.isNullOrEmpty(account) && !Strings.isNullOrEmpty(password)) {
            password = MD5Util.MD5(password);
            UserEntity accountEntity = getUser(account, password);
            if (accountEntity == null) {
                jo.put("RESULT_CODE", "0001");
                jo.put("RESULT_MSG", "用户名或密码错误");
            } else {
                jo.put("RESULT_CODE", "0000");
                jo.put("RESULT_MSG", "SUCCESS");
                jo.put("USER_INFO", accountEntity);
                //
                String phone = accountEntity.getMobile();
                final String cookieKey = PREFIX + "weChat:userInfo:isValid:" + phone;
                System.out.println("------------------app登陆key-------:");
                if (!hasKey(cookieKey)) {
                    redisTemplate.execute(new RedisCallback<Object>() {
                        @Override
                        public Object doInRedis(RedisConnection connection) throws DataAccessException {
                            System.out.println("====>>addRedis>>:======" + cookieKey + "===success");
                            byte[] serialKey = redisTemplate.getStringSerializer().serialize(cookieKey);
                            connection.del(serialKey);
                            connection.set(serialKey, redisTemplate.getStringSerializer().serialize("1"));
                            connection.expire(serialKey, 86400);
                            return null;
                        }
                    });
                }

                Cookie phoneCookie = new Cookie("phone", phone);
                phoneCookie.setPath("/");
                phoneCookie.setMaxAge(86400);
                response.addCookie(phoneCookie);
            }
        }
        return jo;
    }

    public boolean hasKey(final String key) {
        return (Boolean) redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] serialKey = redisTemplate.getStringSerializer().serialize(key);
                return connection.exists(serialKey);
            }
        });
    }

}
