package com.miaxis.system.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.miaxis.apple.service.IAppleService;
import com.miaxis.common.core.domain.DyUserInfoResult;
import com.miaxis.common.core.domain.Response;
import com.miaxis.common.core.domain.WxUserInfo;
import com.miaxis.common.core.domain.entity.SysMenu;
import com.miaxis.common.core.domain.entity.SysUser;
import com.miaxis.common.core.domain.model.*;
import com.miaxis.common.enums.StudentLoginTypeEnum;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.utils.SecurityUtils;
import com.miaxis.common.utils.ServletUtils;
import com.miaxis.framework.web.service.SysLoginService;
import com.miaxis.framework.web.service.SysPermissionService;
import com.miaxis.framework.web.service.TokenService;
import com.miaxis.system.dto.common.RouterDTO;
import com.miaxis.system.dto.system.AppleTokenDTO;
import com.miaxis.system.dto.system.TokenDTO;
import com.miaxis.system.dto.system.UserInfoDTO;
import com.miaxis.system.service.ISysMenuService;
import com.miaxis.feign.dto.DyTokenDTO;
import com.miaxis.feign.dto.DyUserInfoDTO;
import com.miaxis.feign.dto.ToutiaoTokenDTO;
import com.miaxis.feign.service.DyService;
import com.miaxis.feign.service.ToutiaoService;
import com.miaxis.feign.service.WxService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author miaxis
 */
@RestController
@Api(tags={"【系统-登录验证】"})
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Resource
    private IAppleService appleService;


    @Autowired
    private WxService wxService;


    @Autowired
    private DyService dyService;

    @Autowired
    private ToutiaoService toutiaoService;


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




    @Value("${app.appId}")
    private String appid;

    @Value("${app.appSecret}")
    private String appSecret;

    @Value("${dy.appId}")
    private String dyappid;

    @Value("${dy.appSecret}")
    private String dyappSecret;

    @Value("${tt.appId}")
    private String ttappid;

    @Value("${tt.appSecret}")
    private String ttappSecret;




    /**
     * 登录方法 （含验证码）
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    @ApiOperation("系统-登录方法")
    public Response<TokenDTO> login(@RequestBody LoginBody loginBody)
    {   TokenDTO tokenDTO = new TokenDTO();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        tokenDTO.setToken(token);
        return Response.success(tokenDTO);
    }
    /**
     * 登录方法 （不含验证码）
     *
     * @param loginBodyNoCode 登录信息
     * @return 结果
     */
    @PostMapping("/login/noCode")
    @ApiOperation("登录方法（不含验证码）")
    public Response<TokenDTO> loginNoCode(@RequestBody LoginBodyNoCode loginBodyNoCode)
    {   TokenDTO tokenDTO = new TokenDTO();
        // 生成令牌
        String token = loginService.login(loginBodyNoCode.getUsername(), loginBodyNoCode.getPassword());
        tokenDTO.setToken(token);
        return Response.success(tokenDTO);
    }

    /**
     * 用户 openid登录
     *
     */
    @PostMapping("/login/code")
    @ApiOperation("微信用户授权码模式登录")
    public Response<TokenDTO> loginByWxAuthorizationCode(String authorizationCode ){
        String wxResultStr = wxService.getWxToken(appid, appSecret, authorizationCode, "authorization_code");
        logger.info("微信授权码登录返回值:"+wxResultStr);
        WxResult wxResult = JSONObject.parseObject(wxResultStr,WxResult.class);

        // 生成令牌
        if (wxResult.getErrcode() != null){
            throw new CustomException("微信授权无效，请重新授权");
        }

        String userInfoStr = wxService.getUserInfo("zh_CN", wxResult.getAccess_token(), wxResult.getOpenid());
        WxUserInfo wxUserInfo = JSONObject.parseObject(userInfoStr,WxUserInfo.class);
        ServletUtils.getRequest().setAttribute("headImage",wxUserInfo.getHeadimgurl());
        ServletUtils.getRequest().setAttribute("nickName",wxUserInfo.getNickname());
        ServletUtils.getRequest().setAttribute("third","weixin");
        ServletUtils.getRequest().setAttribute("openid",wxUserInfo.getOpenid());
        String token = loginService.login(wxUserInfo.getUnionid(),null, StudentLoginTypeEnum.AUTHORIZATION_CODE_LOGIN.getCode());
        TokenDTO tokenDTO = new TokenDTO();
        tokenDTO.setToken(token);
        tokenDTO.setThirdResult(wxUserInfo);
        return Response.success(tokenDTO) ;



    }

    /**
     * 用户 openid登录
     *
     */
    @PostMapping("/login/ttcode")
    @ApiOperation("字节小程序授权码模式登录")
    public Response<TokenDTO> loginByTtAuthorizationCode(String authorizationCode ){
        ToutiaoTokenDTO toutiaoTokenDTO  = new ToutiaoTokenDTO();
        toutiaoTokenDTO.setCode(authorizationCode);
        toutiaoTokenDTO.setAppid(ttappid);
        toutiaoTokenDTO.setSecret(ttappSecret);
        String ttResultStr = toutiaoService.getTtUserInfo(toutiaoTokenDTO);
        logger.info("字节小程序授权码登录返回值:"+ttResultStr);
        TtResult ttResult = JSONObject.parseObject(ttResultStr,TtResult.class);

        // 生成令牌
        if (ttResult.getErr_no() != 0){
            throw new CustomException("抖音授权登录无效，错误原因："+ttResult.getErr_tips());
        }


        ServletUtils.getRequest().setAttribute("third","douyin");
        ServletUtils.getRequest().setAttribute("headImage","");
        ServletUtils.getRequest().setAttribute("nickName","");
        ServletUtils.getRequest().setAttribute("openid",ttResult.getData().getOpenid());

        String token = loginService.login(ttResult.getData().getUnionid(),null, StudentLoginTypeEnum.AUTHORIZATION_CODE_TT_LOGIN.getCode());
        TokenDTO tokenDTO = new TokenDTO();
        tokenDTO.setToken(token);
        tokenDTO.setThirdResult(ttResult);
        return Response.success(tokenDTO) ;



    }

    /**
     * 用户 openid登录
     *
     */
    @PostMapping("/login/dycode")
    @ApiOperation("抖音用户授权码模式登录")
    public Response<TokenDTO> loginByDyAuthorizationCode(String authorizationCode ){
        DyTokenDTO dyTokenDTO = new DyTokenDTO();
        MultiValueMap<String,Object> paramsMap = new LinkedMultiValueMap<String,Object>();
        paramsMap.add("grant_type","authorization_code");
        paramsMap.add("client_secret",dyappSecret);
        paramsMap.add("code",authorizationCode);
        paramsMap.add("client_key",dyappid);
//        dyTokenDTO.setGrantType("authorization_code");
//        dyTokenDTO.setClientKey(dyappid);
//        dyTokenDTO.setClientSecret(dyappSecret);
//        dyTokenDTO.setCode(authorizationCode);
        String dyResultStr = dyService.getDyToken1(dyappSecret,authorizationCode,"authorization_code",dyappid);
        //HttpUtils.sendPost()
       // String dyResultStr = dyService.getDyToken1(dyappSecret,authorizationCode,"authorization_code",dyappid);
        logger.info("抖音授权码登录返回值:"+dyResultStr);
        DyResult dyResult = JSONObject.parseObject(dyResultStr,DyResult.class);

        // 生成令牌
        if (dyResult.getData().getError_code() != 0){
            throw new CustomException("抖音授权登录无效，错误原因："+dyResult.getData().getDescription());
        }
        DyUserInfoDTO dyUserInfoDTO= new DyUserInfoDTO();
        dyUserInfoDTO.setOpen_id(dyResult.getData().getOpen_id());
        dyUserInfoDTO.setAccess_token(dyResult.getData().getAccess_token());
        String userInfoStr = dyService.getUserInfo(dyUserInfoDTO);
        DyUserInfoResult dyUserInfoResult = JSONObject.parseObject(userInfoStr,DyUserInfoResult.class);

        ServletUtils.getRequest().setAttribute("third","douyin");
        ServletUtils.getRequest().setAttribute("headImage",dyUserInfoResult.getData().getAvatar());
        ServletUtils.getRequest().setAttribute("nickName",dyUserInfoResult.getData().getNickname());
        ServletUtils.getRequest().setAttribute("openid",dyUserInfoResult.getData().getOpen_id());
        String token = loginService.login(dyUserInfoResult.getData().getUnion_id(),null, StudentLoginTypeEnum.AUTHORIZATION_CODE_DY_LOGIN.getCode());
        TokenDTO tokenDTO = new TokenDTO();
        tokenDTO.setToken(token);
        tokenDTO.setThirdResult(dyUserInfoResult);
        return Response.success(tokenDTO) ;



    }
    @PostMapping("/login/code/test")
    @ApiOperation("微信用户授权码模式登录--测试")
    public Response<TokenDTO> testloginByAuthorizationCode(String authorizationCode ){
        WxUserInfo wxUserInfo = new WxUserInfo();
       // wxUserInfo.setOpenid("ovKTX5-FKLF6_sgTtCIXpG_lz3PY");

        ServletUtils.getRequest().setAttribute("headImage","https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83erGMFzKaOmz6cIaA0J1nicWSlBLdLKY46N5CNCoASiajT7Z3RIfPngPhJsjmqsSjGCFibPU4vCtfz3aw/132");
        ServletUtils.getRequest().setAttribute("nickName","Althars");
        ServletUtils.getRequest().setAttribute("third","weixin");
        //ServletUtils.getRequest().setAttribute("openid",wxUserInfo.getOpenid());
        String token = loginService.login("oqEKX6GxPyBPfRbM-Bk01CGwA0oM",null, StudentLoginTypeEnum.AUTHORIZATION_CODE_LOGIN.getCode());
        TokenDTO tokenDTO = new TokenDTO();
        tokenDTO.setToken(token);

        return Response.success(tokenDTO) ;


    }

    @PostMapping("/login/code/ios")
    @ApiOperation("IOS登录")
    public Response<AppleTokenDTO> ioslogin(String identityToken){
        try {
            JSONObject appleUser = appleService.getAppleUserInfo(identityToken);
            String token = loginService.login(appleUser.getString("sub"),null, StudentLoginTypeEnum.IOS_CODE_LOGIN.getCode());
            AppleTokenDTO tokenDTO = new AppleTokenDTO();
            tokenDTO.setAppleUserInfo(appleUser);
            tokenDTO.setToken(token);
            return Response.success(tokenDTO);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取苹果用户信息失败");
        }


    }

//
//    /**
//     * 用户 jscode登录
//     *
//     */
//    @PostMapping("/login/jscode-test")
//    @ApiOperation("用户jscode登录(测试，固定openid)")
//    public Response<TokenDTO> getInfoTest(String jscode){
//        TokenDTO tokenDTO = new TokenDTO();
//            // 生成令牌
//        String token = loginService.login("oO7PJ5CPQJo62kZWA3uiUX2KG2s4",null, StudentLoginTypeEnum.AUTHORIZATION_CODE_LOGIN.getCode());
//        tokenDTO.setToken(token);
//        return Response.success(tokenDTO) ;
//
//
//    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @ApiOperation("获取用户信息")
    public Response<UserInfoDTO> getInfo()
    {
        SecurityUtils.getLoginUser();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        SysUser user = loginUser.getUser();
        if (user != null){
            userInfoDTO.setUser(user);
            // 角色集合
            Set<String> roles = permissionService.getRolePermission(user);
            // 权限集合
            Set<String> permissions = permissionService.getMenuPermission(user);
            userInfoDTO.setRoles(roles);
            userInfoDTO.setPermissions(permissions);
        }
        userInfoDTO.setStudent(loginUser.getStudent());
        return Response.success(userInfoDTO);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    @ApiOperation("获取路由信息")
    public Response<List<RouterDTO>> getRouters()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return Response.success(menuService.buildMenus(menus));
    }
}
