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

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.ap.SysConstains;
import com.mortals.framework.common.Rest;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.ITokenService;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.AESUtil;
import com.mortals.framework.util.DateUtils;
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.LoginPdu;
import com.mortals.xhx.common.pdu.user.UserPdu;
import com.mortals.xhx.common.utils.MenuEncodeUtil;
import com.mortals.xhx.feign.user.IUserFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
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")
public class LoginController extends BaseCRUDJsonBodyMappingController<UserService, UserEntity, Long> {

    @Autowired
    private ResourceService resourceService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private IUserFeign userFeign;
    @RequestMapping("login")
    public String login( @RequestBody LoginForm loginForm) throws Exception {
        String loginName = loginForm.getLoginName();
        String password = loginForm.getPassword();
        LoginPdu loginPdu = new LoginPdu();
        loginPdu.setLoginName(loginName);
        loginPdu.setPassword(password);
        loginPdu.setSecurityCode("admin");
        String resp = userFeign.portalLogin(loginPdu);
        return resp;
    }

    @RequestMapping("logout")
    public void logout() throws Exception {
        recordSysLog(request, "退出登录");
        super.removeCurrUser(request);
    }

    @RequestMapping("index")
    public String index(HttpServletRequest request, HttpServletResponse response) 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);

        List<MenuEntity> treeMenuList = menuService.findTreeMenu(user);
        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("menuList", treeMenuList);
        data.put("id", user.getId());
        data.put("userType", user.getUserType());
        ret.put(KEY_RESULT_DATA, data);
        cacheService.hset(RedisKey.KEY_USER_MENU_CACHE, user.getId().toString(), MenuEncodeUtil.generateMenuUrlCode(urls));

        ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
        ret.put(KEY_RESULT_MSG, "用户登录系统成功!");
        ret.put("resources", urls);
        return ret.toJSONString();
    }

}
