//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.luozhihui.project.controller;

import com.luozhihui.project.common.ApiResponse;
import com.luozhihui.project.common.SmsBaoConfig;
import com.luozhihui.project.entity.Phone;
import com.luozhihui.project.mapper.PhoneMapper;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin
@RequestMapping({"/api"})
public class PhoneSendCodeController {
    @Resource
    PhoneMapper phoneMapper;
    @Autowired
    private SmsBaoConfig smsBaoConfig;

    public PhoneSendCodeController() {
    }

    @PostMapping({"/sendCode"})
    public ResponseEntity<ApiResponse> sendCode(@RequestParam String Phone) {
        if (!this.isValidPhoneNumber(Phone)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ApiResponse((Object)null, HttpStatus.BAD_REQUEST.value(), "不合法的数字"));
        } else {
            String randomCode = this.generateRandomCode();
            boolean sendStatus = this.sendSms(Phone, randomCode);
            return sendStatus ? ResponseEntity.ok(new ApiResponse((Object)null, HttpStatus.OK.value(), "验证码发送成功")) : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ApiResponse((Object)null, HttpStatus.INTERNAL_SERVER_ERROR.value(), "验证码发送失败"));
        }
    }

    private boolean isValidPhoneNumber(String Phone) {
        return Phone != null && Phone.length() == 11 && Phone.matches("\\d+");
    }

    private String generateRandomCode() {
        Random random = new Random();
        int code = random.nextInt(9000) + 1000;
        return String.valueOf(code);
    }

    private boolean sendSms(String Phone, String code) {
        try {
            String username = this.smsBaoConfig.getUsername();
            String password = this.smsBaoConfig.getPassword();
            String content = "【曙光网络】您的验证码为" + code + "在30分钟内有效。";
            String smsBaoUrl = "http://api.smsbao.com/sms";
            String httpArg = "u=" + username + "&p=" + this.md5(password) + "&m=" + Phone + "&c=" + this.encodeUrlString(content, "UTF-8");
            String result = this.request(smsBaoUrl, httpArg);
            if (result != null && result.equals("0")) {
                this.saveVerificationCode(Phone, code);
                return true;
            } else {
                return false;
            }
        } catch (Exception var9) {
            Exception e = var9;
            e.printStackTrace();
            return false;
        }
    }

    private String request(String smsBaoUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        smsBaoUrl = smsBaoUrl + "?" + httpArg;

        try {
            URL url = new URL(smsBaoUrl);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = reader.readLine();
            if (strRead != null) {
                sbf.append(strRead);

                while((strRead = reader.readLine()) != null) {
                    sbf.append("\n");
                    sbf.append(strRead);
                }
            }

            reader.close();
            result = sbf.toString();
        } catch (Exception var10) {
            Exception e = var10;
            e.printStackTrace();
        }

        return result;
    }

    private String md5(String password) {
        StringBuffer buf = null;

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            byte[] b = md.digest();
            buf = new StringBuffer("");

            for(int offset = 0; offset < b.length; ++offset) {
                int i = b[offset];
                if (i < 0) {
                    i += 256;
                }

                if (i < 16) {
                    buf.append("0");
                }

                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException var7) {
            NoSuchAlgorithmException e = var7;
            e.printStackTrace();
        }

        return buf.toString();
    }

    private String encodeUrlString(String content, String charset) {
        String strret = null;
        if (content == null) {
            return content;
        } else {
            try {
                strret = URLEncoder.encode(content, charset);
            } catch (UnsupportedEncodingException var5) {
                UnsupportedEncodingException e = var5;
                e.printStackTrace();
            }

            return strret;
        }
    }

    private void saveVerificationCode(String Phone, String code) {
        Phone phone = new Phone();
        phone.setPhone(Phone);
        phone.setCode(code);
        this.phoneMapper.save(phone);
    }
}
