package com.template.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.template.annotation.DESRespondSecret;
import com.template.annotation.PassToken;
import com.template.api.LogInfoControllerAPI;
import com.template.common.utils.AesUtils;
import com.template.common.utils.JWTUtil;
import com.template.model.pojo.SmartUser;
import com.template.model.pojo.SmsCode;
import com.template.model.pojo.SystemUser;
import com.template.model.result.CommonResult;
import com.template.model.vo.LoginVO;
import com.template.services.SmartUserService;
import com.template.services.impl.SmsCodeServiceImpl;
import com.template.services.impl.SystemUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
//返回参数加密注解
@DESRespondSecret
public class LogInfoController implements LogInfoControllerAPI {


    @Autowired
    SystemUserServiceImpl systemUserService;

    @Autowired
    SmsCodeServiceImpl smsCodeService;

    @Autowired
    SmartUserService smartUserService;

    @Override
    @PassToken
    @DESRespondSecret(validated = true)
    public CommonResult verifyPhone(@RequestParam String phone) {
        return CommonResult.ok();
    }

    @Override
    @PassToken
    @DESRespondSecret(validated = true)
    public CommonResult logInfo(String phone, String code) {
        return smsCodeService.logIn(phone, code);
    }

    @Override
    @PassToken
    public CommonResult verification(String phone, String code) {
        QueryWrapper<SmsCode> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("deleted", 0);
        queryWrapper1.eq("is_verify", 0);
        queryWrapper1.eq("phone_number", phone);
        queryWrapper1.eq("code", code);
        queryWrapper1.isNull("method");
        queryWrapper1.ge("expiration_time", new Date());
        List<SmsCode> listc = smsCodeService.getSmsCodeByKey(queryWrapper1);
        if (listc.isEmpty()) {
            return CommonResult.ok("验证码已失效");
        }
//        核销验证码
        for (SmsCode smsCode : listc) {
            smsCode.setIsVerify("1");
            smsCodeService.updateSmsCode(smsCode);
        }
        // 登录成功，生成token
        LambdaQueryWrapper<SmartUser> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(SmartUser::getPhone, phone);
        SmartUser one1 = smartUserService.getOne(wrapper2);
        long expired = 1000 * 60 * 60 * 24;
        String token = JWTUtil.getToken(one1,expired);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", token);
        jsonObject.put("user", one1);
        jsonObject.put("userhead", AesUtils.encrypt(String.valueOf(one1.getId())));
        return CommonResult.ok(jsonObject);
    }
}
