package com.jpsoft.shinestar.modules.common.controller;

import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.utils.DES3;
import com.jpsoft.shinestar.modules.common.utils.JwtUtil;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class JwtsUserController {
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Autowired
    private UserService userService;

    @Autowired
    private ValueOperations<String,Object> valueOperations;

    /**
     * 接收扫码登录回调
     * @param eventKey
     * @param openId
     * @return 返回值会在微信中显示
     */
    @ApiOperation(value = "接收扫码登录回调")
    @PostMapping(value="/qrcode/scanLogin")
    @ResponseBody
    public MessageResult<String> scanLogin(String eventKey,String openId){
        MessageResult<String> messageResult = new MessageResult<>();
        log.warn(openId + "请求登录!");
        String result;

        User user = userService.findByOpenId(openId);

        if(user!=null) {
            String[] arr = eventKey.split(",");
            String randNum = arr[1];

            long expireSeconds = 3000; //5分钟

            //生成token
            String token = JwtUtil.createToken(jwtSecret,user.getId(),DateTime.now().plusHours(6).toDate());

            valueOperations.set("scan_qrcode_login_" + randNum, token, expireSeconds, TimeUnit.SECONDS);
            messageResult.setMessage("扫码登录成功!");
            messageResult.setResult(true);
        }
        else{
            messageResult.setMessage("当前用户未绑定微信!");
            messageResult.setResult(false);
        }

        return messageResult;
    }

    @PostMapping("/qrcode/queryScanResult")
    @ApiOperation(value="查询扫码结果")
    public MessageResult<String> queryScanResult(String rnd){
        MessageResult<String> messageResult = new MessageResult<>();

        try {
            String data = (String)valueOperations.get("scan_qrcode_login_" + rnd);

            if(StringUtils.isNotEmpty(data)) {
                messageResult.setData(data);
                messageResult.setResult(true);
            }
            else{
                messageResult.setResult(false);
                messageResult.setMessage("暂无扫码结果");
            }
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);

            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("/login")
    @ApiOperation(value="登录获取token,在swagger ui中获取token时将写入session，调用其它接口时不用再设置header")
    @ApiImplicitParams({
            @ApiImplicitParam(name="userName", paramType="query", required=true, value="用户名"),
            @ApiImplicitParam(name="password", paramType="query", required=true, value="密码")
    })
    public MessageResult<String> login(String userName, String password, @ApiIgnore HttpSession session){
        MessageResult<String> messageResult = new MessageResult<>();

        try {
            User user = userService.findByUserName(userName);

            DES3 des3 = new DES3();

            String passwordEnc = des3.encrypt(jwtSecret,password);

            if(user!=null && passwordEnc.equals(user.getPassword())){

                //生成token
                String token = JwtUtil.createToken(jwtSecret,user.getId(),DateTime.now().plusHours(6).toDate());

                session.setAttribute("token",token);

                messageResult.setResult(true);
                messageResult.setData(token);
            }
            else{
                messageResult.setResult(false);
                messageResult.setMessage("用户不存在或密码错误！");
            }

        }
        catch(Exception ex){
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @GetMapping("/userInfo")
    public MessageResult<User> userInfo(@RequestAttribute String subject){
        MessageResult<User> messageResult = new MessageResult<>();

        try {
            User user = userService.get(subject);

            messageResult.setResult(true);
            messageResult.setData(user);
        }
        catch(Exception ex){
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }
}
