package com.example.demo.module.captcha;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.CacheMapRoot;
import com.example.demo.common.MD5Tool;
import com.example.demo.common.RequestResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pers.jc.util.JCLogger;

import java.util.Random;

@CrossOrigin
@RestController
@RequestMapping("/phoneValidate")
public class PhoneValidateController {

    @PostMapping("/sendPhoneValidateCode")
    public RequestResult sendPhoneValidateCode(String phone, int language) {
        int validateCode = new Random().nextInt(900000) + 100000;
        boolean success = SendSms.ins.sendValidateCode(phone, validateCode, 10);
        RequestResult requestResult = new RequestResult();
        if (success) {
            CacheMapRoot.validatePhone.put(phone, validateCode, System.currentTimeMillis() + 10 * 60 * 1000);
            JCLogger.info("手机验证发送", phone, validateCode);
        } else {
            requestResult.setFailCode();
        }
        return requestResult;
    }

    @PostMapping("/validatePhone")
    public RequestResult validatePhone(String phone, int code) {
        Integer validateCode = CacheMapRoot.validatePhone.get(phone, Integer.class);
        RequestResult requestResult = new RequestResult();
        if (validateCode == null || validateCode != code) {
            requestResult.setFailCode();
            return requestResult;
        }
        CacheMapRoot.validatePhone.remove(phone, code);
        JSONObject data = new JSONObject();
        long timestamp = System.currentTimeMillis();
        data.put("phone", phone);
        data.put("timestamp", timestamp);
        data.put("sign", MD5Tool.makeMD5(phone + "~happy~" + timestamp));
        requestResult.setData(data);
        return requestResult;
    }
}
