package com.mortals.xhx.busiz.h5.web;

import cn.hutool.core.util.IdUtil;
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.exception.AppException;
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.DateUtils;
import com.mortals.framework.util.HttpUtil;
import com.mortals.framework.util.StringUtils;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.framework.web.BaseJsonBodyController;
import com.mortals.xhx.base.login.web.LoginForm;
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.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.base.system.valid.service.ValidCodeService;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.key.RedisKey;
import com.mortals.xhx.module.dingding.personal.service.IDingPersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.mortals.xhx.common.key.ErrorCode.*;

@RestController
@Slf4j
@RequestMapping("/api/v1/login")
public class ApiLoginController extends BaseJsonBodyController {

    @Autowired
    private UserService userService;
    @Autowired
    private IAuthTokenService authTokenService;

    @Autowired
    private IDingPersonService dingPersonService;


    @RequestMapping("login")
    public String login(@RequestBody LoginForm loginForm) throws Exception {


        JSONObject ret = new JSONObject();
        JSONObject data = new JSONObject();
        String loginName = loginForm.getLoginName();
        String password = loginForm.getPassword();
        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 {
            if (ObjectUtils.isEmpty(loginForm.getCode())) {
                throw new AppException("钉钉code不能为空！");
            }
            //根据code 查询钉钉用户id
            Rest<String> personRest = dingPersonService.getPersonByCode(loginForm.getCode());
            if (personRest.getCode() != YesNoEnum.YES.getValue()) {
                throw new AppException(DING_AUTH_FAIL,String.format("获取钉钉用户异常,%s", personRest.getMsg()));
            }
            userEntity = userService.doLogin(loginName, password, ip);

            if (!ObjectUtils.isEmpty(loginForm.getCode())) {
                //更新绑定钉钉
                userEntity.setDingUserId(loginForm.getCode());
                userService.getUserDao().update(userEntity);
            }

            HashSet<Integer> set = new HashSet<>();
            set.add(0);
            set.add(2);
            set.add(3);

            if (ObjectUtils.isEmpty(userEntity.getUserType()) || !set.contains(userEntity.getUserType())) {
                throw new AppException("当前用户不支持H5登录!");
            }

            data.put("id", userEntity.getId());
            data.put("userType", userEntity.getUserType());
            userEntity.setLoginTime(System.currentTimeMillis());
            userEntity.setToken(IdUtil.fastSimpleUUID());
            userEntity.setExpireTime(DateUtils.addCurrDate(7).getTime());
            String token = authTokenService.createToken(userEntity);
            data.put("token", token);
            ret.put(KEY_RESULT_DATA, data);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_MSG, "用户登录系统成功!");
            recordSysLog(request, userEntity, "钉钉用户登录系统成功!");
            return ret.toJSONString();
        } catch (AppException e) {
            log.error("dinding login error ", e);
            ret.put(KEY_RESULT_CODE, e.getCode());
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        } catch (Exception e) {
            log.error("系统异常 error ", e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, super.convertException(e));
            return ret.toJSONString();
        }

/*


        JSONObject ret = new JSONObject();
        String loginName = loginForm.getLoginName();
        String password = loginForm.getPassword();
        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);
            recordSysLog(request, userEntity, "H5用户登录系统成功!");
            String currUserName = userEntity.getRealName();
            if (currUserName == null || currUserName.trim().length() == 0) {
                currUserName = "管理员";
            }
            JSONObject data = new JSONObject();
            data.put("currUserName", currUserName);
            data.put("id", userEntity.getId());
            data.put("userType", userEntity.getUserType());

            HashSet<Integer> set = new HashSet<>();
            set.add(0);
            set.add(2);
            set.add(3);

            if (ObjectUtils.isEmpty(userEntity.getUserType()) || !set.contains(userEntity.getUserType())) {
                throw new AppException("当前用户不支持H5登录!");
            }

            userEntity.setLoginTime(System.currentTimeMillis());
            userEntity.setToken(IdUtil.fastSimpleUUID());
            userEntity.setExpireTime(DateUtils.addCurrDate(3).getTime());
            String token = authTokenService.createToken(userEntity);
            data.put("token", token);

            if (!ObjectUtils.isEmpty(loginForm.getDingCode())) {
                //更新绑定钉钉
                userEntity.setDingUserId(loginForm.getDingCode());
                userService.getUserDao().update(userEntity);
            }
            ret.put(KEY_RESULT_DATA, data);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_MSG, "用户登录系统成功!");
            return ret.toJSONString();
        } catch (Exception e) {
            log.error("h5 login error ", e);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);SyncDoorsEventTaskImpl
            ret.put(KEY_RESULT_MSG, super.convertException(e));SyncDoorsEventTaskImpl
            return ret.toJSONString();
        }*/
    }

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


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