package com.dcsoft.auth.controller;

import javax.servlet.http.HttpServletRequest;

import com.dcsoft.auth.bean.ValidateResult;
import com.dcsoft.auth.form.IDaasBody;
import com.dcsoft.auth.utils.LicenseManager;
import com.dcsoft.auth.utils.LicenseThread;
import com.idsmanager.dingdang.jwt.DingdangUserRetriever;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.dcsoft.auth.form.LoginBody;
import com.dcsoft.auth.form.RegisterBody;
import com.dcsoft.auth.service.SysLoginService;
import com.dcsoft.common.core.domain.R;
import com.dcsoft.common.core.utils.JwtUtils;
import com.dcsoft.common.core.utils.StringUtils;
import com.dcsoft.common.security.auth.AuthUtil;
import com.dcsoft.common.security.service.TokenService;
import com.dcsoft.common.security.utils.SecurityUtils;
import com.dcsoft.system.api.model.LoginUser;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * token 控制
 *
 * @author dcsoft
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Value("${license.enabled}")
    private Boolean enabled;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
     /*   if(enabled){
            ValidateResult validateResult = LicenseThread.validateResult.get("Authorize");
            if (!validateResult.getIsValidate()){
                return R.fail(validateResult.getMessage());
            }
        }*/

        LoginUser userInfo=new LoginUser();
        // 用户登录
        if("weixin".equals(form.getFlag())){
            R<LoginUser> userInfos=sysLoginService.getWxUserInfo(form);
            //userInfo=sysLoginService.login(form.getUsername());
            userInfo = userInfos.getData();
            if(userInfo==null){
                R.fail();
            }
        }else if("app".equals(form.getFlag())){
            userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
            //保存用户openid
            if(StringUtils.isNotEmpty(form.getOpenid())){
                sysLoginService.updateOpenId(userInfo,form);
            }
        }else{
             userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        }
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @PostMapping("app")
    public R<?> app(@RequestBody LoginBody form)
    {
     /*   if(enabled){
            ValidateResult validateResult = LicenseThread.validateResult.get("Authorize");
            if (!validateResult.getIsValidate()){
                return R.fail(validateResult.getMessage());
            }
        }*/

        LoginUser userInfo=new LoginUser();
        // 用户登录
        if("weixin".equals(form.getFlag())){
            R<LoginUser> userInfos=sysLoginService.getWxUserInfo(form);
            userInfo = userInfos.getData();
            if(userInfo==null){
                R.fail();
            }
        }else if("app".equals(form.getFlag())){
            userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
            //保存用户openid
            if(!"".equals(form.getOpenid())){
                sysLoginService.updateOpenId(userInfo,form);
            }
        }else{
            userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        }
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }


    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }

   /* @PostMapping("validate")
    public R<?> validate(@RequestBody IDaasBody iDaasBody)
    {
        String name= null;
        try {
            name = checkUsername(iDaasBody.getIdToken());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        LoginUser userInfo=new LoginUser();
        // 用户登录
        userInfo = sysLoginService.login(name);
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }*/

  /*  private String checkUsername(String id_token) throws
            UnsupportedEncodingException {
        //1.使⽤公钥解析id_token，使⽤publicKey解密上⼀步获取的id_token令牌
        DingdangUserRetriever retriever = new DingdangUserRetriever(id_token,publickey);
        DingdangUserRetriever.User user = null;
        try {
        //2.获取⽤户信息
            user = retriever.retrieve();
        } catch (Exception e) {
            return "error";
        }
        //3.如果publicKey不正确或者id_token过期，获取到的⽤户信息可能为null
        if (null == user) {

            return "error";
        }
        //4.获取到⽤户信息，检测⽤户名是否存在⾃⼰的业务系统中，isExistedUsername⽅法为示例实现
        if (StringUtils.isNotEmpty(user.getUsername())) {
            return user.getUsername();
        } else {
            //8.如果不存在,返回登录失败⻚⾯,提示⽤户不存在
            return "error";
        }
    }*/

    //获取服务器标识接口
    @GetMapping("/getServerID")
    public Map<String,Object> getServerID(){
        Map<String,Object> retMap=new HashMap<>(2);
        retMap.put("code","200");
        retMap.put("serverID", LicenseManager.getSystemSign());
        return retMap;
    }

   //授权码更新接口
    @PostMapping("/updateSign")
    public Map<String,Object> updateSign(String sign){
        Map<String,Object> retMap=new HashMap<>(2);
        LicenseManager.updateSign(sign);
        LicenseThread.validateAfterUpdateSign();
        retMap.put("code","200");
        retMap.put("msg","激活成功！");
        return retMap;
    }

}
