package com.gic.haoban.manage.web.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import com.gic.enterprise.api.dto.EnterpriseSettingDTO;
import com.gic.enterprise.api.dto.StoreWidgetDTO;
import com.gic.enterprise.api.service.StoreWidgetService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.dto.PowerClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.clerk.api.service.RightService;
import com.gic.clerk.api.service.UserService;
import com.gic.commons.util.GlobalVar;
import com.gic.commons.util.ToolUtil;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.anno.IgnoreLogin;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.manage.api.dto.EnterpriseDetailDTO;
import com.gic.haoban.manage.api.dto.HaobanUserDTO;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.api.dto.WxApplicationDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.api.service.HaobanUserApiService;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.service.WxApplicationApiService;
import com.gic.haoban.manage.api.service.WxEnterpriseApiService;
import com.gic.haoban.manage.api.service.WxEnterpriseRelatedApiService;
import com.gic.haoban.manage.web.config.Config;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.vo.WebLoginVO;
import com.gic.redis.data.util.RedisUtil;
import com.gic.wechat.api.dto.qywx.UserDTO;
import com.gic.wechat.api.service.qywx.QywxCorpApiService;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;

@RestController
public class LoginController extends WebBaseController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    private static final String LOGIN_KEY = "haoban#login$key";

    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private QywxCorpApiService qywxCorpApiService;
    @Autowired
    private WxEnterpriseApiService wxEnterpriseApiService;
    @Autowired
    private WxEnterpriseRelatedApiService wxEnterpriseRelatedApiService;
    @Autowired
    private WxApplicationApiService wxApplicationApiService;
    @Autowired
    private UserService userService;
    @Autowired
    private Config config;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private HaobanUserApiService haobanUserApiService;
    @Autowired
    private RightService rightService ;
    @Autowired
    private StoreWidgetService storeWidgetService;

    /**
     * 企微后台登录
     */
    @RequestMapping("login")
    @IgnoreLogin
    public HaobanResponse login(String auth_code, HttpServletResponse response) {
        String userJson = qywxCorpApiService.getLoginUserInfo(config.getCorpid(), auth_code);
        String host = GlobalVar.ctxPropertiesMap.get("haoban_service_host") ;
        if (StringUtils.isBlank(userJson)) {
            logger.info("企微登录失败auth_code={}", auth_code);
            String code = "1000" ;
            try {
                response.sendRedirect(host+"/haoban-3/#/gic-error?errorCode="+code);
            } catch (IOException e) {
                logger.info("异常",e);
            }
            return this.fail(this.errMessage(code));
        }
        UserDTO wxUser = JSON.parseObject(userJson, UserDTO.class);
        logger.info("企微登录user={}", JSON.toJSONString(wxUser));
        String corpId = wxUser.getCorpid();
        if (StringUtils.isBlank(corpId)) {
            logger.info("企微登录失败auth_code={}", auth_code);
            String code = "1000" ;
            try {
                response.sendRedirect(host+"/haoban-3/#/gic-error?errorCode="+code);
            } catch (IOException e) {
                logger.info("异常",e);
            }
            return this.fail(this.errMessage(code));
        }
        WxEnterpriseDTO wxEnterprise = wxEnterpriseApiService.getEnterpriseBycorpId(corpId);
        if (null == wxEnterprise) {
            logger.info("微信企业不存在corpId={}", corpId);
            String code = "1000" ;
            try {
                response.sendRedirect(host+"/haoban-3/#/gic-error?errorCode="+code);
            } catch (IOException e) {
                logger.info("异常",e);
            }
            return this.fail(this.errMessage(code));
        }
        logger.info("企微登录wxenterprise={}", JSON.toJSONString(wxEnterprise));
        String wxEnterpriseId = wxEnterprise.getWxEnterpriseId();
        StaffDTO loginStaff = staffApiService.selectByUserIdAndEnterpriseId(wxUser.getUserid(), wxEnterpriseId);
        if (loginStaff == null) {
            staffApiService.wxFristAdd(JSON.toJSONString(wxUser), wxEnterprise.getWxEnterpriseId());
            loginStaff = staffApiService.selectByUserIdAndEnterpriseId(wxUser.getUserid(),
                    wxEnterprise.getWxEnterpriseId());
        }
        logger.info("企微登录staff={}", JSON.toJSONString(loginStaff));
        if (loginStaff == null) {
            logger.info("登录失败,好办管理员不存在");
            String code = "1000" ;
            try {
                response.sendRedirect(host+"/haoban-3/#/gic-error?errorCode="+code);
            } catch (IOException e) {
                logger.info("异常",e);
            }
            return this.fail(this.errMessage(code));
        }
        String loginPhoneNumber = loginStaff.getPhoneNumber();
        if (StringUtils.isBlank(loginPhoneNumber)) {
            logger.info("未配置手机号,staffId ={}", loginStaff.getStaffId());
            String code = "3000" ;
            try {
                response.sendRedirect(host+"/haoban-3/#/gic-error?errorCode="+code);
            } catch (IOException e) {
                logger.info("异常",e);
            }
            return this.fail(this.errMessage(code));
        }
        List<EnterpriseDetailDTO> list = this.wxEnterpriseRelatedApiService
                .listEnterpriseByWxEnterpriseId(wxEnterpriseId, loginPhoneNumber, true);
        if (CollectionUtils.isEmpty(list)) {
            logger.info("企微下无管理GIC商户");
            String code = "1001" ;
            try {
                response.sendRedirect(host+"/haoban-3/#/gic-error?errorCode="+code);
            } catch (IOException e) {
                logger.info("异常",e);
            }
            return this.fail(this.errMessage(code));
        }
        String gicEnterpriseId = list.get(0).getEnterpriseId();
        HaobanUserDTO dto =  this.haobanUserApiService.selectByPhone(wxEnterpriseId,loginPhoneNumber) ;
        if(null != dto && StringUtils.isNotBlank(dto.getDefaultGicEid())) {
            for(EnterpriseDetailDTO item : list) {
                if(item.getEnterpriseId().equals(dto.getDefaultGicEid())) {
                    gicEnterpriseId = item.getEnterpriseId() ;
                }
            }
        }
        logger.info("登录商户={}",gicEnterpriseId);
        String code = this.doLogin(wxEnterpriseId, gicEnterpriseId, loginPhoneNumber, "gic", response,
                null, null, null,null);
        if (StringUtils.isNotBlank(code)) {
            try {
                response.sendRedirect(host+"/haoban-3/#/gic-error?errorCode="+code);
            } catch (IOException e) {
                logger.info("异常",e);
            }
            return this.fail(this.errMessage(code));
        } else {
            return this.success(null);
        }
    }

    /**
     * 运维登录
     */
    @IgnoreLogin
    @RequestMapping("yw-login")
    public HaobanResponse ywLogin(String wxEnterpriseId, String gicEnterpriseId, String random,
            HttpServletResponse response, String operationUserId, String userName, String userMobile) throws UnsupportedEncodingException {
        // 判断是否存在random
        Object o = RedisUtil.getCache(random);
        if (o == null) {
            return resultResponse(HaoBanErrCode.ERR_4);
        }
        if (StringUtils.isAnyBlank(gicEnterpriseId, wxEnterpriseId)) {
            return this.fail("微信企业和gic商户参数为空");
        }
        String gicSuperPhone = clerkService.getSuperAdminPhoneNumber(gicEnterpriseId);
        if (StringUtils.isNotBlank(userName)) {
            userName = URLDecoder.decode(userName, "UTF-8");
        }
        logger.info("好办运维登录商户id={},超管手机={},运维信息:{}-{}-{}", gicEnterpriseId, gicSuperPhone, operationUserId, userName, userMobile);
        if (StringUtils.isBlank(gicSuperPhone)) {
            return this.fail("商户超管的手机号未配置");
        }
        //运维单点登录信息：operationUserId  userName ： 运维realName
        String code = this.doLogin(wxEnterpriseId, gicEnterpriseId, gicSuperPhone, "yw", response, operationUserId, userName,userMobile,null);
        if (StringUtils.isNotBlank(code)) {
            return this.fail(this.errMessage(code));
        }
        return null;
    }

    /**
     * gic商户后台登录
     */
    @IgnoreLogin
    @RequestMapping("gic-login")
    public ModelAndView gicLogin(String random, String wxEnterpriseId, HttpServletResponse response , String hbPage) {
        // 判断是否存在random
        AES aes = SecureUtil.aes(LOGIN_KEY.getBytes());
        String o = aes.decryptStr(random);
        if (o == null || StringUtils.isBlank(wxEnterpriseId)) {
            logger.info("解密异常");
            ModelAndView model = new ModelAndView(new RedirectView("/haoban-3/#/gic-error", false, false));
            return model;
        }
        Object flag = RedisUtil.getCache(random);
        if(null == flag) {
            logger.info("无缓存");
            ModelAndView model = new ModelAndView(
                    new RedirectView("/haoban-3/#/gic-error?errorCode=1005", false, false));
            return model; 
        }
        JSONObject jsonObject = JSONObject.parseObject(o);
        logger.info("登录信息={}",jsonObject.toString());
        String gicEnterpriseId = jsonObject.getString("enterpriseId");
        String loginPhoneNumber = jsonObject.getString("phoneNumber");
        Long timestamp = jsonObject.getLong("timestamp") ;
        if(null == timestamp || StringUtils.isAnyBlank(gicEnterpriseId,loginPhoneNumber)) {
            logger.info("timestamp is null,gicEnterpriseId={},loginPhoneNumber={}", gicEnterpriseId, loginPhoneNumber);
            ModelAndView model = new ModelAndView(
                    new RedirectView("/haoban-3/#/gic-error?errorCode=1000", false, false));
            return model;
        }
        if(timestamp+1000*60*5 < System.currentTimeMillis()) {
            logger.info("登录超时gicEnterpriseId={},loginPhoneNumber={}", gicEnterpriseId, loginPhoneNumber);
            ModelAndView model = new ModelAndView(
                    new RedirectView("/haoban-3/#/gic-error?errorCode=1005", false, false));
            return model;
        }
        List<WxEnterpriseDTO> wxEnterpriseList = wxEnterpriseRelatedApiService.listWxEnterpriseByEid(gicEnterpriseId,
                loginPhoneNumber);
        if (CollectionUtils.isEmpty(wxEnterpriseList)) {
            logger.info("查询好办企业列表null,gicEnterpriseId={},loginPhoneNumber={}", gicEnterpriseId, loginPhoneNumber);
            ModelAndView model = new ModelAndView(
                    new RedirectView("/haoban-3/#/gic-error?errorCode=1001", false, false));
            return model;
        }
        List<String> wxIdList = wxEnterpriseList.stream().map(dto -> dto.getWxEnterpriseId())
                .collect(Collectors.toList());
        if (!wxIdList.contains(wxEnterpriseId)) {
            logger.info("无进去此好办企业的权限={}", wxEnterpriseId);
            ModelAndView model = new ModelAndView(
                    new RedirectView("/haoban-3/#/gic-error?errorCode=1001", false, false));
            return model;
        }

        //运维登录信息
        String operationUserId = jsonObject.getString("operationUserId");
        String userName = jsonObject.getString("userName");
        String userMobile = jsonObject.getString("userMobile");

        String errorCode = this.doLogin(wxEnterpriseId, gicEnterpriseId, loginPhoneNumber, "gic", response,
                operationUserId, userName, userMobile,hbPage);
        if (StringUtils.isNotBlank(errorCode)) {
            ModelAndView model = new ModelAndView(
                    new RedirectView("/haoban-3/#/gic-error?errorCode=" + errorCode, false, false));
            return model;
        }
        RedisUtil.delCache(random) ;
        return null;
    }

    /**
     * 好办-扫码登录 废弃
     */
    @RequestMapping("get-login-qrcode")
    @Deprecated
    public HaobanResponse getLoginQrcode(HttpServletResponse response) throws UnsupportedEncodingException {
       /* String corpid = config.getCorpid();
        String redirectUri = config.getHost() + "login";
        String url = "https://open.work.weixin.qq.com/wwopen/sso/3rd_qrConnect?appid=" + corpid + "&redirect_uri="
                + URLEncoder.encode(redirectUri, "UTF-8") + "&state=web_login@gyoss9&usertype=admin";*/
       // return resultResponse(HaoBanErrCode.ERR_1, URL.decode(url));
        String gicHost =this.getGicHost()+"gic-web/#/login?ishb=1";
        try {
            response.sendRedirect(gicHost);
        } catch (IOException e) {
            logger.info("异常",e);
        }
        return null ;
    }
    
    private String getGicHost(){
        return GlobalVar.ctxPropertiesMap.get("gicweb_service_host").replace("gicweb", "");
    }

    // 登录逻辑
    private String doLogin(String wxEnterpriseId, String gicEnterpriseId, String loginPhoneNumber, String loginChannel,
            HttpServletResponse response, String operationUserId, String userName, String userMobile , String hbPage) {
        //运维单点登录信息：operationUserId  userName ： 运维realName
        logger.info("doLogin={},{},{},{},{}",gicEnterpriseId,loginPhoneNumber, operationUserId, userName, userMobile);
        WxApplicationDTO application = wxApplicationApiService.selectByWxEnterpriseIdAndApplicationType(wxEnterpriseId,2);
        if (null == application) {
            logger.info("登录企业应用 没授权!gicEnterpriseId:{}", gicEnterpriseId);
            WxEnterpriseQwDTO qw = this.wxEnterpriseApiService.getQwInfo(wxEnterpriseId) ;
            if(!qw.isSelf()) {
                return "1004";
            }
        }
        WxEnterpriseDTO enterprise = wxEnterpriseApiService.getOne(wxEnterpriseId);
        if (null == enterprise) {
            logger.info("登录失败,微信企业不存在=wxEnterpriseId{}", wxEnterpriseId);
            return "1000";
        }
        
        WebLoginDTO webLoginDTO = new WebLoginDTO() ;
        StaffDTO staff = staffApiService.selectByNationcodeAndPhoneNumber(wxEnterpriseId, "86", loginPhoneNumber);
        if (null == staff) {
            logger.info("查询staff表不存在,gicEnterpriseId:{},loginPhoneNumber={}", gicEnterpriseId);
           // return "1002" ;
        }else {
            webLoginDTO = EntityUtil.changeEntityByJSON(WebLoginDTO.class, staff);
        }
        
        HaobanUserDTO hbUser = new HaobanUserDTO() ;
        hbUser.setWxEnterpriseId(wxEnterpriseId);
        hbUser.setPhoneNumber(loginPhoneNumber);
        hbUser.setDefaultGicEid(gicEnterpriseId);
        hbUser = this.haobanUserApiService.insert(hbUser) ;
        if(hbUser==null) {
            logger.info("查询staff表不存在,gicEnterpriseId:{},loginPhoneNumber={}", gicEnterpriseId);
            return "1002" ;
        }
        webLoginDTO.setPhoneNumber(loginPhoneNumber);
        webLoginDTO.setHanbaoUserId(hbUser.getUserId());
        webLoginDTO.setWxEnterpriseId(wxEnterpriseId);
        webLoginDTO.setEnterpriseId(gicEnterpriseId);
        // 导购id
        ClerkDTO clerk = clerkService.getUserByPhoneNumber(loginPhoneNumber, gicEnterpriseId);
        if (clerk == null) {
            logger.info("gic账号不存在,eid={},phone={}", gicEnterpriseId, loginPhoneNumber);
            return "1003";
        }
        if(clerk.getStatus() != 1) {
            logger.info("gic冻结,eid={},phone={}", gicEnterpriseId, loginPhoneNumber);
            return "1006" ;
        }
        EnterpriseDTO en = this.enterpriseService.getEnterpriseById(gicEnterpriseId) ;
        webLoginDTO.setLoginChannel(loginChannel);
        webLoginDTO.setClerkId(clerk.getClerkId());
        String roleId = this.rightService.getRoleIdByClerkId(clerk.getClerkId()) ;
        webLoginDTO.setIsClique(en.getIsClique());
        webLoginDTO.setCliqueId(en.getCliqueId());
        webLoginDTO.setRoleId(roleId);
        webLoginDTO.setClerkName(clerk.getClerkName());
        webLoginDTO.setBrandName(en.getBrandName());
        webLoginDTO.setSuperAdmin(clerk.getSuperAdmin());
        webLoginDTO.setDepartAuth(clerk.getDepartAuth());
        //运维登录信息
        webLoginDTO.setOperationUserId(operationUserId);
        webLoginDTO.setOperationUserName(userName);
        webLoginDTO.setClerkPhone(userMobile);
        String redirectUri = config.getHost() ;
        if(StringUtils.isNotBlank(hbPage)) {
            redirectUri += hbPage ;
        }else {
            redirectUri += "index" ;
        }
        redirectUri = redirectUri.replace("haoban-manage3-web", "haoban-3/#");
        String token = ToolUtil.randomUUID() + "-" + ToolUtil.randomStringByTime();
        AuthWebRequestUtil.setSessionUser(webLoginDTO);
        AuthWebRequestUtil.setAppLoginUser(token, webLoginDTO);
        try {
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);
            response.sendRedirect(redirectUri);
            response.setHeader("token", token);
        } catch (IOException e) {
            logger.info("异常",e);
        }
        return null;
    }

    private String errMessage(String code) {
        if (code.equals("1000")) {
            return "系统异常";
        } else if (code.equals("1001")) {
            return "您还不是好办的管理员，请在 GIC 后台绑定好办企业后再登录";
        } else if (code.equals("1002")) {
            return "通过手机号查询staff表，查询不到";
        } else if (code.equals("1003")) {
            return "通过手机号查询clerk，查询不到";
        } else if (code.equals("1004")) {
            return "企微应用未授权";
        } else if(code.equals("1006")) {
            return "账号已冻结,请联系管理员" ;
        }  else if(code.equals("3000")) {
            return "成员未配置手机号" ;
        } else {
            return "系统异常";
        }
    }

    /**
     * 获取登录信息
     */
    @RequestMapping("get-login-info")
    @IgnoreLogin
    public HaobanResponse getLoginInfo() {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        WebLoginVO vo =  new WebLoginVO() ;
        if(null != loginUser) {
            logger.info("当前登录信息={}", JSON.toJSON(loginUser));
            vo = EntityUtil.changeEntityByOrika(WebLoginVO.class, loginUser);
        }
        String gicHost = this.getGicHost();
        vo.setGicHost(gicHost);

        String clerkId = loginUser.getClerkId();
        ClerkDTO clerkDTO = clerkService.getClerkByClerkId(clerkId);
        vo.setHasAllStorePermission(0);
        if (null != clerkDTO) {
            vo.setHasAllStorePermission(isAdminAuthStore(loginUser.getEnterpriseId(), clerkDTO) ? 1:0);
        }

        return this.success(vo);
    }

    private boolean isAdminAuthStore(String enterpriseId, ClerkDTO clerkDTO) {
        if (!isAuthEnterprise(enterpriseId)) {
            return true;
        }
        boolean isAdmin = clerkDTO.getSuperAdmin() != null && clerkDTO.getSuperAdmin() == 1;
        return isAdmin || StringUtils.isBlank(clerkDTO.getStoreWidgetId()) || isAllAuth(clerkDTO.getStoreWidgetId());
    }

    private boolean isAuthEnterprise(String enterpriseId) {
        EnterpriseSettingDTO enterpriseSettingDTO = enterpriseService.getEnterpriseSettingByEnterpriseId(enterpriseId);
        Integer enableAccessControl = enterpriseSettingDTO.getEnableAccessControl();
        //是否开启权限控制
        boolean isEnableAccessControl = enableAccessControl != null && enableAccessControl.intValue() == 1;
        return isEnableAccessControl;
    }

    private boolean isAllAuth(String key) {
        StoreWidgetDTO storeWidgetDTO = storeWidgetService.getStoreWidgetBykey(key);
        return storeWidgetDTO != null && storeWidgetDTO.getSelectType().intValue() == 0;
    }

    @RequestMapping("get-login-session")
    @IgnoreLogin
    public HaobanResponse getLoginSession() {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        return this.success(loginUser);
    }

    /**
     * 好办后台-切换GIC商户
     */
    @RequestMapping("enterprise-is-over")
    public HaobanResponse enterpriseIsOver(String enterpriseId) {
        if (StringUtils.isEmpty(enterpriseId)) {
            return this.fail("企业ID空");
        }
        EnterpriseDTO enterprise = this.enterpriseService.getEnterpriseById(enterpriseId);
        if (null == enterprise) {
            return this.fail("gic商户查询不到");
        }
        String token = AuthWebRequestUtil.getToken();
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        if (null == loginUser) {
            return this.fail("用户未登录");
        }
        logger.info("切换商户,登录信息={},enterpriseId", JSON.toJSONString(loginUser), enterpriseId);
        String phoneNumber = loginUser.getPhoneNumber();
        ClerkDTO clerk = clerkService.getUserByPhoneNumber(phoneNumber, enterpriseId);
        if (clerk == null) {
            logger.info("切换商户失败,gic账号不存在,eid={},phone={}", enterpriseId, phoneNumber);
            return this.fail("切换商户失败,gic账号不存在");
        }
        String endMessage = wxEnterpriseApiService.getEndDate(enterpriseId);
        if (StringUtils.isNotBlank(endMessage)) {
            logger.info("切换商户失败,商户已过期,eid={},phone={}", enterpriseId, phoneNumber);
            return this.fail(endMessage);
        }
        EnterpriseDTO en = this.enterpriseService.getEnterpriseById(clerk.getEnterpriseId()) ;
        loginUser.setIsClique(en.getIsClique());
        loginUser.setCliqueId(en.getCliqueId());
        loginUser.setEnterpriseId(enterpriseId);
        loginUser.setClerkId(clerk.getClerkId());
        loginUser.setClerkName(clerk.getClerkName());
        loginUser.setSuperAdmin(clerk.getSuperAdmin());
        String roleId = this.rightService.getRoleIdByClerkId(clerk.getClerkId()) ;
        loginUser.setRoleId(roleId);
        loginUser.setDepartAuth(clerk.getDepartAuth());
        loginUser.setBrandName(enterprise.getBrandName());
        loginUser.setClerkPhone(clerk.getPhoneNumber()) ;
        AuthWebRequestUtil.setSessionUser(loginUser);
        AuthWebRequestUtil.setAppLoginUser(token, loginUser);
        return resultResponse(HaoBanErrCode.ERR_1, false);
    }

    /**
     * 登录微信企业列表
     * @param random
     * @return
     */
    @RequestMapping("login-wx-enterprise-list")
    @IgnoreLogin
    public HaobanResponse loginWxEnterpriseList(String random) {
        // 判断是否存在random
        AES aes = SecureUtil.aes(LOGIN_KEY.getBytes());
        String o = aes.decryptStr(random);
        if (o == null) {
            logger.info("解密异常");
            return resultResponse(HaoBanErrCode.ERR_5);
        }
        Object flag = RedisUtil.getCache(random);
        if(null == flag) {
            logger.info("无缓存");
            return this.fail("登录已失效,请重新登录");
        }
        JSONObject jsonObject = JSONObject.parseObject(o);
        String wxEnterpriseId = jsonObject.getString("wxEnterpriseId");
        String gicEnterpriseId = jsonObject.getString("enterpriseId");
        String phoneNumber = jsonObject.getString("phoneNumber");
        Long timestamp = jsonObject.getLong("timestamp") ;
        if(null == timestamp) {
            return this.fail("登录请求参数异常timestamp");
        }
        logger.info("选择企微列表,params={}", o);
        if (StringUtils.isAnyBlank(gicEnterpriseId, phoneNumber)) {
            return this.fail("参数异常");
        }
        if(timestamp+1000*60*5 < System.currentTimeMillis()) {
            logger.info("登录超时gicEnterpriseId={},loginPhoneNumber={}", gicEnterpriseId,phoneNumber);
            return this.fail("登录超时,请重新登录");
        }
        // 判断商户
        List<WxEnterpriseDTO> wxEnterpriseList = wxEnterpriseRelatedApiService.listWxEnterpriseByEid(gicEnterpriseId,
                phoneNumber);
        if (CollectionUtils.isEmpty(wxEnterpriseList)) {
            logger.info("查询微信企业列表空,gicEnterpriseId={},phoneNumber={}", gicEnterpriseId, phoneNumber);
            return this.fail("您还不是好办的管理员，请在 GIC 后台绑定好办企业后再登录");
        }
        List<String> wxIdList = wxEnterpriseList.stream().map(dto -> dto.getWxEnterpriseId())
                .collect(Collectors.toList());
        if (StringUtils.isNotBlank(wxEnterpriseId)) {
            if (!wxIdList.contains(wxEnterpriseId)) {
                logger.info("无权限,wxEnterpriseId={}", wxEnterpriseId);
                return this.fail("您还不是好办的管理员，请在 GIC 后台绑定好办企业后再登录");
            }
            List<WxEnterpriseDTO> collect = wxEnterpriseList.stream()
                    .filter(dto -> dto.getWxEnterpriseId().equals(wxEnterpriseId)).collect(Collectors.toList());
            return resultResponse(HaoBanErrCode.ERR_1, collect);
        }
        return resultResponse(HaoBanErrCode.ERR_1, wxEnterpriseList);
    }

    /**
     * 登出
     */
    @RequestMapping("login-out")
    public HaobanResponse loginOut() {
        String token = "";
        Cookie[] cookies = AuthWebRequestUtil.getRequest().getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    token = cookie.getValue();
                    break;
                }
            }
        }
        if (StringUtils.isNotBlank(token)) {
            RedisUtil.delCache(token);
        }
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 
    * @Title: gicLogin
    * @Description: 由于从gic商户后台登录不确认商户需要登录哪一个微信企业,
    * @author xugh
    * @param code
    * @param hbEnt
    * @return
    * @throws
     */
    @RequestMapping("/gic-login-check")
    @IgnoreLogin
    public ModelAndView gicLogin(String code, String hbEnt,String hbPage, String operationUserId, String userName, String userMobile) throws UnsupportedEncodingException {
        logger.info("gic登录clerkId={},hbEnt={},operationUserId={},userName={}", code, hbEnt, operationUserId, userName);
        PowerClerkDTO clerkDTO = this.userService.haobanLoginBack(code);
        if (clerkDTO == null) {
            logger.info("从gic后台登录,传入clerkId={}无效", code);
            ModelAndView model = new ModelAndView(new RedirectView("/haoban-3/#/gic-error?errCode=1", false));
            return model;
        }
        String gicEnterpriseId = clerkDTO.getEnterpriseId();
        String loginPhoneNumber = clerkDTO.getPhoneNumber();
        Map<String, String> retMap = new HashMap<>();
        retMap.put("wxEnterpriseId", hbEnt);
        retMap.put("hbPage", hbPage) ;
        retMap.put("enterpriseId", gicEnterpriseId);
        retMap.put("phoneNumber", loginPhoneNumber);
        retMap.put("timestamp", System.currentTimeMillis()+"") ;
        //运维登录信息
        retMap.put("operationUserId", operationUserId) ;
        if (StringUtils.isNotBlank(userName)) {
            userName = URLDecoder.decode(userName, "UTF-8");
        }
        retMap.put("userName", userName) ;
        retMap.put("userMobile", userMobile) ;
        String ret = JSONObject.toJSONString(retMap);
        AES aes = SecureUtil.aes(LOGIN_KEY.getBytes());
        String random = aes.encryptHex(ret);
        String pageStr = "";
        if(StringUtils.isNotBlank(hbPage)) {
            pageStr += "&hbPage="+hbPage ;
        }
        RedisUtil.setCache(random, 1,10L,TimeUnit.MINUTES);
        ModelAndView model = new ModelAndView(new RedirectView("/haoban-3/#/loginMore?random=" + random+pageStr, false, false));
        return model;
    }

}
