package com.cmeeting.ad.controller;

import com.alibaba.fastjson.JSONObject;
import com.cmeeting.ad.service.UserService;
import com.cmeeting.ad.vo.UserVo;
import com.cmeeting.annotation.OperLog;
import com.cmeeting.constant.RecordTemplateConstant;
import com.cmeeting.util.AESUtils;
import com.cmeeting.util.IPUtils;
import com.cmeeting.util.R;
import com.cmeeting.ad.vo.ApplicationUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Value("${aec.key}")
    private String aseKey;

    /**
     * 账号密码登录
     *
     * @param vo
     * @return
     */
    @CrossOrigin
    @PostMapping("/login")
    public R login(@RequestBody @Validated ApplicationUserVO.LoginDecrypt vo, HttpServletRequest request) {
        String ipAddr = IPUtils.getIpAddr(request);
        return userService.login(vo.getAgentId(), vo.getData(), ipAddr);
    }


    /**
     * 角色扮演进入系统接口
     * @param vo
     * @return
     */
    @OperLog(location = "角色扮演页面", operation = "进入系统")
    @PostMapping(value = "/userAuth")
    public R userAuth(@Validated @RequestBody UserVo.Auth vo) {
        return R.ok(userService.auth(vo.getId(), vo.getNick(), RecordTemplateConstant.TEMPLATE_TYPE_CUSTOM));
    }

    /**
     * 用户使用
     * @param vo
     * @return
     */
    @PostMapping(value = "/tokenAuth")
    public R tokenAuth(@Validated @RequestBody ApplicationUserVO.LoginDecrypt vo) {
        try {
            Object token = userService.tokenAuth(vo);
            return R.ok(token);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    @PostMapping(value = "/emailAuth")
    public R emailAuth(@Validated @RequestBody UserVo.LoginDecrypt vo) {
        try {
            Object token = userService.tokenAuth(vo.getData());
            return R.ok(token);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
//        String decrypt = AESUtils.decrypt(vo.getData(), aseKey);
//        UserVo.Auth auth = JSONObject.parseObject(decrypt, UserVo.Auth.class);
//        return R.ok(userService.emailAuth(auth));
    }
}