package com.example.system.controller;

import com.example.system.model.ArticleTable;
import com.example.system.model.UserTable;
import com.example.system.repository.ArticleRepository;
import com.example.system.repository.RegistrationRepository;
import com.example.system.advice.SmsBaoConfig;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.RowSet;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Optional;
import org.springframework.web.bind.annotation.CrossOrigin;
@CrossOrigin
@RestController
public class PhoneSendCodeController {

    @Autowired
    private SmsBaoConfig smsBaoConfig;

    @Autowired
    private RegistrationRepository registrationRepository;

    @Autowired
    private ArticleRepository articleRepository;

    // 发送文章简介给参赛者
    @PostMapping("/api/sendsms")
    public ResponseEntity<String> sendArticleBriefToParticipants(@RequestParam Long competitionId, @RequestParam Integer articleId) {
//        // 根据文章ID查找文章
        Optional<ArticleTable> articleOpt = articleRepository.findById(articleId);
        if (articleOpt.isEmpty()) {
            return new ResponseEntity<>("未找到公告", HttpStatus.NOT_FOUND);
        }
        ArticleTable article = articleOpt.get();

        // 根据竞赛ID查找参赛者
        List<String> phone = registrationRepository.findByCompetitionId(competitionId);
        if (phone.isEmpty()) {
            return new ResponseEntity<>("未找到参加比赛的用户", HttpStatus.NOT_FOUND);
        }

        // 获取文章简介内容
        String briefContent = article.getBriefContent();
        String ArticleTitle = article.getArticleTitle();
        // 遍历参赛者并发送短信
        for (String i : phone) {
            if (i != null && !i.isEmpty()) {
                boolean sendStatus = sendSms(i, "【计算机社团】您参加的 ["+ArticleTitle+"] 比赛有新的公告内容：\n" + briefContent +"\n请前往管理平台查看。");
                if (!sendStatus) {
                    System.out.println("Failed to send SMS to: " + i);
                }
            }
        }

        return new ResponseEntity<>("短信发送成功", HttpStatus.OK);
    }

    // 发送短信
    private boolean sendSms(String phone, String content) {
        try {
            String username = smsBaoConfig.getUsername();
            String password = smsBaoConfig.getPassword();
            String encodedContent = encodeUrlString(content, "UTF-8");

            String smsBaoUrl = "http://api.smsbao.com/sms";
            String httpArg = "u=" + username + "&p=" + md5(password) + "&m=" + phone + "&c=" + encodedContent;

            String result = request(smsBaoUrl, httpArg);
            return "0".equals(result);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 发起 HTTP 请求
    private String request(String smsBaoUrl, String httpArg) {
        StringBuilder result = new StringBuilder();
        smsBaoUrl = smsBaoUrl + "?" + httpArg;

        try {
            URL url = new URL(smsBaoUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead;
            while ((strRead = reader.readLine()) != null) {
                result.append(strRead);
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    // 计算 MD5 值
    private String md5(String password) {
        StringBuilder buf = new StringBuilder();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(password.getBytes());
            byte[] b = md.digest();
            for (byte value : b) {
                int i = value;
                if (i < 0) i += 256;
                if (i < 16) buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    // 对字符串进行 URL 编码
    private String encodeUrlString(String content, String charset) {
        String strret = null;
        if (content == null) return content;
        try {
            strret = java.net.URLEncoder.encode(content, charset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return strret;
    }
}
