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

@RestController
@RequestMapping("/api")
public class PhoneSendCodeController {
    @Resource
    PhoneMapper phoneMapper;
    @Autowired
    private SmsBaoConfig smsBaoConfig; // 注入配置类

    @PostMapping("/sendCode")
    public ResponseEntity<ApiResponse> sendCode(@RequestParam String Phone) {
        // 验证手机号码的有效性，可以根据需要添加更多的验证逻辑
        if (!isValidPhoneNumber(Phone)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(new ApiResponse(null, HttpStatus.BAD_REQUEST.value(), "不合法的数字"));
        }
        // 生成随机验证码
        String randomCode = generateRandomCode();

        // 调用发送短信的方法，将随机验证码发送给指定的手机号码
        boolean sendStatus = sendSms(Phone, randomCode);

        if (sendStatus) {
            return ResponseEntity.ok(new ApiResponse(null, HttpStatus.OK.value(), "验证码发送成功"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(null, HttpStatus.INTERNAL_SERVER_ERROR.value(), "验证码发送失败"));
        }
    }

    private boolean isValidPhoneNumber(String Phone) {
        // 简单的手机号码验证，只检查长度和是否只包含数字
        if (Phone == null || Phone.length() != 11 || !Phone.matches("\\d+")) {
            return false;
        }
        return true;
    }

    private String generateRandomCode() {
        // 生成一个四位数的随机数字验证码
        Random random = new Random();
        int code = random.nextInt(9000) + 1000; // 生成1000到9999之间的随机数
        return String.valueOf(code);
    }

    private boolean sendSms(String Phone, String code) {
        try {
            String username = smsBaoConfig.getUsername();
            String password = smsBaoConfig.getPassword();
            String content = "【曙光网络】您的验证码为" + code + "在30分钟内有效。";

            // 构造短信宝的API URL
            String smsBaoUrl = "http://api.smsbao.com/sms";
            String httpArg = "u=" + username + "&p=" + md5(password) + "&m=" + Phone + "&c=" + encodeUrlString(content, "UTF-8");

            // 发送HTTP请求
            String result = request(smsBaoUrl, httpArg);

            // 解析短信宝的响应并判断是否发送成功
            if (result != null && result.equals("0")) {
                // 发送成功，保存验证码到数据库
                saveVerificationCode(Phone, code);
                return true; // 发送成功
            } else {
                return false; // 发送失败
            }
        } catch (Exception e) {
            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 e) {
            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();
            int i;
            buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

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

    // 保存验证码与手机号到数据库中
    private void saveVerificationCode(String Phone, String code) {
        Phone phone = new Phone();
        phone.setPhone(Phone);
        phone.setCode(code);
        // 调用 phoneMapper 的保存方法保存手机号和验证码到数据库
        phoneMapper.save(phone);
    }

}
