package com.dcsoft.auth.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.auth.form.LoginBody;
import com.dcsoft.auth.form.RegisterBody;
import com.dcsoft.auth.service.SysLoginService;
import com.dcsoft.auth.utils.LicenseManager;
import com.dcsoft.auth.utils.LicenseThread;
import com.dcsoft.auth.utils.RsaUiUtils;
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.core.utils.bean.BeanUtils;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * token 控制
 *
 * @author dcsoft
 */
@RestController
public class TokenController
{
    private static final Logger log = LoggerFactory.getLogger(TokenController.class);
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

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

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) throws Exception {
     /*   if(enabled){
            ValidateResult validateResult = LicenseThread.validateResult.get("Authorize");
            if (!validateResult.getIsValidate()){
                return R.fail(validateResult.getMessage());
            }
        }*/
        log.info("login form:{}", form);
        LoginUser userInfo = new LoginUser();
        // 用户登录
        if ("weixin".equals(form.getFlag())) {
            //微信登录openid必传，phone必传
//            String s = RsaUiUtils.decryptByPrivateKey(form.getOpenid());
//            form.setOpenid(s);
            R<LoginUser> userInfos = sysLoginService.getWxUserInfo(form);
            userInfo = userInfos.getData();
            if (ObjectUtil.isEmpty(userInfo) || ObjectUtil.isEmpty(userInfo.getSysUser())) {
                RegisterBody registerBody = new RegisterBody();
                BeanUtils.copyProperties(form, registerBody);
                userInfo = sysLoginService.appRegister(registerBody);
            }
        } else if ("app".equals(form.getFlag())) {
//            String str = RsaUiUtils.decryptByPrivateKey(form.getEncrypt());
//            JSONObject jsonObject = JSONObject.parseObject(str);
//            userInfo = sysLoginService.login(jsonObject.getString("username"), jsonObject.getString("password"));
            userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
            //保存用户openid
            if (StringUtils.isNotEmpty(form.getOpenid())) {
//                String s = RsaUiUtils.decryptByPrivateKey(form.getOpenid());
//                form.setOpenid(s);
                sysLoginService.updateOpenId(userInfo, form);
            }
        } else if ("sms".equals(form.getFlag())) {
            //短信登录openid，phone，smsCode必传(openid不能使用，存在他人手机号登录别人账号场景)
//            String s = RsaUiUtils.decryptByPrivateKey(form.getSmsCode());
//            form.setSmsCode(s);
            userInfo = sysLoginService.Smslogin(form);
        } else {
//            String s = RsaUiUtils.decryptByPrivateKey(form.getEncrypt());
//            JSONObject jsonObject = JSONObject.parseObject(s);
//            userInfo = sysLoginService.login(jsonObject.getString("username"), jsonObject.getString("password"));
            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;
    }

    @PostMapping("/redisSet")
    public R<?> redisSet(@RequestBody JSONObject js) {
        tokenService.redisSet(js.getString("key"), js.getString("value"));
        return R.ok();
    }

    @PostMapping("/redisGet")
    public R<?> redisGet(@RequestBody JSONObject js) {
        return R.ok(tokenService.redisGet(js.getString("key")));
    }

    @PostMapping("/redisDel")
    public R<?> redisDel(@RequestBody JSONObject js) {
        tokenService.redisDel(js.getString("key"));
        return R.ok();
    }

}
