package com.storlead.system;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.storlead.framework.auth.jwt.JwtUtil;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.redis.RedisService;
import com.storlead.system.service.IMenuService;
import com.storlead.system.service.IUserRoleService;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.pojo.entity.JobEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.IJobService;
import com.storlead.user.service.IUserService;
import com.storlead.wecom.pojo.vo.CorpWeChatUserVO;
import com.storlead.wecom.pojo.vo.WechatToken;
import com.storlead.wecom.properties.CorpWeChatConstants;
import com.storlead.wecom.properties.CorpWeChatProperties;
import com.storlead.wecom.service.CorpWeChatService;
import com.storlead.wecom.service.WxDataSyncService;
import com.storlead.wecom.util.CorpWechatUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 企业微信管理
 *
 * @author blank
 * @date 2021-3-8 下午 12:06
 */
@Api(tags = "平台中心 - 系统: 企业微信管理")
@RestController
@RequestMapping("/xwork")
@Log4j2
public class CorpWeChatController {

    @Resource
    private CorpWeChatService corpWeChatService;

    @Resource
    private IUserService sysUserService;

    @Resource
    private IJobService jobService;

    @Resource
    private IDepartService departService;

    @Resource
    private RedisService redisService;

    @Resource
    private IUserRoleService userRoleService;

    @Resource
    private WxDataSyncService wxDataSyncService;

    @Resource
    private Environment environment;

    @Resource
    private IMenuService menuService;

    @ApiOperation("获取AccessToken")
    @GetMapping("/get_access_token")
    public String getAccessToken() {
        return corpWeChatService.getAccessToken().getToken();
    }

    @ApiOperation("获取JS Ticket")
    @GetMapping("/get_js_api_ticket")
    public String getJsApiTicket() {
        return corpWeChatService.getJSApiTicket().getToken();
    }

    @ApiOperation("返回用于企业微信登陆所需要的参数")
    @GetMapping("/get_x_work_login_param")
    public Result<JSONObject> getCorpWechatLoginParam() {
        Result<JSONObject> result = new Result<>();

        result.setResult(corpWeChatService.getCorpWechatLoginParam());
        return result;
    }

    @ApiOperation("根据code登录")
    @GetMapping("/login")
    public Result login(String code) {
        String wxCode = corpWeChatService.login(code);
        String corpId = CorpWeChatProperties.getCorpId();
        String corpAddressSecret = CorpWeChatProperties.getCorpAddressSecret();
        WechatToken t = CorpWechatUtil.getAccessToken(CorpWeChatConstants.GET_ACCESS_TOKEN_URL, corpId, corpAddressSecret);
        CorpWeChatUserVO vo =  wxDataSyncService.getWxLoginInfo(t,code);

        if (StrUtil.isBlank(wxCode)) {
            return Result.error("微信登录错误,未获取到用户信息");
        }
        UserEntity userInfo = sysUserService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getXworkUserId,wxCode));
        if (Objects.isNull(userInfo)) {
            return Result.error("微信登录错误,未获取到用户信息");
        }

//        Integer possessMenuCount = menuService.checkUserMenuAccess(userInfo.getId());
//        if (possessMenuCount == 0) {
//            return Result.error("暂未获取到菜单权限,请联系管理员分配权限!");
//        }

        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(userInfo,loginUser);

        if (Objects.nonNull(userInfo.getJobId())) {
            JobEntity job = jobService.getById(userInfo.getJobId());
            if (Objects.nonNull(job)) {
                loginUser.setJobName(job.getName());
            }
        }

        if (Objects.nonNull(userInfo.getDeptId())) {
            DeptEntity dept = departService.getById(userInfo.getDeptId());
            if (Objects.nonNull(dept)) {
                loginUser.setDeptJobDes(dept.getDeptJobDes());
            }
        }

        //用户登录信息
        String jwtToken = JwtUtil.createJWT(com.alibaba.fastjson.JSONObject.toJSONString(loginUser),loginUser.getMobile());
        String token = SecureUtil.md5(jwtToken);

        String json = com.alibaba.fastjson.JSONObject.toJSONString(loginUser);
        redisService.setCacheObject(token, json, 60 * 60 * 24L, TimeUnit.SECONDS);
//        Map<String, String> apiMap = new HashMap();
//        redisService.setCacheObject(RedisKeySaltConstant.API_CODE_REDIS + loginUser.getMobile(), apiMap);
        obj.put("token", token);
        return Result.result(obj);
    }


//    https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww5323bd8ab4394132&redirect_uri=https%3A%2F%2Fsales.test.storlead.com%2Findex&response_type=code&scope=snsapi_base&agentid=1000033&state=/fromQYwx#wechat_redirect

    @ApiOperation("根据code登录")
    @GetMapping("/code-login")
    public Result apilogin(@RequestParam String code,
                           HttpServletResponse response, HttpServletRequest request)  throws IOException {
        log.error("code-login-------code="+code+"----state--"+"redirect_uri");
        String redirect_uri ="";
        log.error("requestURL----  "+request.getRequestURI());
        String wxCode = corpWeChatService.login(code);
        String corpId = CorpWeChatProperties.getCorpId();
        String corpAddressSecret = CorpWeChatProperties.getCorpAddressSecret();
        WechatToken t = CorpWechatUtil.getAccessToken(CorpWeChatConstants.GET_ACCESS_TOKEN_URL, corpId, corpAddressSecret);
        CorpWeChatUserVO vo =  wxDataSyncService.getWxLoginInfo(t,code);

        if (StrUtil.isBlank(wxCode)) {
            return Result.error("微信登录错误,未获取到用户信息");
        }
        UserEntity userInfo = sysUserService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getXworkUserId,wxCode));
        if (Objects.isNull(userInfo)) {
            return Result.error("微信登录错误,未获取到用户信息");
        }

//        Integer possessMenuCount = menuService.checkUserMenuAccess(userInfo.getId());
//        if (possessMenuCount == 0) {
//            return Result.error("暂未获取到菜单权限,请联系管理员分配权限!");
//        }

        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(userInfo,loginUser);

        if (Objects.nonNull(userInfo.getJobId())) {
            JobEntity job = jobService.getById(userInfo.getJobId());
            if (Objects.nonNull(job)) {
                loginUser.setJobName(job.getName());
            }
        }

        if (Objects.nonNull(userInfo.getDeptId())) {
            DeptEntity dept = departService.getById(userInfo.getDeptId());
            if (Objects.nonNull(dept)) {
                loginUser.setDeptJobDes(dept.getDeptJobDes());
            }
        }

        //用户登录信息
        String jwtToken = JwtUtil.createJWT(com.alibaba.fastjson.JSONObject.toJSONString(loginUser),loginUser.getMobile());
        String token = SecureUtil.md5(jwtToken);

        String json = com.alibaba.fastjson.JSONObject.toJSONString(loginUser);
        redisService.setCacheObject(token, json, 60 * 60 * 24L, TimeUnit.SECONDS);
//        Map<String, String> apiMap = new HashMap();
//        redisService.setCacheObject(RedisKeySaltConstant.API_CODE_REDIS + loginUser.getMobile(), apiMap);
        obj.put("token", token);

        String mobileUrl = "";
        if (isMobile(request)) {
            mobileUrl ="/H5";
        }

        String active = "";
        if(environment.equals("prod")) {
            active = "";
        } else if (environment.equals("test")){
            active = "test.";
        }

        String redirectUrl = "https://sales."+active+"storlead.com"+mobileUrl+"/index?token=" + token;
        log.error("===redirectUrl-----"+redirectUrl);
        response.sendRedirect(redirectUrl);

        return Result.result(obj);
    }

    public boolean isMobile(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) {
            return false;
        }
        // 常见移动设备关键字
        String[] mobileKeywords = {
                "Mobile", "Android", "iPhone", "iPad", "iPod",
                "BlackBerry", "Windows Phone", "Opera Mini", "IEMobile"
        };

        userAgent = userAgent.toLowerCase();
        for (String keyword : mobileKeywords) {
            if (userAgent.contains(keyword.toLowerCase())) {
                return true;
            }
        }
        return false;
    }

}
