package com.mortals.xhx.base.login.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.ap.CookieService;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.ap.SysConstains;
import com.mortals.framework.common.Rest;
import com.mortals.framework.service.IAuthTokenService;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.AESUtil;
import com.mortals.framework.util.HttpUtil;
import com.mortals.framework.util.StringUtils;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.menu.model.MenuEntity;
import com.mortals.xhx.base.system.menu.service.MenuService;
import com.mortals.xhx.base.system.resource.service.ResourceService;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.base.system.valid.service.ValidCodeService;
import com.mortals.xhx.common.key.RedisKey;
import com.mortals.xhx.common.pdu.user.UserPdu;
import com.mortals.xhx.feign.user.IUserFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;

import static com.mortals.xhx.common.key.ErrorCode.ERROR_TOKEN_EXPIRED;
import static com.mortals.xhx.common.key.ErrorCode.ERROR_TOKEN_EXPIRED_CONTENT;

@RestController
@Slf4j
@RequestMapping("login")
@ConditionalOnExpression("'${platform.type:null}'=='cloud'")
public class LoginController extends BaseCRUDJsonBodyMappingController<UserService, UserEntity, Long> implements InitializingBean {

    @Autowired
    private UserService userService;
    @Autowired
    private ValidCodeService validCodeService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private MenuService menuService;
    //    @Autowired
//    private ITokenService tokenService;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private IAuthTokenService authTokenService;
    @Autowired
    private IUserFeign userFeign;

    @RequestMapping("login")
    public String login(@RequestBody LoginForm loginForm) throws Exception {
        String loginName = loginForm.getLoginName();
        String password = loginForm.getPassword();
        UserPdu userPdu = new UserPdu();
        userPdu.setLoginName(loginName);
        userPdu.setPassword(password);
        userPdu.setSecurityCode("admin");
        String resp = userFeign.portalLogin(userPdu);
        return resp;
    }

    @RequestMapping("logout")
    public void logout(HttpServletRequest request, HttpServletResponse response)  {
        recordSysLog(request, "退出登录");
        super.removeCurrUser(request);
        this.deleteBlackCookie(request, response);
    }

    @RequestMapping("index")
    public String index() throws Exception {
        JSONObject ret = new JSONObject();
        IUser user = this.getCurUser();
        if (user == null) {
            return JSONObject.toJSONString(Rest.fail(ERROR_TOKEN_EXPIRED, ERROR_TOKEN_EXPIRED_CONTENT));
        }
        Set<String> urls = resourceService.findUrlSetByUserId(user.getId());
        log.info("userId:{},urls:{}", user.getId(),JSON.toJSONString(urls));
        List<MenuEntity> outlookBarList = menuService.findTreeMenu(user, urls);
        String currUserName = user.getRealName();
        if (currUserName == null || currUserName.trim().length() == 0) {
            currUserName = "管理员";
        }
        JSONObject data = new JSONObject();

        String token = authTokenService.getToken(request);
        data.put("token", token);
        data.put("currUserName", currUserName);
        data.put("barList", outlookBarList);
        data.put("id", user.getId());
        data.put("userType", user.getUserType());
        ret.put(KEY_RESULT_DATA, data);
        generateMenuUrlCode(urls);
        // this.generateBlackCookie(request, response, user.getLoginName(), urls);
        ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
        ret.put(KEY_RESULT_MSG, "用户登录系统成功!");
        ret.put("resources", urls);
        return ret.toJSONString();
    }

    private void generateBlackCookie(HttpServletRequest request, HttpServletResponse response, String loginName, Set<String> urls) {
        try {
            String cacheKey = RedisKey.KEY_MENU_CACHE + loginName;
            String securityKey = GlobalSysInfo.getPropertyValue(SysConstains.PROP_COOKIE_SECURITY_KEY);
            //应为Cookie会超长，所以改为仅存储key将值放入redis
            //CookieService.setCookieForAuth(request, response, securityKey, null);
            StringBuilder sb = new StringBuilder();
            if (urls != null && urls.size() > 0) {
                for (String url : urls) {
                    int index = url.hashCode() & (Integer.MAX_VALUE - 1);
                    sb.append(index).append(",");
                }
            }
            String menuUrl = sb.toString();
            menuUrl = AESUtil.encrypt(menuUrl, securityKey);
            cacheService.set(cacheKey, menuUrl, 604800);
            HttpUtil.setCookieValue(request, response, SysConstains.COOKIE_MENU, cacheKey, -1);

        } catch (Throwable e) {

        }
    }


    private String generateMenuUrlCode(Set<String> urls) {
        try {
            String securityKey = GlobalSysInfo.getPropertyValue(SysConstains.PROP_COOKIE_SECURITY_KEY);
            StringBuilder sb = new StringBuilder();
            if (urls != null && urls.size() > 0) {
                for (String url : urls) {
                    int index = url.hashCode() & (Integer.MAX_VALUE - 1);
                    sb.append(index).append(",");
                }
            }
            String menuUrl = sb.toString();
            return AESUtil.encrypt(menuUrl, securityKey);
        } catch (Throwable e) {
            log.error("编码异常", e);
            return null;

        }
    }

    @RequestMapping("validcode")
    public String validCode(HttpServletRequest request, HttpServletResponse response, LoginForm loginForm) {
        JSONObject ret = new JSONObject();
        String loginName = loginForm.getLoginName();
        String password = loginForm.getPassword();
        if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password)) {
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, "登录名或密码为空");
        }
        UserEntity user = null;
        try {
            user = userService.doCheckUser(loginName, password);
            if (user == null) {
                ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
                ret.put(KEY_RESULT_MSG, "用户名或密码不正确");
            } else if (StringUtils.isEmpty(user.getMobile())) {
                ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
                ret.put(KEY_RESULT_MSG, "用户无正确的手机号");
            } else {
                String mobile = StringUtils.trim(user.getMobile());
                String sessionId = request.getSession().getId();
                String ip = super.getRequestIP(request);
                boolean result = validCodeService.createSmsValidCode(sessionId, ip, mobile);
                if (result) {
                    ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
                } else {
                    ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
                    ret.put(KEY_RESULT_MSG, "验证码发送失败，请稍后在试！");
                }
            }
        } catch (Exception e) {
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, "验证码发送失败：" + super.convertException(e));
        } finally {
            if (user == null) {
                user = new UserEntity();
                user.setLoginName(loginName);
            }
            recordSysLog(request, user, "用户获取短信验证码");
        }
        return ret.toJSONString();
    }

    protected void deleteBlackCookie(HttpServletRequest request, HttpServletResponse response) {
        try {
            CookieService.deleteCookieForAuth(request, response);
        } catch (Throwable e) {
        }
    }


    @RequestMapping("parseToken")
    public IUser parseToken() throws Exception {
        IUser userEntity = authTokenService.getLoginUser(request);
        if (!ObjectUtils.isEmpty(userEntity)) {
            authTokenService.verifyToken(userEntity);
            return userEntity;
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("初始化加载云服务版登录。。。");
    }
}
