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

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.ap.SysConstains;
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.UserPdu;
import com.mortals.xhx.feign.user.IUserFeign;
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;

@RestController
@RequestMapping("login")
public class LoginController extends BaseCRUDJsonBodyMappingController<UserService, UserEntity, Long> {

    @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 IUserFeign userFeign;

    private static Log logger = LogFactory.getLog(LoginController.class);

    @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);
        String resp = userFeign.portalLogin(userPdu);

        return resp;


        /*JSONObject ret = new JSONObject();
        String loginName = loginForm.getLoginName();
        String password = loginForm.getPassword();
        //String securityCode = loginForm.getSecurityCode();
        String ip = super.getRequestIP(request);
        if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password)) {
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, "未获取到用户信息，请重新登录");
            return ret.toJSONString();
        }
        UserEntity userEntity = null;
        try {
            loginForm.validate();

            userEntity = userService.doLogin(loginName, password, ip);
            userEntity.setLastLoginAddress(ip);
            //saveCurrUser(request, response, userEntity);
            recordSysLog(request, userEntity, "用户登录系统成功!");
            // 返回拥有的菜单数据
            Set<String> urls = resourceService.findUrlSetByUserId(userEntity.getId());
            List<MenuEntity> outlookBarList = menuService.findTreeMenu(userEntity, urls);
            String currUserName = userEntity.getRealName();
            if (currUserName == null || currUserName.trim().length() == 0) {
                currUserName = "管理员";
            }
            userEntity.setLoginTime(System.currentTimeMillis());
            userEntity.setToken(IdUtil.fastSimpleUUID());
            userEntity.setExpireTime(DateUtils.addCurrDate(7).getTime());
            String token = authTokenService.createToken(userEntity);
            JSONObject data = new JSONObject();
            data.put("token", token);
            data.put("currUserName", currUserName);
            data.put("barList", outlookBarList);
            data.put("id", userEntity.getId());
            data.put("userType", userEntity.getUserType());

            //this.generateBlackCookie(request, response, loginName, urls);
            ret.put(KEY_RESULT_DATA, data);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_MSG, "用户登录系统成功!");
            ret.put("resources", urls);

            return ret.toJSONString();
        } catch (Exception e) {
            log.error("login error ", e);
            if (userEntity == null) {
                userEntity = new UserEntity();
                userEntity.setLoginName(loginName);
            }
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }*/
    }

    @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 "";
        }
        Set<String> urls = resourceService.findUrlSetByUserId(user.getId());
        List<MenuEntity> outlookBarList = menuService.findTreeMenu(user, urls);
        String currUserName = user.getRealName();
        if (currUserName == null || currUserName.trim().length() == 0) {
            currUserName = "管理员";
        }
        JSONObject data = new JSONObject();
        data.put("currUserName", currUserName);
        data.put("barList", outlookBarList);
        data.put("id", user.getId());
        data.put("userType", user.getUserType());
        ret.put(KEY_RESULT_DATA, data);
        //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();
    }

}
